Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Game Help
#1
My team and made this code for a Labyrinth the problem is
1. When you find a potion it ends the game
2. When you move_left or move_right it ends the game
3. Can't figure out how to add image when you find potion or when a trap is add

The goal is we want to allow the players to move from room to room or move back to previous room, search and find items. If they find a potion and image should be activated to use in pygame if a trap is activated and image and sound to be activated
If you can give any suggestion of what where doing wrong that be greatly appreciated thank you

import random

rooms = ["Empty Room", "Survivor Room", "Trap Room", "Exit Room", "Treasure Room"]
idNum = 1  # Initial ID number
POINTS = 0
TEP_POINTS = 0
SAVED = 0

def timer():
    timer_v = random.randint(8, 10)
    print(f"Timer set for {timer_v} seconds.")
    return timer_v
# Function to generate random rooms and make sure the first room is always the "Exit Room"
def generate_degenerate_room_layout(rows, cols):
    room_map = [["" for _ in range(cols)] for _ in range(rows)]
    
    # Set the starting position (top-left corner) to "Exit Room"
    exit_row, exit_col = 0, 0
    room_map[exit_row][exit_col] = "Exit Room"
    
    # Fill other rooms with random selections from the available rooms
    for i in range(rows):
        for j in range(cols):
            if room_map[i][j] == "":
                room_map[i][j] = random.choice(rooms)
    
    # Ensure the layout has paths (if needed) from the exit room
    create_paths(room_map, exit_row, exit_col, rows, cols)
    
    return room_map

# Function to create paths from the Exit Room to other rooms (simplified)
def create_paths(room_map, exit_row, exit_col, rows, cols):
    for r in range(exit_row, rows):
        room_map[r][exit_col] = random.choice(rooms)  # Make a downward path
    for c in range(exit_col, cols):
        room_map[exit_row][c] = random.choice(rooms)  # Make a rightward path
    return

# Function to handle turn-based actions
def trun(player, mtimer, potions, stimes, rooms, exit_row, exit_col, prev_exit_row, prev_exit_col):
    # Get current room using row and col
    current_room = rooms[exit_row][exit_col]  
    print(f"You are currently in: {current_room}")
    
    # Check if the current room is the "Exit Room"
    if rooms[exit_row][exit_col] == "Exit Room":
        takeTrun = input("What would you like to do? (exit/move/search/use_item/rescue): ")
    else:
        takeTrun = input("What would you like to do? (move/search/use_item): ")
    
    # Move command
    if takeTrun.lower() == "move":
        mtimer, stimes, exit_row, exit_col, prev_exit_row, prev_exit_col = move(player, mtimer, potions, stimes, rooms, exit_row, exit_col, prev_exit_row, prev_exit_col)
    
    # Search command
    elif takeTrun.lower() == "search" and stimes < 4:
        mtimer, stimes, rooms = search(player, mtimer, potions, stimes, rooms, exit_row, exit_col)
    
    # Use item command
    elif takeTrun.lower() == "use_item":
        item_name = input("Enter the item name to use: ")
        mtimer = player.use_item(item_name, mtimer)
    
    # Exit command
    elif takeTrun.lower() == "exit":
        global SAVED
        print(f"You saved {SAVED}")
        return False  # Exit the game
    
    # Rescue command
    elif takeTrun.lower() == "rescue":
        global POINTS
        POINTS += SAVED
        SAVED = 0
        print("Rescue completed.")
    
    return mtimer, stimes, exit_row, exit_col, prev_exit_row, prev_exit_col

