我正在制作一个版本的boids,我试图通过使用pygames MOUSEBUTTONDOWN fucntion将boids附加到列表中。它在某种程度上很有效。我想要它添加一个对象的实例,但它在我点击左键时添加了很多。
from precode import *
from config import *
import pygame as pg
from boids import Boid
from obstacle import Obstacle
def boids():
screen_res = (SCREEN_W,SCREEN_H)
pg.init()
screen = pg.display.set_mode(screen_res)
clock = pg.time.Clock()
boids = []
obstacles = []
while True:
for event in pg.event.get():
if event.type == pg.QUIT or event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
exit()
pg.draw.rect(screen, (0,0,0), (0, 0, screen.get_width(), screen.get_height()))
time_passed = clock.tick(60) # limit to 60FPS
time_passed_seconds = time_passed / 1000.0 # convert to seconds
if event.type == pg.MOUSEBUTTONDOWN and event.button == LEFT:
x, y = pg.mouse.get_pos()
obstacles.append(Obstacle(screen, Vector2D(x,y)))
for obstacle in obstacles:
obstacle.draw()
if event.type == pg.MOUSEBUTTONDOWN and event.button == RIGHT:
x, y = pg.mouse.get_pos()
boids.append(Boid(screen, Vector2D(x,y), Vector2D(10,5)))
for boid in boids:
boid.move()
boid.draw()
pg.display.update()
if __name__ == '__main__':
boids()
boids和障碍的类都是简单的类,我可以根据需要添加它们。
答案 0 :(得分:0)
if event.type == pg.MOUSEBUTTONDOWN:
子句应该在事件循环中。检查此版本是否按预期工作:
def boids():
screen_res = (SCREEN_W, SCREEN_H)
pg.init()
screen = pg.display.set_mode(screen_res)
clock = pg.time.Clock()
boids = []
obstacles = []
while True:
time_passed = clock.tick(60) # limit to 60FPS
time_passed_seconds = time_passed / 1000.0 # convert to seconds
# Handle the events.
for event in pg.event.get():
if event.type == pg.QUIT or event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
return
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == LEFT:
x, y = pg.mouse.get_pos()
obstacles.append(Obstacle(screen, Vector2D(x,y)))
elif event.button == RIGHT:
x, y = pg.mouse.get_pos()
boids.append(Boid(screen, Vector2D(x,y), Vector2D(10,5)))
# Insert game logic here.
# Draw everything.
pg.draw.rect(screen, (0,0,0), (0, 0, screen.get_width(), screen.get_height()))
for obstacle in obstacles:
obstacle.draw()
for boid in boids:
boid.move()
boid.draw()
pg.display.update()