gpt4 book ai didi

python - 如何解决运行程序时出现黑屏的问题

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:00 35 4
gpt4 key购买 nike

我是 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()

最佳答案

你必须尊重 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()

关于python - 如何解决运行程序时出现黑屏的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026092/

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