gpt4 book ai didi

python - 为什么我的移动功能在 pygame 中不起作用?

转载 作者:行者123 更新时间:2023-12-05 01:23:00 29 4
gpt4 key购买 nike

IDK 为什么我的 player.move() 不工作这是我的主类:

import pygame
from player import *

pygame.init()

WIDTH, HEIGHT = 900, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("MyGame!")

FPS = 60

player_x = 500
player_y = 500
PLAYER_WIDTH = 60
PLAYER_HEIGHT = 60
PLAYER_VEL = 5

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

keys_pressed = pygame.key.get_pressed()

player_rect = pygame.Rect(player_x, player_y, PLAYER_WIDTH, PLAYER_HEIGHT)
player = Player(player_rect, BLACK, WIN, keys_pressed, PLAYER_VEL)

def draw_window():
WIN.fill(WHITE)
pygame.display.update()

def main():
run = True
clock = pygame.time.Clock()

while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

draw_window()
player.move()
player.draw_player()

pygame.display.update()

pygame.quit()

if __name__ == '__main__':
main()

这是我的另一个名为 player.py 的类,移动功能不起作用:导入pygame

class Player(object):
def __init__(self, player, color, surface, keys_pressed, vel):
self.player = player
self.color = color
self.surface = surface
self.keys_pressed = keys_pressed
self.vel = vel

def draw_player(self):
pygame.draw.rect(self.surface, self.color, self.player)
pygame.display.update()

def move(self):
if self.keys_pressed[pygame.K_a]:
self.player.x -= self.vel

if self.keys_pressed[pygame.K_d]:
self.player.x += self.vel

我尝试将 player = Player(...) 放在 main 函数之前。但是无论我尝试过什么,它似乎都不起作用,这是我第一次在 stackoverflow 上发帖提问。这个问题在过去也发生过很多次,所以感谢你帮助我。

最佳答案

pygame.key.get_pressed()返回包含每个键状态的序列。如果按住某个键,则该键的状态为 1,否则为 0。当键的状态改变时,keys_pressed 列表的内容不会神奇地改变。 keys_pressed 与按键无关。您需要在每一帧中获取键的新状态:

class Player(object):
# [...]

def move(self):

# get current state of the keys
self.keys_pressed = pygame.key.get_pressed()

if self.keys_pressed[pygame.K_a]:
self.player.x -= self.vel

if self.keys_pressed[pygame.K_d]:
self.player.x += self.vel

关于python - 为什么我的移动功能在 pygame 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72983671/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com