# Function for the movement
def move(player, mtimer, potions, stimes, rooms, exit_row, exit_col, prev_exit_row, prev_exit_col):
    side_move = input("Where would you like to go (move_left/move_right/move_back): ")
    
    if side_move.lower() == "move_right" and exit_col < len(rooms[0]) - 1:
        prev_exit_row, prev_exit_col = exit_row, exit_col  # Store current position as previous
        exit_col += 1  # Move right increases column
        mtimer -= 2  # Time spent moving
        print(f"You moved to Room: {rooms[exit_row][exit_col]}")
    
    elif side_move.lower() == "move_left" and exit_col > 0:
        prev_exit_row, prev_exit_col = exit_row, exit_col  # Store current position as previous
        exit_col -= 1  # Move left decreases column
        mtimer -= 2  # Time spent moving
        print(f"You moved to Room: {rooms[exit_row][exit_col]}")
    
    elif side_move.lower() == "move_back":
        if prev_exit_row is not None and prev_exit_col is not None:
            exit_row, exit_col = prev_exit_row, prev_exit_col  # Move back to previous room
            mtimer -= 2  # Time spent moving back
            print(f"You moved back to Room: {rooms[exit_row][exit_col]}")
        else:
            print("No previous room to move back to.")
    
    else:
        print("Invalid move! You are at the edge of the room layout.")
    
    return mtimer, stimes, exit_row, exit_col, prev_exit_row, prev_exit_col
class Potion:
    def __init__(self, name, effect):
        self.name = name
        self.effect = effect

    def __str__(self):
        return f"{self.name} - Effect: {self.effect}"

def find_potion(potions):
    if not potions:
        return "No potions available."
    return random.choice(potions)

potions = [
    Potion("Healing Potion", "Restores 50 HP"),
    Potion("Speed Potion", "Increase Time"),
]
# Sample Player class
class Player:
    def __init__(self):
        self.inventory = set()

    def take_item(self, item_name):
        self.inventory.add(item_name)
        print(f"You took {item_name}.")

    def drop_item(self, item_name):
        if item_name in self.inventory:
            self.inventory.remove(item_name)
            print(f"You dropped {item_name}.")
        else:
            print("You don't have that item.")

    def use_item(self, item_name, mtimer):
        if item_name in self.inventory:
            print(f"You used {item_name}.")
            mtimer -= 2  # Use item reduces timer
        else:
            print("You don't have that item.")
        return mtimer

def ward(mtimer):
    if mtimer <= 6:
        more_time = random.randint(6, 10)
        more_time += mtimer
        print(f"You have {more_time} more turns.")
    else:
        print("This will have no effect.")

def Welconme():
    print("Welcome to Labyrinth Rescue, Inc.")

def game_start():
    print("It is your first day working with Labyrinth Rescue, Inc.")

def get_player_id(idNum):
    name = input("Please input your worker ID (first initial and last name): ")
    confirm = input(f"Your ID is {name}{idNum}. Is that correct? (yes/no): ")
    if confirm.lower() == "yes":
        player_id = name + str(idNum)
        print(f"Your player ID is {player_id}.")
        game_start()  # Game start
        return player_id
    else:
        print("Please restart the process to enter your details again.")
        return get_player_id(idNum)

def search(player, mtimer, potions, stimes, rooms, exit_row, exit_col):
    if mtimer >= 2:
        mtimer -= 2  # Searching takes 2 seconds
        print(f"Time remaining: {mtimer} seconds.")
    else:
        mtimer -= 1
    
    if stimes < 4:  
        number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        random.shuffle(number_list)
        selected_number = number_list.pop(0)  
        stimes += 1
    else:
        number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        random.shuffle(number_list)
        selected_number = number_list.pop(0)
    
    itemsInRoom = selected_number
    print(f"Item number found in room: {itemsInRoom}")

    if itemsInRoom == 3 or itemsInRoom == 6:
        print("You found a potion!")
        found_potion = find_potion(potions)  
        player.take_item(found_potion.name)
    elif itemsInRoom > 9:
        print("You found a component!")
    else:
        print("Nothing found this time.")

    if rooms[exit_row][exit_col] == "Trap Room":
        print("You stepped on a trap!")
        mtimer -= 1  # Decrease time when stepping on a trap
    elif rooms[exit_row][exit_col] == "Survivor Room":
        Survivor = random.randint(1, 5)
        global POINTS
        POINTS += Survivor
        print(f"You found a survivor! You gain {Survivor} points.")
    elif rooms[exit_row][exit_col] == "Treasure Room":
        global TEP_POINTS
        TEP_POINTS += random.randint(1, 5)
        print(f"You found Treasure! You gain {TEP_POINTS} points.")
    
    return mtimer, stimes, rooms

