我正在尝试使用pygame在Python中重新创建Agar.io。到目前为止,我已经能够在某种程度上模拟玩家的动作,但是后来我尝试使用pygame.time.set_timer()方法在给定的间隔内生成一些“食物单元”,尽管其余的游戏元素都是在绘制这些食物单元(例如屏幕和播放器)时,只有在我拖动游戏窗口时才绘制(并添加到“ food_list”列表中)。我认为这可能是我不真正知道如何处理事件队列的问题。
main.py,这是游戏循环所在的位置:
import sys, pygame
from player import Player
from food import Food
import random
pygame.init()
SCREEN_SIZE = [1024, 768]
WHITE = (255, 255 , 255)
generate_food = pygame.USEREVENT + 1
screen = pygame.display.set_mode(SCREEN_SIZE)
screen.fill(WHITE)
player = Player()
food_list = []
## TODO: Make a separate GameScreen class.
## TODO: Make a list of constants
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == generate_food:
food_x = random.randrange(0, 760)
food_y = random.randrange(0, 1000)
food_list.append(Food(food_x, food_y))
pygame.time.set_timer(generate_food, 200)
screen.fill(WHITE)
for f in food_list:
f.draw(screen)
player.update()
player.draw(screen)
pygame.display.flip()
food.py:
import pygame
import random
from cell import Cell
DARK_GREEN = (0, 102, 0)
class Food(Cell):
def __init__(self, x, y):
super().__init__()
self.size = 2
self.image = pygame.Surface([2, 2])
self.image.fill(DARK_GREEN)
self.rect = self.image.get_rect()
self.x = x
self.y = y
def draw(self, screen):
pygame.draw.circle(screen, DARK_GREEN, (self.x, self.y), self.size, 0)
def getX(self):
return self.x
def getY(self):
return self.y
答案 0 :(得分:0)
实际上定时器是在应用循环中不断重启的。但是,pygame.time.set_timer()
会生成一个计时器,该计时器会在事件队列中重复创建 USEREVENT
。因此,在应用程序循环之前启动一次计时器就足够了:
pygame.time.set_timer(generate_food, 200) # <--- ADD
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == generate_food:
food_x = random.randrange(0, 760)
food_y = random.randrange(0, 1000)
food_list.append(Food(food_x, food_y))
# pygame.time.set_timer(generate_food, 200) <--- DELTE