I am developping a small wormy program with PyGame. I have a worm eating apples and growing each time it eats an apple. When it meets its own tail, or a window bordure, it ‘games over’.
I want to add, at random times, bad apples with poison. These apples appear anywhere on screen, at some place not already occupied with an apple. On the contrary, the good apples appear one at a time. when wormy eats an apple, it grows by one, and one other apple appears on screen. So, I guess I should have the production of bad apples in a separated thread. However, I would like to have access to position etc… of bad apples in main thread, so that wormy dies when meeting a bad apple.
Do you have an idea how this can be written?
I thought of having this in main()
# Start bad apples thread
threading.Thread(target=badApples).start()
so that main() ends up looking like this :
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...
(code from http://inventwithpython.com/ mostly)
and a target method badApples starting with
def badApples():
time.sleep(random.randint(200,500))
badApple = getRandomLocation()
but how then to recover in main thread the location for bad apple, as to delete worm?
thanks and regards
You absolutly don’t have to use threads for this. As you are in control of your game loop, you can just schedule the creating of a bad apple (using some kind of countdown).
Create a variable that will store a value indicating when a new bad apple will show up, and a list of already created bad apples.
In your main loop, decrease the value of next_bad_apple. If it reaches
0, create a bad apple and start over again.