Python无列表实现剪刀石头布游戏:函数未定义问题求助
问题解决:函数未定义及代码逻辑修复
核心问题分析
你遇到的getRandomShape未定义错误,根源是函数调用顺序错误:你在getRandomShape函数定义之前就执行了possibleHands = getRandomShape(computerHand),Python解释器从上到下执行代码,此时还没读到函数定义,自然找不到这个函数。
除此之外,代码还有其他逻辑问题需要修正,才能符合“不使用列表”的要求并正常运行:
computerHand在调用时未定义,属于无效传参getRandomShape当前仅打印形状,未返回实际值,无法用于后续胜负判断- 名字输入被放在循环内,每轮游戏都会重复要求输入
- 依赖列表的
random.choice(possibleHands)不符合“不使用列表”的要求
分步修复方案
- 调整函数定义与调用顺序:把所有函数定义移到代码最前面(导入模块之后),确保调用前函数已被定义。
- 重构
getRandomShape函数:去掉无用参数,改为返回对应的形状字符串(而非仅打印),满足不使用列表的要求。 - 修正游戏循环逻辑:将名字输入移到循环外,避免重复输入;直接调用
getRandomShape生成电脑出的形状,替代依赖列表的写法。 - 修正参数传递问题:删除无效的
computerHand传参,函数内部直接生成随机形状。
修正后的完整代码
import random def getRandomShape(): # 生成1-3的随机数,返回对应的形状字符串 shape_num = random.randint(1, 3) if shape_num == 1: return 'Scissors' elif shape_num == 2: return 'Stone' else: return 'Paper' def checkForWinner(playerHand, computerHand): if(playerHand == 'Stone' and computerHand == 'Paper'): print('you lost') return 'cpu' elif(playerHand == 'Stone' and computerHand == 'Scissors'): print('you won') return 'player' elif(playerHand == 'Scissors' and computerHand == 'Paper'): print('you won') return 'player' elif(playerHand == 'Scissors' and computerHand == 'Stone'): print('you lost') return 'cpu' elif(playerHand == 'Paper' and computerHand == 'Scissors'): print('you lost') return 'cpu' elif(playerHand == 'Paper' and computerHand == 'Stone'): print('you won') return 'player' else: print('its a tie. play again') return 'tie' # 初始化游戏状态 print('welcome to scissors paper stone') cpuScore = 0 playerScore = 0 tieScore = 0 # 获取玩家名字(只输入一次) name = input('Please enter your name: ') # 游戏主循环,先到3分获胜 while(playerScore != 3 and cpuScore != 3): # 获取玩家有效输入 while True: playerHand = input(f'Round {playerScore + cpuScore + tieScore + 1}: {name}, please choose a shape: ') if playerHand in ['Scissors', 'Paper', 'Stone']: break else: print('invalid input, case sensitive. Try again') # 生成电脑的形状(不使用列表) computerHand = getRandomShape() # 输出双方选择 print('your Hand: ', playerHand) print('cpu Hand: ', computerHand) # 判断胜负并更新分数 results = checkForWinner(playerHand, computerHand) if results == 'player': playerScore += 1 elif results == 'cpu': cpuScore += 1 else: tieScore += 1 # 输出当前比分 print(f'your score: {playerScore} | CPU: {cpuScore} | Ties: {tieScore}') print('gg game over')
关键修复点说明
- 函数
getRandomShape现在返回字符串而非打印,这样可以将返回值赋值给computerHand,用于后续的胜负判断。 - 移除了所有列表相关的代码,完全通过随机数映射实现电脑出拳,符合“不使用列表”的要求。
- 名字输入移到循环外,避免每轮重复输入,提升游戏体验。
- 调整了回合数的显示逻辑,根据当前比分动态计算回合数,更合理。
内容的提问来源于stack exchange,提问作者suprematzy
相关产品推荐
相关产品推荐