# Function to start the game
def play_game(idNum, Player, timer, potions, rooms, generate_degenerate_room_layout):
    print("Welcome to Labyrinth Rescue, Inc.")
    print("It is your first day working with Labyrinth Rescue, Inc.")

    player_id = get_player_id(idNum)
    player = Player()  

    # Generate the room map with the first room as "Exit Room"
    rooms = generate_degenerate_room_layout(4, 5)

    mtimer = timer()  # Timer
    stimes = 0
    exit_row, exit_col = 0, 0  # Starting position (top-left corner)
    prev_exit_row, prev_exit_col = None, None  # No previous position initially
    
    while True:
        result = trun(player, mtimer, potions, stimes, rooms, exit_row, exit_col, prev_exit_row, prev_exit_col)
        
        if result is False:  # If the result is False, the game is over
            print("Exiting game.")
            break
        
        mtimer, stimes, exit_row, exit_col, prev_exit_row, prev_exit_col = result  # Unpack the return values when game continues
        print(f"Time left: {mtimer} seconds.")
        
        global POINTS
        if mtimer <= 0 and POINTS == 0:
            print("Game over.")
            break
        elif mtimer <= 0 and POINTS > 0:
            POINTS -= 1
            mtimer += 2
        
        # Prompt the player for replay after the game ends
        replay = input("Would you like to play again? (yes/no): ")
        if replay.lower() != 'yes':
            print("Thank you for playing!")
            break  # Exit the game loop
        else:
            idNum += 1  # Increment the idNum for the next player
            play_game(idNum, Player, timer, potions, rooms, generate_degenerate_room_layout)  # Start a new game with a new ID


# Example function call to start the game
play_game(idNum, Player, timer, potions, rooms, generate_degenerate_room_layout)
Larz60+ write Mar-06-2025, 08:47 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
bbcode tags have been added for you this time.
Reply
#2
Your description of the problem is not correct. The code asking if your want to play again runs each time you take a turn. The play again code should be removed from the play_game() function. Like this:
def play_game(idNum, Player, timer, potions, rooms, generate_degenerate_room_layout):
    print("Welcome to Labyrinth Rescue, Inc.")
    print("It is your first day working with Labyrinth Rescue, Inc.")

    player_id = get_player_id(idNum)
    player = Player()

    # Generate the room map with the first room as "Exit Room"
    rooms = generate_degenerate_room_layout(4, 5)

    mtimer = timer()  # Timer
    stimes = 0
    exit_row, exit_col = 0, 0  # Starting position (top-left corner)
    prev_exit_row, prev_exit_col = None, None  # No previous position initially

    while True:
        result = trun(player, mtimer, potions, stimes, rooms, exit_row, exit_col, prev_exit_row, prev_exit_col)

        if result is False:  # If the result is False, the game is over
            print("Exiting game.")
            break

        mtimer, stimes, exit_row, exit_col, prev_exit_row, prev_exit_col = (
            result  # Unpack the return values when game continues
        )
        print(f"Time left: {mtimer} seconds.")

        global POINTS
        if mtimer <= 0 and POINTS == 0:
            print("Game over.")
            break
        elif mtimer <= 0 and POINTS > 0:
            POINTS -= 1
            mtimer += 2


while True:
    play_game(idNum, Player, timer, potions, rooms, generate_degenerate_room_layout)

    # Prompt the player for replay after the game ends
    replay = input("Would you like to play again? (yes/no): ")
    if replay.lower() != "yes":
        print("Thank you for playing!")
        break  # Exit the game loop
    idNum += 1  # Increment the idNum for the next player
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020