Build a complete game with Python and PyGame

The moveBots Function

The moveBots function updates the position of all of the robots after the player moves. Each robot will move one space closer to the player in whichever direction is appropriate.

Line 87 starts a loop that walks through each of the robots in self.robots. Line 90 checks whether the robot is already on a rubble square. If it is, then continue is called (line 92) to ignore that robot. Line 94 clears the robot's grid position in preparation for moving by setting its value to a blank string.

Line 96 unpacks the tuple into discreet botx and boty variables for easier use in movement calculations. Lines 97 and 98 (commented out) accomplish the same thing but may be less ambiguous about what's happening.

The if/elif on lines 99-100 and 102-103 adjust the x and y coordinates of the robot to move toward the player. Once they have been updated, line 105 creates a new bot tuple, then line 107 updates the self.robots list.

Lines 110 through 114 check for collisions. On lines 110 and 111, if the bot shares its location with the player, then the function returns (exits). If this is true, then the player has lost the game. However, this function doesn't deal with that; it only moves the bots.

Lines 113 and 114 check for collisions with other robots. If a collision has occurred, then the space is relabeled RUBBLE. On lines 122 and 123, if the grid square is rubble, then the program carries on with the next list entry (continue on line 123). Finally, the new grid location is marked as ROBOT on line 125.

The checkGrid Function

checkGrid is used to see if any adjoining squares from the provided grid coordinates contain a robot. The function accepts one argument: a tuple of the position to be checked.

On line 128, result = False initializes the return value. Then, a new coordinate is generated by incrementing and decrementing the x and y values. Each if statement (lines 131, 134, 137, and 140) looks for that position in self.robots. If it exists, then result is set to True. Line 142 returns result: True if a robot is adjacent, and False if not.

Buy this article as PDF

Express-Checkout as PDF

Pages: 8

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content