# 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 # check if worm has eaten an apply if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']: # don't remove worm's tail segment apple = getRandomLocation() # set a new apple somewhere else: del wormCoords[-1] # remove worm's tail segment
We do a similar collision detection check between the head of the worm and the apple’s XY coordinates. If they match, we set the coordinates of the apple to a random new location (which we get from the return value of
If the head has not collided with an apple, then we delete the last body segment in the
wormCoords list. Remember that negative integers for indexes count from the end of the list. So while
0 is the index of the first item in the list and
1 is for the second item,
-1 is for the last item in the list and
-2 is for the second to last item.
The code on lines 91 to 100 (described next in the "Moving the Worm" section) will add a new body segment (for the head) in the direction that the worm is going. This will make the worm one segment longer. By not deleting the last body segment when the worm eats an apple, the overall length of the worm increases by one. But when line 13  deletes the last body segment, the size remains the same because a new head segment is added right afterwards.