开始制作游戏,一切正常,但随后移动功能停止工作



我找不到我更改的内容,因此我的移动功能不再起作用,它以前运行良好。我没有收到任何错误,它只是根本不移动。 对不起,如果代码真的很草率。 大多数缩进错误可能是因为我格式化错误(这是我第一次使用stackoverflow(。

import pygame
pygame.init()
work = True
b_y = 425
key = pygame.key.get_pressed()
newWindow = pygame.display.set_mode((500, 500))
pygame.display.set_caption("NewFile")
class player:
def __init__(self, vel, x):
self.x = x
self.vel = vel
def playerdraw(self):
pygame.draw.rect(newWindow, (255, 255, 255),  (p1.x, 425,
40,20))
def  move(self):
if key[pygame.K_LEFT] and p1.x>5:
p1.x -=  self.vel
elif key[pygame.K_RIGHT] and p1.x < 455:
p1.x += self.vel  

p1 = player(2, 250)
b_x = p1.x
while work:
for event in pygame.event.get():
if event.type == pygame.QUIT:
work= False
newWindow.fill((0, 0, 0))
p1.move()
p1.playerdraw()
pygame.display.update()

pygame.quit()

我需要玩家移动

您需要在每个循环中读取get_pressed键函数

def  move(self):
key = pygame.key.get_pressed() # You need to read the get_pressed key function on each loop
if key[pygame.K_LEFT] and p1.x>5:
p1.x -=  self.vel
elif key[pygame.K_RIGHT] and p1.x < 455:
p1.x += self.vel  

完整代码

import pygame
pygame.init()
work = True
b_y = 425
key = pygame.key.get_pressed()
newWindow = pygame.display.set_mode((500, 500))
pygame.display.set_caption("NewFile")
class player:
def __init__(self, vel, x):
self.x = x
self.vel = vel
def playerdraw(self):
pygame.draw.rect(newWindow, (255, 255, 255),  (p1.x, 425,
40,20))
def  move(self):
key = pygame.key.get_pressed() # You need to read the get_pressed key function on each loop
if key[pygame.K_LEFT] and p1.x>5:
p1.x -=  self.vel
elif key[pygame.K_RIGHT] and p1.x < 455:
p1.x += self.vel  

p1 = player(2, 250)
b_x = p1.x
while work:
for event in pygame.event.get():
if event.type == pygame.QUIT:
work= False
newWindow.fill((0, 0, 0))
p1.move()
p1.playerdraw()
pygame.display.update()

pygame.quit()

你必须在主游戏循环中连续设置key

while work:
# [...]
key = pygame.key.get_pressed()

请注意,您已在应用程序开始时初始化了key,但错过了更新它。存储在列表key全局名称空间中的键的状态在类player的方法move()中计算。
pygame.key.get_pressed()返回一个布尔值列表,表示每个键的状态。计算(键(事件时,将更新键的内部状态。之后,pygame.key.get_pressed()将返回新的和实际的值。

最新更新