You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python动态读取CSV行开发自制冒险游戏引擎?

Dynamic Adventure Game Engine Implementation for CSV-Based Stories

Got it, let's refactor your static code to handle any number of dynamic options from your CSV, while keeping the "Save game" feature intact. Here's a step-by-step solution:

Key Concepts to Address

Your CSV structure follows: [剧情提示, 选项1, 选项2, ..., 选项X, 跳转1, 跳转2, ..., 跳转X] — so we need to:

  • Dynamically extract the variable number of options and their corresponding jump targets
  • Generate numbered options without hardcoding
  • Validate user input to avoid crashes
  • Handle the fixed "Save game" option alongside story choices

Full Dynamic Implementation

Assuming you've already loaded your CSV into a list called story (using csv.reader or similar), here's the core game loop:

import csv

# First, load your CSV story file (example setup)
with open("adventure_story.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    story = list(reader)

current_line = 0  # Start at the first story row (0-based index)

while True:
    current_row = story[current_line]
    
    # Extract prompt, dynamic options, and jump targets
    story_prompt = current_row[0]
    # Calculate how many story options exist (total cells minus 1 prompt, split equally into options/jumps)
    num_story_options = (len(current_row) - 1) // 2
    story_options = current_row[1 : 1 + num_story_options]
    jump_targets = current_row[1 + num_story_options : ]
    
    # Display story prompt
    print("\n" + story_prompt)
    
    # Display dynamic story options with auto-numbering
    for option_num, option_text in enumerate(story_options, start=1):
        print(f"{option_num} - {option_text}")
    
    # Add fixed "Save game" option (always the last choice)
    save_option_num = num_story_options + 1
    print(f"{save_option_num} - Save game")
    
    # Get and validate user input
    while True:
        try:
            user_choice = int(input("\nEnter your choice: "))
            if 1 <= user_choice <= save_option_num:
                break
            print(f"Please enter a number between 1 and {save_option_num}")
        except ValueError:
            print("Please enter a valid whole number.")
    
    # Handle user selection
    if user_choice == save_option_num:
        # Insert your save game logic here (e.g., save current_line to a file)
        with open("save_game.txt", "w") as save_file:
            save_file.write(str(current_line))
        print("✅ Game saved successfully!")
    else:
        # Convert choice to 0-based index for jump_targets, adjust for 1-based CSV row numbers
        target_row = int(jump_targets[user_choice - 1]) - 1
        current_line = target_row

Breakdown of Key Features

  • Dynamic Option Parsing: num_story_options = (len(current_row) - 1) // 2 calculates how many story choices exist by splitting the remaining CSV cells (after the prompt) equally into options and jump targets.
  • Auto-Numbered Options: enumerate(story_options, start=1) automatically assigns sequential numbers to each option, no hardcoding needed.
  • Input Validation: The inner loop ensures users enter a valid number within the choice range, preventing crashes from invalid inputs.
  • 1-Based to 0-Based Conversion: Since your CSV uses 1-based row numbers for jumps (e.g., "第2行"), we subtract 1 to match Python's 0-based list indexing.
  • Persistent Save Feature: The example saves the current story line to a text file — you can expand this to save more state if needed.

内容的提问来源于stack exchange,提问作者Alex Doiron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:00:17