私は PyGame で小さなワーム プログラムを開発しています。りんごを食べるワームがあり、りんごを食べるたびに成長します。自分のしっぽや窓枠にぶつかると「ゲームオーバー」になります。毒のある悪いリンゴをランダムに追加したい。これらのリンゴは、画面のどこにでも表示されますが、まだリンゴで占められていない場所に表示されます。それどころか、良いリンゴが次々と現れます。Wormy がリンゴを食べると、リンゴが 1 つ成長し、別のリンゴが画面に表示されます。だから、別のスレッドで悪いリンゴを生産する必要があると思います。ただし、メインスレッドで悪いりんごの位置などにアクセスして、悪いりんごに出会ったときにワームが死ぬようにしたいと思います。
これをどのように書くことができるか考えていますか?
これを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()
しかし、ワームを削除するように、メインスレッドで不良リンゴの場所を回復するにはどうすればよいでしょうか?
感謝とよろしく