运行程序时如何解决黑屏的发生

时间:2019-05-07 15:36:58

标签: python pygame

我是Python游戏开发的新手,我想通过遵循FreeCodeCamp在Youtube上的教程来学习,但没有获得预期的输出。当我运行程序时,窗口会打开,但显示黑屏,没有输出。

试图包含pygame.init()和pygame.display.init(),但这都不起作用。

import pygame

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

client_number = 0

class Player():

    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = (x, y, width, height)
        self.vel = 3

    def draw(self, win):
        pygame.draw.rect(win, self.color, self.rect)

    def move(self):
        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 redraw_Window(win, player):

    win.fill((255, 255, 255))
    player.draw(win)
    pygame.display.update()


def main():

    run = True
    p = Player(50, 50, 100, 100, (0, 255, 0))
    clock = pygame.time.Clock()
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
    p.move()
    redraw_Window(win, p)


main()

1 个答案:

答案 0 :(得分:0)

您必须尊重Indentation
p.move()redraw_Window(win, p)必须在主循环的范围内(在while run:的范围内),而不是在函数main main的范围内:

def main():

    run = True
    p = Player(50, 50, 100, 100, (0, 255, 0))
    clock = pygame.time.Clock()
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

        # ->>>
        p.move()
        redraw_Window(win, p)

main()