0

我目前正在尝试使用 Pygame 创建一个简单版本的 Breakout 游戏。问题是我想让我的球棒在屏幕上移动,为此我需要处理事件以及当你按下右/左箭头时球棒立即右/左移动的事实。但是我的代码不起作用;每当我按下键时,球棒的长度就会增加,而不是简单地移动。我已经浏览了代码和示例,但我仍然迷路了。

这是我的代码:

import pygame, sys

pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode([width, height])
bat_speed = 30
bat = pygame.image.load('bat.png').convert()
batrect = bat.get_rect()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:                        
                batrect = batrect.move(-bat_speed, 0)     
                if (batrect.left < 0):                           
                    batrect.left = 0      
            if event.key == pygame.K_RIGHT:                    
                batrect = batrect.move(bat_speed, 0)
                if (batrect.right > width):                            
                    batrect.right = width

    screen.blit(bat, batrect)
    pygame.display.flip()

pygame.quit()
4

1 回答 1

0

当您在屏幕上粘贴某些内容时,它会停留在那里。正在发生的事情是,您在不同的位置对球棒进行击球,使球棒的宽度看起来好像在增加。简单的解决方法是在绘制蝙蝠之前清除屏幕。

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:                        
                batrect = batrect.move(-bat_speed, 0)     
                if (batrect.left < 0):                           
                    batrect.left = 0      
            elif event.key == pygame.K_RIGHT:                    
                batrect = batrect.move(bat_speed, 0)
                if (batrect.right > width):                            
                    batrect.right = width

    screen.fill((0, 0, 0))  # This will fill the screen with a black color.
    screen.blit(bat, batrect)
    pygame.display.flip()

此外,当您不想检查每个条件时,请使用elif而不是多个,就像我在上面所做的那样。if

于 2017-01-28T23:38:33.383 回答