当我按下向上键时,我不明白为什么矩形没有改变它的位置。我没有收到任何错误,一切都在显现。
导入pygame 来自pygame.locals import *
class SnekHead(object):
def __init__(self, screensize):
self.screensize = screensize
self.center_x = int(screensize[0]*0.5)
self.center_y = int(screensize[1]*0.5)
self.width = 50
self.height = 50
self.rect = pygame.Rect(self.center_x-25, self.center_y-50, self.width, self.height)
self.color = (100, 255, 100)
self.speed = 10
self.direction = 0
def update(self):
self.center_y += self.direction*self.speed
def render(self, screen):
pygame.draw.rect(screen, self.color, self.rect, 0)
def run_game(): pygame.init()
screensize = (640, 480)
background_image = pygame.image.load('Sky_back_layer.png')
screen = pygame.display.set_mode(screensize)
clock = pygame.time.Clock()
snake = SnekHead(screensize)
running = True
while running:
clock.tick(64)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.key == K_UP:
snake.direction = -1
snake.update()
screen.blit(background_image, (0, 0))
snake.render(screen)
pygame.display.flip()
pygame.quit()
run_game()
答案 0 :(得分:0)
问自己这个问题。按下键后self.rect
的值是多少? (按下键时,您递减snake.direction
,然后更新snake.center_y
,但snake.rect
保持不变,矩形的位置也是如此,因为这是您传递给{{1}的位置。 1}}在你的pygame.draw.rect()
函数中)