Search code examples
pythonwhile-loopadventure

Issue with while loop in game.


I'm making a game and it has different tiles obviously. But I've come to an issue in my main Game while loop.

def play():
    player  = player1()
    while True:
        room = ClubWorld.tile_at(player.x, player.y)
        print(room.intro_text())
        choose_action(room, player)

Example of a Tile in my game:

class GirlTile(MapTile):
    def __init__(self,x,y):
        self.meet_girl = Girls()
        super().__init__(x, y)

    def intro_text(self):
        return "Hey whats up, my name is {}".format(self.meet_girl.name)

This loop keeps going as long as I'm on a game tile. It produces the available actions you have and lets the other functions know your position. it also outputs that tiles intro text, where my problem lies. I want the game to only output the intro text upon entry into a tile, once that happens i only want it to display the actions available. Suggestions?


Solution

  • You can keep previous_room and compare with room:

    def play():
        player  = player1()
        previous_room = None
        while True:
            room = ClubWorld.tile_at(player.x, player.y)
            if room != previous_room:
                print(room.intro_text())
                previous_room = room
            choose_action(room, player)
    

    Or keep player previous position previous_x, previous_y and compare with new position

    def play():
        player = player1()
        previous_x = None
        previous_y = None
        while True:
            if player.x != previous_x or player.y != previous_y :
                room = ClubWorld.tile_at(player.x, player.y)
                print(room.intro_text())
                previous_x = player.x
                previous_y = player.y
            choose_action(room, player)