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

Skribbl.io风格猜词游戏出现IndexError:列表索引越界求助

Skribbl.io风格猜词游戏错误修复及功能优化

问题概述

开发Skribbl.io风格猜词游戏时触发IndexError: list index out of range错误,同时存在下划线打印不符合预期的问题。

报错回溯

Traceback (most recent call last):
File "/Users/kalybarly/Skribbl.py", line 37, in 
print(f'Letter {word_place}: {letter_hint[word_place]}')
IndexError: list index out of range

原始代码

from random import choice, randint
from time import sleep

words = ['Python','Turn','Fall','Call','Word','Skribbl','Nintendo','Sega','Mitsubishi','Walmart','Egg','Tomato','Toe','Soup','Japanese','Chinese','Willy','Programming','Baller','Says','Said','Fight','Road','Store','Core','Mighty','Lottery','Night']
word = choice(words)
place = randint(0,len(word))

for i in range(0,len(words)):
    print('_')

print(f'Length of word: {len(word)}')

guess = str(input('Enter word here: '))

while guess != word:
    guess = str(input('Enter word here: '))

    sleep(randint(1,40))

    print(f'Hint: Letter {place}: {word[place]}')

if guess == word:
    print(word)

预期需求(中文翻译)

  1. 打印与目标单词长度一致的下划线(当前仅在首次猜测后生效,不符合预期)
  2. 猜对后输出目标单词(如:Nintendo、Sega)

错误原因

  1. 索引越界:randint(0, len(word))会生成包含len(word)的数值,但字符串索引范围是0到len(word)-1,当place等于len(word)时,访问word[place]必然触发索引越界。
  2. 下划线打印错误:循环遍历的是单词列表长度len(words),而非目标单词长度len(word),导致下划线数量与目标单词不匹配。
  3. 猜测逻辑漏洞:首次输入的guess未进入循环判断,直接跳过了错误检查环节。

修复后的代码

from random import choice, randint
from time import sleep

words = ['Python','Turn','Fall','Call','Word','Skribbl','Nintendo','Sega','Mitsubishi','Walmart','Egg','Tomato','Toe','Soup','Japanese','Chinese','Willy','Programming','Baller','Says','Said','Fight','Road','Store','Core','Mighty','Lottery','Night']
word = choice(words)
# 生成合法索引:范围0到len(word)-1
place = randint(0, len(word)-1)

# 打印与目标单词长度一致的下划线(同一行显示)
for _ in range(len(word)):
    print('_', end=' ')
print()

print(f'单词长度: {len(word)}')

# 优化循环逻辑,覆盖首次猜测场景
while True:
    guess = input('请输入猜测的单词: ')
    if guess == word:
        print(word)
        break
    # 猜错后给出提示,缩短等待时间(原40秒过长)
    sleep(randint(1, 5))
    print(f'提示: 第{place+1}个字母是: {word[place]}')

修复说明

  • 修正索引范围:将randint(0, len(word))改为randint(0, len(word)-1),确保索引在字符串合法范围内。
  • 修正下划线打印:循环次数改为len(word),并用end=' '让下划线在同一行显示,符合猜词游戏视觉习惯。
  • 优化猜测逻辑:使用while True循环,确保首次输入也会被检查,猜对后直接输出目标单词并退出循环。
  • 体验优化:将等待提示的时间从1-40秒缩短为1-5秒,同时将界面提示改为中文,提升使用体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:03:15