IDK为什么是我的球员.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移动功能不工作:

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(…)在主功能之前.

推荐答案

pygame.key.get_pressed()返回每个键的状态序列.如果按下 keys ,则 keys 的状态为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相关问答推荐

Pandas 密集排名具有相同值,按顺序排列

如何从同一类的多个元素中抓取数据?

在Python中使用readline函数时如何向下行

为什么基于条件的过滤会导致pandas中的空数据框架?

从今天起的future 12个月内使用Python迭代

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

如何通过多2多字段过滤查询集

Python中使用时区感知日期时间对象进行时间算术的Incredit

在函数内部使用eval(),将函数的输入作为字符串的一部分

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

_repr_html_实现自定义__getattr_时未显示

海运图:调整行和列标签

Python虚拟环境的轻量级使用

如何在Python中找到线性依赖mod 2

使用groupby方法移除公共子字符串

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

Python Pandas获取层次路径直到顶层管理

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送