代码运行时播放器不显示?

Player not displaying when the code runs?

代码有一些错误,但我不明白。我试图搜索它们,但一无所获!

错误是:

  File "d:\Python\sendsend\client.py", line 67, in <module>
    main()
  File "d:\Python\sendsend\client.py", line 64, in main
    redrawWindow(win,p)
  File "d:\Python\sendsend\client.py", line 50, in redrawWindow
    pygame.display.update()

密码是:

import pygame

                                                    
width = 500
height = 500
win = pygame.display.set_mode ((width, height))
pygame.init()
pygame.display.set_caption("Client")

clientNumber = 0

class Player:
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = (x,y,width,height)
        self.val = 3
    
    def draw(self,win):
        pygame.init()
        pygame.draw.rect(win, self.color, self.rect)

    def move(self):
        pygame.init()
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.x -= self.vel

        if keys[pygame.K_RIGHT]:
            self.x += self.vel

        if keys[pygame.K_DOWN]:
            self.y -= self.vel

        if keys[pygame.K_UP]:
            self.y += self.vel

        self.rect = self.x,self.y,self.width,self.height

     


def redrawWindow(win,player):   
    player.draw(win)                              
    win.fill((0,0,255))
    pygame.display.update()

def main () :                                       
    run = True
    p = Player(50,50,100,100,(0,255,0))

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:           
                run = False
                pygame.init()
                pygame.quit()
        
        pygame.init()
        p.move()
        redrawWindow(win,p)    

pygame.init()
main() 

我正在尝试借助本教程编写在线游戏代码:

https://www.youtube.com/watch?v=McoDjOCb2Zo&t=22s

顺便说一句,这是我的第一个 post 如果我有任何错误,请原谅!

Player.__init__ 中有错别字。 self.val 需要 self.vel:

self.val = 3

self.vel = 3

您需要在清除背景后和更新屏幕之前绘制播放器:

def redrawWindow(win,player):  
    win.fill((0,0,255)) 
    player.draw(win)                              
    pygame.display.update()

使用pygame.time.Clock控制每秒帧数,从而控制游戏速度。

方法tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

def main () :                                       
    run = True
    p = Player(50,50,100,100,(0,255,0))

    clock = pygame.time.Clock()
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:           
                run = False
                pygame.init()
                pygame.quit()
        
        pygame.init()
        p.move()
        redrawWindow(win,p)
        clock.tick(60)    

pygame.init()
main() 

典型的 PyGame 应用程序循环必须: