我最近开始用Python和Pygame模块编程。我正在尝试做一个游戏,玩家一个街区一个街区地移动,但是我不知道从哪里开始碰撞检测。你知道吗
例如,运动员应该能够在草地上移动,但不能下水。到目前为止,我的情况是:
import pygame as pg, sys
# Frames
clock = pg.time.Clock()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Tile declarations
GRASS = 0
WATER = 1
# Tile colors
colors = {
GRASS: GREEN,
WATER: BLUE
}
# Tile dimensions
tileWidth = 50
tileHeight = 50
# Map
tileSet = [
[GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, GRASS, WATER, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, WATER, WATER, WATER, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, WATER, WATER, WATER, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, WATER, WATER, WATER, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, GRASS, WATER, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS],
[GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS, GRASS]
]
# Map dimensions
mapWidth = 12
mapHeight = 9
# Screen dimensions
screenWidth = tileWidth * mapWidth
screenHeight = tileHeight * mapHeight
# Set up display
pg.init()
win = pg.display.set_mode((screenWidth, screenHeight))
class Player(pg.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.image = pg.Surface([tileWidth, tileHeight])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def map_gen():
for row in range(mapHeight):
for elementInRow in range(mapWidth):
pg.draw.rect(win, colors[tileSet[row][elementInRow]], [elementInRow * tileWidth, row * tileHeight, tileWidth, tileHeight])
def main():
sprite_list = pg.sprite.Group()
player = Player(0, 0, RED)
sprite_list.add(player)
# Game loop variable
running = True
while running:
# Inputs
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_w:
player.rect.y -= tileHeight
if event.key == pg.K_a:
player.rect.x -= tileWidth
if event.key == pg.K_s:
player.rect.y += tileHeight
if event.key == pg.K_d:
player.rect.x += tileWidth
# Map
map_gen()
sprite_list.update()
sprite_list.draw(win)
pg.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
有什么想法吗?你知道吗
有了地图后,可以将字符位置存储为
x, y
坐标,并检查要移动到的磁贴是否属于指定类型:例如:
小心coordinates system
相关问题 更多 >
编程相关推荐