我是Python和Pygame的初学者,我不知道我在这里做错了什么。

huangapple go评论64阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月26日 22:38:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定