我正在用 PyGame 开发一个小型蠕虫程序。我有一条虫子吃苹果,每次它吃一个苹果就长。当它遇到自己的尾巴或窗户边缘时,它“游戏结束”。我想随机添加有毒的坏苹果。这些苹果出现在屏幕上的任何地方,在某个尚未被苹果占据的地方。相反,好苹果一次出现一个。当wormy吃掉一个苹果时,它会长一个,屏幕上会出现另一个苹果。所以,我想我应该在一个单独的线程中生产坏苹果。但是,我想在主线程中访问坏苹果的位置等,以便虫子在遇到坏苹果时死亡。
你知道怎么写吗?
我想在 main() 中有这个
# Start bad apples thread
threading.Thread(target=badApples).start()
所以 main() 最终看起来像这样:
def runGame():
# Set a random start point.
startx = random.randint(5, CELLWIDTH-5)
starty = random.randint(5, CELLHEIGHT-5)
wormCoords = [{'x': startx, 'y': starty},
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT
# Start the apple in a random place.
apple = getRandomLocation()
# Start bad apples thread
threading.Thread(target=badApples).start()
while True: # main game loop
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
# check if the worm has hit itself or the edge
if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT:
return # game over
for wormBody in wormCoords[1:]:
if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
return # game over
# etc...
(主要来自http://inventwithpython.com/的代码)
和一个以 badApples 开头的目标方法
def badApples():
time.sleep(random.randint(200,500))
badApple = getRandomLocation()
但是如何在主线程中恢复坏苹果的位置,以删除蠕虫?
谢谢并恭祝安康