Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Building a Text-Based Survival Adventure Game in Python

Tech 2

A text-based survival adventure game can be created using Python by implementing a branching narrative structure with interactive choices, mini-games, and scoring mechanics. The game simulates a post-apocalyptic scenario where players make decisions that affect their survival outcome.

Core Game Structure

The game utilizes a list of dictionaries to store questions, options, scores, and navigation logic. Each dictionary represents a game state with the following keys:

  • id: Unique identifier for the question.
  • question: The text displayed to the player.
  • options: A list of possible choices.
  • scores: A dictionary mapping each option to a score value.
  • next_question: A dictionary mapping each option to the next question ID or a string identifier for endings.

Example of a game state dictionary:

scenario = {
    "identifier": 1,
    "prompt": "You wake up in a ruined city. Do you search for supplies or hide?",
    "choices": ["A. Search for supplies", "B. Hide in a building"],
    "points": {"A": 5, "B": 2},
    "next_step": {"A": 2, "B": 3}
}

Game Loop Implementation

The main game loop processes player inputs, updates scores, and navigates through questions based on choices. It uses functions for input validation and slow text display to enhance user experience.

import time
import random
import math

def display_text_slowly(message):
    for character in message:
        print(character, end='', flush=True)
        time.sleep(0.02)
    print()

def get_player_choice(prompt, valid_choices):
    while True:
        user_selection = input(prompt).upper()
        if user_selection in valid_choices:
            return user_selection
        print("Invalid selection. Please choose from the available options.")

def calculate_survival_time(days):
    if days < 0:
        raise ValueError("Days cannot be negative.")
    years = days // 365
    remaining_days = days % 365
    months = remaining_days // 30
    days_left = remaining_days % 30
    return years, months, days_left

Mini-Games for Enhanced Gameplay

Three mini-games are integrated to assess player attributes: luck, reaction time, and physical fitness. These scores modify the final survival outcome.

Luck Assessment Game

This game tests intuition by guessing a random number, with fewer attempts yielding higher luck scores.

def assess_luck():
    target_value = random.randint(1, 60)
    tries = 0
    luck_points = 10
    print("Test your intuition by guessing where the second hand points (0-60).")
    while True:
        try:
            player_guess = int(input("Enter your guess: "))
            tries += 1
            if luck_points >= 0:
                luck_points -= 1
            print(f"Attempts used: {tries}")
            if player_guess < target_value:
                print("Too low.")
            elif player_guess > target_value:
                print("Too high.")
            else:
                print(f"Correct! Your luck score is: {luck_points}")
                return luck_points
        except ValueError:
            print("Please enter a valid integer.")

Reaction Time Test

Measures how quickly the player responds to a prompt, with faster times increasing the reaction score.

def test_reaction():
    print("Test your reaction time. Press Enter as soon as you see the message.")
    delay = random.uniform(5, 15)
    time.sleep(delay)
    start = time.time()
    input("Eliminate the threat now!!!")
    end = time.time()
    response_duration = end - start
    return 1.5 - response_duration

Physical Fitness Evaluation

Calculates a fitness score based on BMI, sprint time, and long-distance run performance.

def evaluate_fitness():
    fitness_score = 0
    while True:
        try:
            height = float(input("Enter your height in meters: "))
            weight = float(input("Enter your weight in kilograms: "))
            if height <= 0 or weight <= 0:
                print("Height and weight must be positive values.")
                continue
            bmi = weight / (height ** 2)
            while True:
                try:
                    sprint_time = float(input("Enter your 50m sprint time in seconds: "))
                    long_run_time = float(input("Enter your 1000m run time in seconds: "))
                    if sprint_time <= 0 or long_run_time <= 0:
                        print("Times must be positive values.")
                        continue
                    break
                except ValueError:
                    print("Please enter valid numbers.")
            break
        except ValueError:
            print("Invalid input. Enter numeric values.")
        except ZeroDivisionError:
            print("Height cannot be zero.")
    if 18.5 < bmi < 23.9:
        fitness_score += 1
    else:
        fitness_score += 0.5
    if sprint_time <= 6.8:
        fitness_score += 1
    elif 6.8 < sprint_time < 7.5:
        fitness_score += 0.8
    else:
        fitness_score += 0.5
    if long_run_time <= 180:
        fitness_score += 1
    elif 180 < long_run_time < 210:
        fitness_score += 0.8
    else:
        fitness_score += 0.5
    return fitness_score

Final Score Calculation and Outcome

After completing the narrative choices, the game calculates a final survival score by combining choice scores with mini-game results. The outcome is displayed as survival time with a descriptive message.

def determine_outcome():
    reaction_modifier = test_reaction()
    luck_factor = assess_luck()
    fitness_multiplier = evaluate_fitness()
    # Example calculation: adjust based on game design
    survival_score = ((choice_total * luck_factor) ** reaction_modifier) * fitness_multiplier
    survival_score *= 6
    total_days = math.ceil(survival_score)
    years, months, days = calculate_survival_time(total_days)
    print(f"You survived for {years} years, {months} months, and {days} days.")
    if survival_score <= 30:
        print("Too reckless, perished early.")
    elif 30 < survival_score <= 100:
        print("Briefly experienced the apocalypse before falling.")
    elif 100 < survival_score <= 1000:
        print("Endured the apocalypse for a while but ultimately succumbed.")
    elif 1000 < survival_score <= 2000:
        print("Overcame the apocalypse through wisdom and courage, starting anew.")
    else:
        print("Became a savior, leading humanity to rebuild civilization.")

Deployment and Packaging

The game can be packgaed into an executable using PyInstaller and deployed on platforms like Gitee for version control. For cloud execution, set up an elastic cloud server, connect via SSH tools like PuTTY, transfer files with WinSCP, and run the Python script.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.