Pygame没有呼吸



我是Pygame的新手(我在python中使用了许多库(我面临的一个严重问题是我的Pygame窗口没有响应我不知道为什么,但每次我运行代码。

这是窗口

这是代码:

import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
while run:
pygame.time.delay(100)

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel  :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel

win.fill((255,255,255))  # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))   
pygame.display.update() 
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

pygame.quit()

你能帮忙解决这个问题吗。

这只是缩进的问题。您已经实现了一个无限循环,因此窗口没有响应。您需要在应用程序循环中绘制场景并处理事件,而不是在程序循环之后的

import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
while run:
pygame.time.delay(100)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel  :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
# INDENTATION
#-->|

win.fill((255,255,255))  # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))   
pygame.display.update() 
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

pygame.quit()

您的问题是由脚本的缩进引起的。

pygame.display.update()将更新屏幕,该屏幕应在while run内部!

"用黑色填充屏幕"可以在while上执行,因为您只需要一次。

与设置run = Falsefor循环相同,按钮和事件是您希望在每次迭代中检查的内容,因此将其移动到while


import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")

x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
win.fill((255,255,255))  # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))
while run:
# pygame.time.delay(100)

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel  :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel

pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()

最新更新