【发布时间】:2016-11-13 04:35:04
【问题描述】:
我正在使用 python 2.7 并尝试使用 pygame 模块制作一个简单的游戏。在程序中,它制作了一个矩形,而我遇到的麻烦是让它在按键被按下时移动。我相信问题出在我的代码中的“player.move”部分,但 pygames 网站上的文档很差。任何帮助表示赞赏。
import pygame
import random
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
displayWidth = 800
displayHeight = 800
FPS = 30
clock = pygame.time.Clock()
blockWidth = 50
blockHeight = 50
pygame.display.set_caption('Test Game')
screen = pygame.display.set_mode([displayWidth, displayHeight])
background = pygame.Surface(screen.get_size())
background.fill((white))
background = background.convert()
screen.blit(background, (0,0))
global xStart, yStart
xStart = 400
yStart = 400
global player
player = pygame.draw.rect(screen, black, ([xStart,yStart,blockWidth,blockHeight]))
pygame.display.update()
def mainloop():
global x, y
x = xStart
y = yStart
mainloop = True
pygame.display.update()
while mainloop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_UP:
player.move(x, y + 10)
pygame.display.update()
if event.key == pygame.K_DOWN:
player.move(x, y - 10)
pygame.display.update()
if event.key == pygame.K_LEFT:
player.move(x - 10, y)
pygame.display.update()
if event.key == pygame.K_RIGHT:
player.move(x + 10, y)
pygame.display.update()
clock.tick(FPS)
pygame.display.flip()
mainloop()
pygame.quit()
【问题讨论】:
-
pygame.draw.rect()用于绘制矩形,而不用于创建对象。在while True中,您必须清除屏幕并在新位置绘制矩形 - 一次又一次。现在您更改了玩家位置,但您不会在新位置再次绘制它。 PyGame 是低级库,您必须自己完成所有操作 - 它不会自动移动和绘制。 -
最好找到一些教程 - 即。 Program Arcade Games With Python And Pygame
-
@Austin ,也尝试阅读我们在pygame.上的测试版文档
标签: python python-2.7 pygame