User Tools

Site Tools


robots-2

This is an old revision of the document!


Robots Part 2

This part of the code was taught to Roger on September 26th.

Rocks and Robots

The first thing we want to do is add one robot and one rock to make the game world feel less lonely and work on the rules of the game. If the game works with one, it can work with more. This is induction!

Adding Rocks

After the code which creates the map in init() add this:

Adding Rocks

        # Add rocks.
        self.gameMap[7][7] = '*'

There, we have added a rock to the map.

If you want to get fancy you can add it randomly (or add a second, random rock!) as follows:

Alternate version

        # Add rocks.
        self.gameMap[7][7] = '*'
        
        # Add a rock randomly
        rx = random.randint(1,self.gameW)
        ry = random.randint(1,self.gameH)
        self.gameMap[ry][rx] = '*'

Next, we need to make sure that if the player hits the rock, he will die.

To do this we add an elif to movePlayer(). Add the following elif to the if condition in movePlayer:

rock collision in movePlayer()

        if self.gameMap[to_y][to_x] == '#':
            return
        elif self.gameMap[to_y][to_x] == '*':
            self.killPlayer()

        self.px = to_x
        self.py = to_y

For reference, here is a version that uses if-elif-else:

version with elif-else

        if self.gameMap[to_y][to_x] == '#':
            pass
        elif self.gameMap[to_y][to_x] == '*':
            self.killPlayer()
        else:
            self.px = to_x
            self.py = to_y

It doesn't matter which version you use, pick the one which feels right to you.

In any case you will notice the killPlayer() function. This is new. Here it is:

killPlayer()

    def killPlayer(self):
        print("You have died! ¯\_(ツ)_/¯", end="")
        quit()

There it is. Simple idea, simple execution. We just want something functional for now.

In one version I used GAME OVER instead of a shrug smiley, but I thought this way was a bit funnier.

robots-2.1695775161.txt.gz · Last modified: 2023/09/27 00:39 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki