Skip to content

Commit 85c2ead

Browse files
authored
Merge pull request #79 from debojit11/main
Interactive Text-Based Adventure Game(Issue no. 24)
2 parents 05e1481 + e30c089 commit 85c2ead

File tree

2 files changed

+238
-0
lines changed

2 files changed

+238
-0
lines changed

Text_Adventure_Game/readme.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Text-Based Adventure Game
2+
3+
Welcome to the **Text-Based Adventure Game**! This Python game is a simple interactive adventure where players explore rooms, collect items, and engage in combat with opponents like goblins and dragons. Each decision you make will affect your inventory and how you handle future challenges.
4+
5+
## Features
6+
7+
- **Two distinct types of doors**: Players can choose between doors, which may lead to hidden items such as swords or shields.
8+
- **Combat System**: Engage in battle with different opponents:
9+
- **Goblin**: A weak opponent that requires strategy.
10+
- **Dragon**: A formidable final boss with special attacks.
11+
- **Inventory Management**: Pick up and use items like swords and shields to aid in combat.
12+
- **Game Save & Load**: Your progress is automatically saved, so you can load it later and continue from where you left off.
13+
14+
## Gameplay
15+
16+
- Players start the game by entering their name.
17+
- You are presented with two doors to choose from, each leading to different experiences.
18+
- Items like swords and shields can be found to help you in combat.
19+
- Random encounters with goblins and dragons will test your decision-making skills.
20+
- The game automatically saves your progress, allowing you to resume your adventure later.
21+
22+
## How to Play
23+
24+
1. **Choose a door**: When prompted, choose either the left or right door. Each door may contain hidden treasures like a sword or shield.
25+
2. **Make choices**: Decide whether to pick up items or face challenges.
26+
3. **Combat**: Engage in combat with either a goblin or dragon. Use your sword and shield to protect yourself or defeat enemies.
27+
4. **Save your progress**: The game will automatically save after each major action.
28+
5. **Reload your game**: If you exit the game, you can load it from the last saved point when you return.
29+
30+
## Setup and Installation
31+
32+
1. Ensure you have Python 3 installed on your machine.
33+
2. Clone this repository to your local machine.
34+
3. Navigate to the project directory.
35+
4. Run the text_adventure_game.py file.
36+
37+
38+
## Code Overview
39+
40+
The game is built using Python, and its logic is divided into several components:
41+
42+
- **Opponent Class**: The base class for both weak and strong opponents. Handles basic attack logic.
43+
- **WeakOpponent Class**: A class for weaker opponents like the goblin. Overrides the attack method to reflect weaker attacks.
44+
- **FinalBoss Class**: A subclass of Opponent designed for more challenging enemies like the dragon, with special powers.
45+
- **Combat and Exploration**: Players can choose doors, explore rooms, collect items, and engage in combat.
46+
- **Saving and Loading**: The game state is saved to a file (`game_save.txt`), and players can load this file to continue their progress.
47+
48+
## Error Handling
49+
50+
The game is designed with basic error handling using `try-except` blocks:
51+
- If there are issues with file saving or loading, an error message is displayed.
52+
- Combat logic is wrapped in error handling to prevent crashes due to unexpected input.
53+
54+
Enjoy your adventure!
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
import random
2+
import os # Used to check if the file exists
3+
4+
# Opponent base class
5+
class Opponent:
6+
def __init__(self, name, health, attack_strength):
7+
self.name = name
8+
self.health = health
9+
self.attack_strength = attack_strength
10+
11+
def attack(self):
12+
"""General attack logic for opponents."""
13+
return random.randint(1, self.attack_strength)
14+
15+
# WeakOpponent class inheriting from Opponent
16+
class WeakOpponent(Opponent):
17+
def __init__(self, name, health, attack_strength):
18+
super().__init__(name, health, attack_strength)
19+
20+
def attack(self):
21+
"""Overriding attack for weak opponents."""
22+
print(f"{self.name} attacks weakly!")
23+
return random.randint(1, self.attack_strength // 2) # Weak attack is halved
24+
25+
# FinalBoss class inheriting from Opponent
26+
class FinalBoss(Opponent):
27+
def __init__(self, name, health, attack_strength, special_power):
28+
super().__init__(name, health, attack_strength)
29+
self.special_power = special_power # New attribute for FinalBoss
30+
31+
def attack(self):
32+
"""Overriding attack for final bosses with special power."""
33+
if random.random() > 0.7: # 30% chance of using special power
34+
print(f"{self.name} uses {self.special_power}!")
35+
return random.randint(self.attack_strength, self.attack_strength * 2)
36+
else:
37+
print(f"{self.name} attacks normally.")
38+
return super().attack()
39+
40+
# Additional methods for game logic
41+
42+
def save_game(player_name, inventory, doors_chosen):
43+
"""Saves the current game state to a file."""
44+
try:
45+
with open('game_save.txt', 'w') as file:
46+
file.write(f"{player_name}\n")
47+
file.write(",".join(inventory) + "\n")
48+
file.write(f"{doors_chosen['left']},{doors_chosen['right']}\n")
49+
except Exception as e:
50+
print(f"Error saving game: {e}")
51+
52+
def load_game():
53+
"""Loads the game state from a file if it exists."""
54+
if not os.path.exists('game_save.txt'):
55+
return None, [], {"left": False, "right": False}
56+
57+
try:
58+
with open('game_save.txt', 'r') as file:
59+
file_content = file.readlines()
60+
61+
player_name = file_content[0].strip()
62+
inventory = file_content[1].strip().split(",") if file_content[1].strip() else []
63+
doors_status = file_content[2].strip().split(",")
64+
doors_chosen = {"left": doors_status[0] == "True", "right": doors_status[1] == "True"}
65+
66+
return player_name, inventory, doors_chosen
67+
except Exception as e:
68+
print(f"Error loading game: {e}")
69+
return None, [], {"left": False, "right": False}
70+
71+
def choose_door(doors_chosen, inventory):
72+
"""Handles the player's choice of doors and updates the game state accordingly."""
73+
available_doors = []
74+
if not doors_chosen["left"]:
75+
available_doors.append("left")
76+
if not doors_chosen["right"]:
77+
available_doors.append("right")
78+
79+
print(f'{"You return to the two doors.":^30}')
80+
if available_doors:
81+
print(f'{"Available doors are: " + ", ".join(available_doors):^30}')
82+
83+
choice = ""
84+
while choice not in available_doors:
85+
choice = input(f'{"Which door do you want to choose? (left/right): ":^30}').lower()
86+
87+
try:
88+
if choice == "left" and not doors_chosen["left"]:
89+
print(f'{"You are in a room with no doors. It is empty.":^30}')
90+
if input(f'{"Do you want to look around? (yes/no): ":^30}').lower() == "yes":
91+
print(f'{"You see a sword on the ground.":^30}')
92+
if input(f'{"Do you want to take the sword? (yes/no): ":^30}').lower() == "yes":
93+
inventory.append("sword")
94+
print(f'{"You took the sword!":^30}')
95+
else:
96+
print(f'{"You left the sword.":^30}')
97+
doors_chosen["left"] = True
98+
99+
elif choice == "right" and not doors_chosen["right"]:
100+
print(f'{"You enter a room and find a shield!":^30}')
101+
if input(f'{"Do you want to take the shield? (yes/no): ":^30}').lower() == "yes":
102+
inventory.append("shield")
103+
print(f'{"You took the shield!":^30}')
104+
else:
105+
print(f'{"You left the shield.":^30}')
106+
doors_chosen["right"] = True
107+
except Exception as e:
108+
print(f"Error during door selection: {e}")
109+
110+
save_game(player_name, inventory, doors_chosen)
111+
return doors_chosen, inventory
112+
113+
def combat(choice, inventory):
114+
"""Handles combat encounters using the new Opponent system."""
115+
try:
116+
if choice == "dragon":
117+
dragon = FinalBoss("Dragon", health=100, attack_strength=20, special_power="Fire Breath")
118+
print(f'{"You encounter a fearsome dragon!":^30}')
119+
if input(f'{"Do you want to fight the dragon? (yes/no): ":^30}').lower() == "yes":
120+
if "sword" in inventory:
121+
print(f'{"Rolling the dice to see the outcome...":^30}')
122+
player_attack = random.randint(1, 10) # Simulating player's attack
123+
dragon_attack = dragon.attack()
124+
125+
if player_attack >= dragon_attack:
126+
print(f'{"You defeated the dragon with your sword!":^30}')
127+
else:
128+
if "shield" in inventory:
129+
print(f'{"The dragon overpowered you, but your shield saved you!":^30}')
130+
inventory.remove("shield")
131+
else:
132+
print(f'{"The dragon overpowered you and you lost the game!":^30}')
133+
inventory.clear()
134+
else:
135+
print(f'{"You were eaten by the dragon because you had no sword!":^30}')
136+
inventory.clear()
137+
138+
elif choice == "goblin":
139+
goblin = WeakOpponent("Goblin", health=50, attack_strength=5)
140+
print(f'{"You encounter a sneaky goblin!":^30}')
141+
if input(f'{"Do you want to fight the goblin? (yes/no): ":^30}').lower() == "yes":
142+
if "sword" in inventory:
143+
print(f'{"Rolling the dice to see the outcome...":^30}')
144+
player_attack = random.randint(1, 10) # Simulating player's attack
145+
goblin_attack = goblin.attack()
146+
147+
if player_attack >= goblin_attack:
148+
print(f'{"You defeated the goblin with your sword!":^30}')
149+
else:
150+
if "shield" in inventory:
151+
print(f'{"The goblin tricked you, but your shield protected you!":^30}')
152+
inventory.remove("shield")
153+
else:
154+
print(f'{"The goblin tricked you and you lost the game!":^30}')
155+
inventory.clear()
156+
elif "shield" in inventory:
157+
print(f'{"The goblin attacked, but your shield saved you!":^30}')
158+
inventory.remove("shield")
159+
else:
160+
print(f'{"The goblin defeated you because you had no sword or shield!":^30}')
161+
inventory.clear()
162+
except Exception as e:
163+
print(f"Error during combat: {e}")
164+
165+
return inventory
166+
167+
def play_game():
168+
"""Main function that runs the game logic."""
169+
player_name, inventory, doors_chosen = load_game()
170+
171+
if not player_name:
172+
player_name = input("Enter your name: ")
173+
174+
print(f'{"Welcome to the Adventure Game, " + player_name + "!":^30}')
175+
176+
# Let player choose a door
177+
doors_chosen, inventory = choose_door(doors_chosen, inventory)
178+
179+
# Encounter either a goblin or a dragon randomly
180+
encounter = random.choice(["goblin", "dragon"])
181+
inventory = combat(encounter, inventory)
182+
183+
if __name__ == "__main__":
184+
play_game()

0 commit comments

Comments
 (0)