Pygame- Pong- 按 w 或 s 时矩形不移动

Pygame- Pong- rectangle doesnt move while pressing w or s

Pygame -Pong- 矩形在按下 ws

时不会移动

我只是不明白为什么它不动请帮助我在 python :3

import pygame
import sys
import numpy as np


class Game( ):
    def __init__(self):
        pygame.init( )

        self.player_x = 75
        self.player_y = 300
        self.player1_x = 1100
        self.player1_y = 300
        self.screen = pygame.display.set_mode((1200, 800))
        pygame.display.set_caption("Pong")
        self.FPS = pygame.time.Clock( )
        self.player_speed = 0

        self.width = 25
        self.hight = 100
        self.speed = 5


        self.game_loop()

    def game_loop(self):
        while True:
            self.FPS = pygame.time.Clock()

            for event in pygame.event.get( ):
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_w:
                        self.player_speed -= 7
                    if event.key == pygame.K_s:
                        self.player_speed += 7

            self.screen.fill((0, 0, 0))
            self.Player_1()

            self.player.y += self.player_speed
            self.player1.y += self.player_speed



            pygame.display.flip()
            self.FPS.tick(60)




    def Player_1(self):

        self.player = pygame.Rect(self.player_x, self.player_y, self.width, self.hight)
        self.player1 = pygame.Rect(self.player1_x, self.player1_y, self.width, self.hight)
        pygame.draw.rect(self.screen, "Red", self.player)
        pygame.draw.rect(self.screen, "Red", self.player1)


Game( )

您将玩家道具定义为:

self.player_x = 75
self.player_y = 300
self.player1_x = 1100
self.player1_y = 300

但是你正在设置:

self.player.y += self.player_speed
self.player1.y += self.player_speed

其中一个:

AttributeError: 'Game' object has no attribute 'player'


所以把上面的改成:

self.player_y += self.player_speed
self.player1_y += self.player_speed

矩形将在 ws 上移动。