Skip to main content
Engineering LibreTexts

7.6: A Separate runGame() Function

  • Page ID
    13602
  • def runGame():
        # Set a random start point.
        startx = random.randint(5, CELLWIDTH - 6)
        starty = random.randint(5, CELLHEIGHT - 6)
        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()
    

    At the beginning of a game, we want the worm to start in a random position (but not too close to the edges of the board) so we store a random coordinate in startx and starty. (Remember that CELLWIDTH and CELLHEIGHT is the number of cells wide and high the window is, not the number of pixels wide and high).

    The body of the worm will be stored in a list of dictionary values. There will be one dictionary value per body segment of the worm. The dictionary will have keys 'x' and 'y' for the XY coordinates of that body segment. The head of the body to be at startx and starty. The other two body segments will be one and two cells to the left of the head.

    The head of the worm will always be the body part at wormCoords[0]. To make this code more readable, we’ve set the HEAD constant to 0 on line 32, so that we can use wormCoords[HEAD] instead of wormCoords[0].

    • Was this article helpful?