Enhancing your Oregon Trail game to make it more advanced involves adding multiple layers of complexity, including better character management, comprehensive supply tracking, diverse events with choices, dynamic UI updates, and more robust game mechanics. Below is an expanded version of your game incorporating these features:
Key Enhancements:
-
Supply Management:
- Track various supplies like food, ammo, clothing, tools, and ammunition.
- Allow players to purchase supplies before starting the journey.
-
Character Attributes:
- Introduce additional attributes such as stamina, skills, or morale.
-
Diverse Events with Choices:
- Implement events that require player decisions, influencing the game’s outcome.
-
Dynamic UI:
- Display detailed status including supplies, characters' stats, and journey progress.
-
Map and Progress Tracking:
- Show distance traveled and milestones achieved.
-
Saving and Loading Game State:
- Allow players to save their progress and load it later.
-
Random Weather and Challenges:
- Introduce weather effects that impact travel and character health.
Enhanced Code Implementation:
Below is the enhanced version of your Oregon Trail game incorporating the above features. Due to the complexity and length, the code is organized into multiple classes and functions for better readability and maintainability.
import sys
import random
import json
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QLineEdit,
QMessageBox, QTextEdit, QHBoxLayout, QComboBox, QDialog, QFormLayout,
QSpinBox, QListWidget, QProgressBar
)
from PyQt6.QtCore import Qt, QTimer
# ---------------------- Character Class ----------------------
class Character:
def __init__(self, name):
self.name = name
self.health = 100
self.food = 100
self.stamina = 100
self.morale = 100
self.alive = True
def __str__(self):
return (f"{self.name} - Health: {self.health}, Food: {self.food}, "
f"Stamina: {self.stamina}, Morale: {self.morale}, Alive: {self.alive}")
def to_dict(self):
return {
'name': self.name,
'health': self.health,
'food': self.food,
'stamina': self.stamina,
'morale': self.morale,
'alive': self.alive
}
@staticmethod
def from_dict(data):
char = Character(data['name'])
char.health = data['health']
char.food = data['food']
char.stamina = data['stamina']
char.morale = data['morale']
char.alive = data['alive']
return char
# ---------------------- Supply Class ----------------------
class Supply:
def __init__(self, food=100, ammo=50, clothing=50, tools=50):
self.food = food
self.ammo = ammo
self.clothing = clothing
self.tools = tools
def __str__(self):
return (f"Food: {self.food}, Ammo: {self.ammo}, "
f"Clothing: {self.clothing}, Tools: {self.tools}")
def to_dict(self):
return {
'food': self.food,
'ammo': self.ammo,
'clothing': self.clothing,
'tools': self.tools
}
@staticmethod
def from_dict(data):
return Supply(
food=data.get('food', 100),
ammo=data.get('ammo', 50),
clothing=data.get('clothing', 50),
tools=data.get('tools', 50)
)
# ---------------------- OregonTrailGame Class ----------------------
class OregonTrailGame:
def __init__(self):
self.distance_to_travel = 2000 # Total distance in miles
self.distance_traveled = 0
self.days_passed = 0
self.characters = []
self.supplies = Supply()
self.events = [
"found food",
"lost food",
"health issues",
"nothing happens",
"disease outbreak",
"friendly encounter",
"river crossing",
"bandit attack",
"weather storm",
"market encounter"
]
self.weather = "Sunny"
def setup_characters(self, names):
self.characters = [Character(name) for name in names]
def buy_supplies(self, food, ammo, clothing, tools):
self.supplies.food += food
self.supplies.ammo += ammo
self.supplies.clothing += clothing
self.supplies.tools += tools
def travel(self, player_choices=None):
if all(not character.alive for character in self.characters):
return "All characters have perished. Game over.", False
travel_distance = random.randint(20, 60)
self.distance_traveled += travel_distance
self.days_passed += 1
# Consuming food and stamina
for character in self.characters:
if character.alive:
food_consumed = random.randint(5, 15)
character.food -= food_consumed
if character.food <= 0:
character.health -= 10
if character.health <= 0:
character.alive = False
# Stamina consumption based on distance
stamina_consumed = travel_distance // 10
character.stamina -= stamina_consumed
if character.stamina <= 0:
character.health -= 5
if character.health <= 0:
character.alive = False
else:
# Recover some stamina if not exhausted
character.stamina += random.randint(5, 10)
if character.stamina > 100:
character.stamina = 100
event_message = self.trigger_event(player_choices)
weather_message = self.update_weather()
# Check for game end
if self.distance_traveled >= self.distance_to_travel:
return "Congratulations! You've reached your destination!", False
return f"Day {self.days_passed}: You traveled {travel_distance} miles.\n{event_message}\n{weather_message}", True
def trigger_event(self, player_choices=None):
event = random.choice(self.events)
message = ""
if event == "found food":
food_found = random.randint(20, 50)
self.supplies.food += food_found
message = f"You found {food_found} units of food!"
elif event == "lost food":
food_lost = random.randint(10, 30)
self.supplies.food = max(self.supplies.food - food_lost, 0)
message = f"You lost {food_lost} units of food due to spoilage!"
elif event == "health issues":
for character in self.characters:
if character.alive:
health_loss = random.randint(5, 20)
character.health -= health_loss
message += f"{character.name} lost {health_loss} health!\n"
if character.health <= 0:
character.alive = False
message += f"{character.name} has died from health issues.\n"
elif event == "disease outbreak":
for character in self.characters:
if character.alive:
health_loss = random.randint(15, 35)
character.health -= health_loss
message += f"{character.name} contracted a disease and lost {health_loss} health!\n"
if character.health <= 0:
character.alive = False
message += f"{character.name} has died from the disease.\n"
elif event == "friendly encounter":
food_shared = random.randint(20, 40)
self.supplies.food += food_shared
message = f"You encountered friendly travelers who shared {food_shared} units of food!"
elif event == "river crossing":
success = random.choice([True, False])
if success:
message = "You successfully crossed the river without issues."
else:
health_loss = random.randint(10, 25)
for character in self.characters:
if character.alive:
character.health -= health_loss
message = f"Attempting to cross the river failed! All characters lost {health_loss} health."
elif event == "bandit attack":
ammo_used = random.randint(5, 15)
if self.supplies.ammo >= ammo_used:
self.supplies.ammo -= ammo_used
message = "Bandits attacked! You defended successfully using your ammo."
else:
health_loss = random.randint(10, 30)
for character in self.characters:
if character.alive:
character.health -= health_loss
message = f"Bandits attacked! You lacked ammo and lost {health_loss} health."
elif event == "weather storm":
weather_impact = random.choice(["heavy rain", "snowstorm", "heatwave"])
self.weather = weather_impact
for character in self.characters:
if character.alive:
stamina_loss = random.randint(10, 20)
character.stamina -= stamina_loss
if character.stamina < 0:
character.stamina = 0
message = f"A {weather_impact} hits your group, reducing your stamina."
elif event == "market encounter":
# Player can choose to trade
if player_choices and 'market_trade' in player_choices:
trade_choice = player_choices['market_trade']
if trade_choice == 'buy_food':
cost = 10
amount = 50
if self.supplies.food >= cost:
self.supplies.food -= cost
message = f"You bought {amount} units of food."
else:
message = "Not enough food to buy more food."
elif trade_choice == 'buy_ammo':
cost = 20
amount = 25
if self.supplies.food >= cost:
self.supplies.food -= cost
self.supplies.ammo += amount
message = f"You bought {amount} units of ammo."
else:
message = "Not enough food to buy ammo."
else:
message = "You decided not to trade."
else:
message = "You came across a market but chose not to trade."
return message.strip()
def update_weather(self):
# Simple weather cycle
weather_options = ["Sunny", "Cloudy", "Rainy", "Stormy", "Snowy", "Heatwave"]
self.weather = random.choice(weather_options)
return f"Current weather: {self.weather}"
def get_status(self):
status = f"Day: {self.days_passed}\n"
status += f"Distance Traveled: {self.distance_traveled}/{self.distance_to_travel} miles\n"
status += f"Weather: {self.weather}\n\n"
status += "Supplies:\n"
status += str(self.supplies) + "\n\n"
status += "Characters:\n"
for character in self.characters:
status += str(character) + "\n"
return status
def save_game(self, filename='savegame.json'):
data = {
'distance_traveled': self.distance_traveled,
'days_passed': self.days_passed,
'characters': [char.to_dict() for char in self.characters],
'supplies': self.supplies.to_dict(),
'weather': self.weather
}
with open(filename, 'w') as f:
json.dump(data, f)
return "Game saved successfully."
def load_game(self, filename='savegame.json'):
try:
with open(filename, 'r') as f:
data = json.load(f)
self.distance_traveled = data.get('distance_traveled', 0)
self.days_passed = data.get('days_passed', 0)
self.characters = [Character.from_dict(char) for char in data.get('characters', [])]
self.supplies = Supply.from_dict(data.get('supplies', {}))
self.weather = data.get('weather', "Sunny")
return "Game loaded successfully."
except FileNotFoundError:
return "No saved game found."
# ---------------------- BuySuppliesDialog Class ----------------------
class BuySuppliesDialog(QDialog):
def __init__(self, game, parent=None):
super().__init__(parent)
self.game = game
self.setWindowTitle("Buy Supplies")
self.setModal(True)
self.layout = QFormLayout()
self.food_spin = QSpinBox()
self.food_spin.setRange(0, 500)
self.food_spin.setValue(0)
self.layout.addRow("Food (Cost: 1 unit):", self.food_spin)
self.ammo_spin = QSpinBox()
self.ammo_spin.setRange(0, 200)
self.ammo_spin.setValue(0)
self.layout.addRow("Ammo (Cost: 2 units):", self.ammo_spin)
self.clothing_spin = QSpinBox()
self.clothing_spin.setRange(0, 200)
self.clothing_spin.setValue(0)
self.layout.addRow("Clothing (Cost: 3 units):", self.clothing_spin)
self.tools_spin = QSpinBox()
self.tools_spin.setRange(0, 200)
self.tools_spin.setValue(0)
self.layout.addRow("Tools (Cost: 4 units):", self.tools_spin)
self.submit_btn = QPushButton("Buy")
self.submit_btn.clicked.connect(self.buy)
self.layout.addRow(self.submit_btn)
self.setLayout(self.layout)
def buy(self):
total_cost = (self.food_spin.value() * 1 +
self.ammo_spin.value() * 2 +
self.clothing_spin.value() * 3 +
self.tools_spin.value() * 4)
if self.game.supplies.food < total_cost:
QMessageBox.warning(self, "Insufficient Supplies", "Not enough food to buy supplies.")
return
self.game.supplies.food -= total_cost
self.game.supplies.food += self.food_spin.value()
self.game.supplies.ammo += self.ammo_spin.value()
self.game.supplies.clothing += self.clothing_spin.value()
self.game.supplies.tools += self.tools_spin.value()
QMessageBox.information(self, "Purchase Successful", f"Bought supplies for {total_cost} food units.")
self.accept()
# ---------------------- MainWindow Class ----------------------
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Oregon Trail - Enhanced Version")
self.setGeometry(100, 100, 800, 600)
self.game = OregonTrailGame()
self.layout = QVBoxLayout()
# Intro Section
self.intro_label = QLabel("Welcome to the Oregon Trail Game!")
self.intro_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.intro_label.setStyleSheet("font-size: 24px; font-weight: bold;")
self.layout.addWidget(self.intro_label)
# Character Setup
self.character_input = QLineEdit(self)
self.character_input.setPlaceholderText("Enter character names (comma separated)")
self.layout.addWidget(self.character_input)
self.setup_button = QPushButton("Setup Characters", self)
self.setup_button.clicked.connect(self.setup_characters)
self.layout.addWidget(self.setup_button)
# Buy Supplies Button
self.buy_supplies_button = QPushButton("Buy Supplies", self)
self.buy_supplies_button.clicked.connect(self.buy_supplies)
self.buy_supplies_button.setEnabled(False)
self.layout.addWidget(self.buy_supplies_button)
# Travel Section
self.travel_button = QPushButton("Travel", self)
self.travel_button.clicked.connect(self.travel)
self.travel_button.setEnabled(False)
self.layout.addWidget(self.travel_button)
# Save and Load Buttons
self.save_button = QPushButton("Save Game", self)
self.save_button.clicked.connect(self.save_game)
self.save_button.setEnabled(False)
self.layout.addWidget(self.save_button)
self.load_button = QPushButton("Load Game", self)
self.load_button.clicked.connect(self.load_game)
self.layout.addWidget(self.load_button)
# Status Display
self.status_display = QTextEdit(self)
self.status_display.setReadOnly(True)
self.layout.addWidget(self.status_display)
# Progress Bar
self.progress_bar = QProgressBar(self)
self.progress_bar.setMaximum(self.game.distance_to_travel)
self.progress_bar.setValue(self.game.distance_traveled)
self.layout.addWidget(self.progress_bar)
self.setLayout(self.layout)
self.setStyleSheet("""
QWidget {
background-color: #1e1e1e;
color: #dcdcdc;
font-family: Arial, sans-serif;
font-size: 14px;
}
QLineEdit, QPushButton, QTextEdit, QProgressBar {
padding: 8px;
margin: 5px 0;
}
QPushButton {
background-color: #3a3a3a;
border: none;
color: #dcdcdc;
cursor: pointer;
}
QPushButton:hover {
background-color: #5a5a5a;
}
QProgressBar {
height: 25px;
}
""")
def setup_characters(self):
names = [name.strip() for name in self.character_input.text().split(',') if name.strip()]
if not names:
QMessageBox.warning(self, "Input Error", "Please enter at least one character name.")
return
self.game.setup_characters(names)
self.status_display.append("Characters have been set up:")
for character in self.game.characters:
self.status_display.append(str(character))
self.travel_button.setEnabled(True)
self.buy_supplies_button.setEnabled(True)
self.save_button.setEnabled(True)
self.update_status()
def buy_supplies(self):
dialog = BuySuppliesDialog(self.game, self)
if dialog.exec():
self.status_display.append("Supplies purchased.")
self.update_status()
def travel(self):
# Check for special events that require choices
player_choices = {}
upcoming_event = random.choice(["market_encounter", "none"])
if upcoming_event == "market_encounter":
choice, ok = QMessageBox.question(
self, "Market Encounter",
"You encountered a market. Do you want to trade?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
)
if ok and choice == QMessageBox.StandardButton.Yes:
# For simplicity, we'll simulate a trade
player_choices['market_trade'] = 'buy_food'
else:
player_choices['market_trade'] = 'no_trade'
message, continue_game = self.game.travel(player_choices)
self.status_display.append(message)
self.update_status()
# Check for game over or victory
if not continue_game:
if self.game.distance_traveled >= self.game.distance_to_travel:
QMessageBox.information(self, "Victory", "You've successfully completed the Oregon Trail!")
else:
QMessageBox.information(self, "Game Over", "All your characters have perished.")
self.close()
def update_status(self):
self.status_display.append("\n--- Current Status ---")
self.status_display.append(self.game.get_status())
self.progress_bar.setValue(self.game.distance_traveled)
self.status_display.append("-----------------------\n")
def save_game(self):
message = self.game.save_game()
QMessageBox.information(self, "Save Game", message)
def load_game(self):
message = self.game.load_game()
QMessageBox.information(self, "Load Game", message)
self.status_display.append("Game Loaded:")
self.status_display.append(self.game.get_status())
self.travel_button.setEnabled(True)
self.buy_supplies_button.setEnabled(True)
self.save_button.setEnabled(True)
self.progress_bar.setValue(self.game.distance_traveled)
# ---------------------- Main Execution ----------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Detailed Explanation of Enhancements:
-
Supply Management:
Supply Class: Tracks various supplies (food, ammo, clothing, tools). Methods to convert to and from dictionaries facilitate easy saving and loading.
- Buying Supplies: Implemented
BuySuppliesDialog which allows players to purchase supplies before or during the journey. The cost increases with the amount of supplies purchased.
-
Character Attributes:
- Extended
Character Class: Added stamina and morale attributes to each character, affecting their performance and well-being.
- Stamina Management: Traveling consumes stamina, and players can recover it. If stamina depletes, it negatively affects health.
-
Diverse Events with Choices:
- Additional Events: Introduced events like
river crossing, bandit attack, weather storm, and market encounter which require player decisions affecting the outcome.
- Player Choices: During certain events like market encounters, players can make choices that influence supplies and character statuses.
-
Dynamic UI:
- Status Display: The
QTextEdit widget provides comprehensive updates on the game state, including day count, distance traveled, weather, supplies, and character statuses.
- Progress Bar: Visual representation of the journey progress using
QProgressBar.
-
Map and Progress Tracking:
- Distance Tracking: The game tracks
distance_traveled against distance_to_travel, providing milestones and a sense of progression.
- Weather Effects: Weather conditions randomly change and impact the journey, affecting stamina and health.
-
Saving and Loading Game State:
- Persistence: The game state can be saved to and loaded from a JSON file (
savegame.json). This includes all essential data like characters, supplies, distance, and weather.
- Added and buttons for user interaction.
Further Enhancements and Ideas:
To make the game even more advanced, consider implementing the following features:
-
Inventory Management:
- Allow players to manage their inventory, use items (like medicine to restore health), and craft tools.
-
Character Skills and Traits:
- Assign unique skills or traits to characters that can influence event outcomes (e.g., a character skilled in hunting can gather extra food).
-
Detailed Map:
- Implement a visual map showing the journey progress, landmarks, and upcoming events.
-
Quests and Missions:
- Introduce side quests or missions that provide rewards or additional story elements.
-
Dynamic Event System:
- Create a more sophisticated event system with branching narratives based on player choices.
-
Multimedia Elements:
- Add images, sounds, and animations to enhance the user experience.
-
Difficulty Levels:
- Offer different difficulty settings that adjust event frequencies, resource consumption rates, and challenges.
-
End-Game Scoring:
- Implement a scoring system based on various factors like time taken, resources remaining, and characters surviving.
Implementing these features would require a more extensive codebase and possibly refactoring the current structure for scalability. However, the provided enhanced version sets a solid foundation for a more advanced Oregon Trail game.