我想绘制一个从黑色变为红色的矩形,而无需用户做任何事情。下面的代码应该填满屏幕,绘制一个黑色矩形然后擦除它并绘制一个红色矩形,然后继续循环。但我只得到一个红色矩形。我做错了什么?
import pygame
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, [300, 200, 100, 100],0)
screen.fill(WHITE)
pygame.draw.rect(screen, RED, [300, 200, 100, 100],0)
pygame.display.flip()
clock.tick(60)
pygame.quit()
答案 0 :(得分:1)
您可以在rect(...)
和..
...使用pygame.time.set_timer()
的自有事件来更改此变量中的颜色。
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
size = (700, 500)
# --- start ---
pygame.init()
screen = pygame.display.set_mode(size)
# start color
color = RED
# define own event type
CHANGE_COLOR = pygame.USEREVENT + 1
# create event every 250ms
pygame.time.set_timer(CHANGE_COLOR, 250) # 250ms
# --- mainloop ---
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# check if get event
if event.type == CHANGE_COLOR:
# change color
if color == RED:
color = BLACK
else:
color = RED
screen.fill(WHITE)
pygame.draw.rect(screen, color, [300, 200, 100, 100],0)
pygame.display.flip()
clock.tick(60)
pygame.quit()
...或使用pygame.time.get_ticks()
获取当前时间并检查是否是时候改变颜色。
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
size = (700, 500)
# --- start ---
pygame.init()
screen = pygame.display.set_mode(size)
# start color
color = RED
# get current time
current_time = pygame.time.get_ticks()
# first change after 250 ms
change_color_time = current_time + 250
# --- mainloop ---
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# get current time
current_time = pygame.time.get_ticks()
# check if it is time to change color
if current_time >= change_color_time:
# set new time to change color again
change_color_time = current_time + 250
# change color
if color == RED:
color = BLACK
else:
color = RED
screen.fill(WHITE)
pygame.draw.rect(screen, color, [300, 200, 100, 100],0)
pygame.display.flip()
clock.tick(60)
pygame.quit()