开发Monopoly大富翁游戏报string index out of range错误如何解决
错误原因
你遇到的string index out of range报错核心来自两个逻辑错误:
- 变量被错误覆盖:你最开始定义的
Prices是存储所有地块价格的列表,但后续执行了Prices = Prices[generatedNum],直接把列表变量覆盖成了单个数字(比如150、250这类价格值)。 - 索引逻辑完全错误:
position是你从地块列表中取出的字符串类型的地块名,你写的position[Prices]本质是尝试从字符串中取下标为价格数字的字符,而大部分地块名长度只有几个字符,远小于价格数值,自然触发索引越界。
除此之外你的代码还有多处影响运行的问题:
- 缩进混乱,掷骰子、购买判断的逻辑大部分写在了
while True循环外部,只会执行一次,还会触发变量作用域报错 - 固定值(地块列表、价格列表、初始现金)放在循环内部重复初始化,属于冗余逻辑
- 位置值没有做边界处理,当累计步数超过39(两个列表长度都是40,合法下标为0~39)时也会触发索引越界
- 重复取值冗余,已经通过
position = monopoly[generatedNum]拿到了当前地块名,不需要再重新执行landmark = monopoly[generatedNum]
修复方案
直接参考下方调整后的代码即可运行:
import os, random # 兼容Windows和类Unix系统的清屏命令 os.system("cls||clear") player = input("hello, what is your name? ") # 固定值初始化放在循环外部 monopoly = ["Ga" , "Vastralanggatan", "Allmanning", "Hornsgsgatan", "Inkomstskatt", "Sodrastation", "Folkungagatan", "Chans", "Gotgatan", "Ringvagen", "Besokfangelse", "StEriksgatan", "Elverket", "Odengatan", "Valhallavagen", "ostra station", "Sturegatan", "Allmanning", "Karlavagen", "Narvavagen", "Friparkering", "Strandvagen", "Chans", "Kungstradsgardsgatan", "Hamngatan", "Centralstation", "Vasagatan", "Kungsgatan", "Vattenledningsverket", "Stureplan", "Gaifangelse", "GustavAdolfsTorg", "Drottninggatan", "Allmanning", "Diplomatstaden", "Norrastation", "Chans", "Centrum", "Betalalyxskatt", "Norrmalmstorg"] Prices = [150 , 250 , 130 , 50 , 150 , 250 , 130 , 50 , 150 , 250 , 130 , 50, 50, 250 , 130 , 50 , 150 , 250 , 130 , 50, 50, 250 , 130 , 50 , 150 , 250 , 130 , 50, 50, 250 , 130 , 50 , 150 , 250 , 130 , 50, 50, 250 , 130 , 50] player1_cash = 1500 current_position = 0 # 初始位置在起点 while True: player1_throw = input(player + " press any key to throw the dice") dice1 = random.randint(1,6) dice2 = random.randint(1,6) step = dice1 + dice2 # 位置模40处理,保证永远在合法下标范围内 current_position = (current_position + step) % 40 position_name = monopoly[current_position] position_price = Prices[current_position] print(player + " you threw", step) print("you landed on", position_name) buy_landmark = input("do you want to buy " + position_name + "? J/N ") if buy_landmark.strip().upper() == "J": if player1_cash >= position_price: print("you have bought", position_name) player1_cash -= position_price print("you have", player1_cash, "left") else: print("you don't have enough cash to buy this land")
内容的提问来源于stack exchange,提问作者Ozzy
相关产品推荐
相关产品推荐

