英文:
im a python and pygame beginner and i dont know what i did wrong here
问题
import pygame
running = True
BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
background = GRAY
pygame.init()
screen = pygame.display.set_mode((640, 240))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
background = RED
elif event.key == pygame.K_g:
background = GREEN
screen.fill(background)
pygame.display.update()
pygame.quit()
英文:
import pygame
running = True
BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
background = GRAY
pygame.init()
screen = pygame.display.set_mode((640, 240))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
background = RED
elif event.key == pygame.K_g:
background = GREEN
screen.fill(background)
pygame.display.update()
pygame.quit()
it should be a gray background and change color when you press r or g but it just starts and doesn't change the color on a key press.
答案1
得分: 0
代码中提到了缩进的问题。事件必须在事件循环中进行评估,而不是在应用程序循环中:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 缩进
#-->|
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
background = RED
elif event.key == pygame.K_g:
background = GREEN
screen.fill(background)
pygame.display.update()
在上述代码中,缩进非常重要,它用于表示代码块的嵌套结构。
英文:
Its a matter of Indentation. The event must be evaluated in the event loop, but not in the application loop:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENATION
#-->|
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
background = RED
elif event.key == pygame.K_g:
background = GREEN
screen.fill(background)
pygame.display.update()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论