PyGame桨板不动

时间:2018-11-15 02:42:52

标签: python-3.x pygame

在控制台上可以很好地注册关键事件。另外,我的桨出现了,这表明从另一个文件调用的桨类有效。但是,我希望当按下向左箭头键或向右箭头键时,桨板能够平稳移动,因此用户不必重复单击。但是,使用我当前的代码,桨板根本不会移动。我试图改变if / else语句的位置,将位置更改为无济于事。我在这里做什么错了?

主要游戏:

import pygame
from pygame.locals import *

from Config import Config 
from Paddle import Paddle

pygame.init()

#--Display settings
pygame.display.set_caption(Config['game']['caption'])
game_display = pygame.display.set_mode((Config['game']['display_width'], 
Config['game']['display_height']))
clock = pygame.time.Clock()
paddle= Paddle(game_display)

x_change = 0
pressed_left = False
pressed_right = False

def event_handler():
for event in pygame.event.get():
    print (event)
    if (event.type == QUIT) or (event.type == KEYDOWN and event.key == 
K_ESCAPE):
        pygame.quit()
        quit()

    #To move the paddle to the left and right
    if event.type == KEYDOWN:
        if event.key == K_LEFT:
            pressed_left = True  
        elif event.key== K_RIGHT:
            pressed_right = True

    #If the key is up
    if event.type == KEYUP:
        if event.key == K_LEFT:
            pressed_left = False
            x_change = 0
        elif event.key == K_RIGHT:
            pressed_right = False 
            x_change = 0

#--This changes the position
if pressed_left:
    x_change = -5
if pressed_right:
    x_change = 5

while True:
    event_handler()
    game_display.fill(Config['colors']['white'])
    paddle.draw()
    paddle.movement(x_change)

    pygame.display.update()
    clock.tick(Config['game']['fps'])

在我的包含Paddle类的paddle.py中:

import pygame
from pygame.locals import *

from Config import Config

class Paddle:
    def __init__(self, game_display):
        self.x = (Config['game']['display_width'] * 0.45)
        self.y = (Config['game']['display_height'] * 0.92)
        self.game_display=game_display


    def draw(self):
        pygame.draw.rect(self.game_display, Config['colors']['red'], 
[self.x, self.y, 40, 25])

    def movement(self, x_change):
        self.x += x_change

2 个答案:

答案 0 :(得分:1)

让我们看一个简单的例子。尝试运行该程序。

pressed_left = False
def event_handler():
    pressed_left = True

event_handler()

print(pressed_left)

当您希望程序打印True时,它将打印False。发生这种情况的原因是python中变量作用域的工作方式。当您尝试修改未在该函数本身中定义的函数中的变量时,python会定义一个新变量,而不是寻找全局变量。 因此,pressed_left = True中的event_handler()行仅创建一个新的pressed_left变量,该变量仅存在于event_handler函数中,而无需修改全局变量。

要解决此问题,您需要在函数中将变量声明为global。尝试运行该程序。

pressed_left = False
def event_handler():
    global pressed_left
    pressed_left = True

event_handler()

print(pressed_left)

答案 1 :(得分:0)

将您的密钥更改为类似的内容

key = pygame.key.pressed()

if key[pygame.K_left]:
    pygame movement