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

Python射击游戏中自定义shoot函数调用其他函数报错问题

问题原因

  • shoot 函数定义时要求传入result参数,但你在触发游戏逻辑if play == "y"的分支里调用shoot()时没有传任何参数,直接触发参数不匹配报错。
  • hit/miss/both三个函数内部修改全局变量playpoints/comppoints/playhealth/comphealth时,没有用global声明变量为全局作用域,会触发「局部变量赋值前引用」的报错。
  • shoot函数内部的判断逻辑错误:elif miss:实际是判断miss这个函数对象的布尔值,永远为真,你实际需要的是elif result == miss:。
  • shoot函数的else分支里调用both()时没有传入要求的player和comp参数,触发参数不匹配报错。
  • 你没有提前调用hit/miss/both函数生成result值,也没有提前判断玩家和电脑的随机数大小匹配对应逻辑,整个执行顺序完全混乱。
  • 输入判断只匹配了小写的y,没有兼容大写Y的情况,用户输入大写Y会直接跳过游戏逻辑。

修复方案

先调整执行顺序:获取用户输入后,先判断玩家和电脑的随机数值大小,调用对应函数拿到result,再把result传给shoot函数,同时修复所有作用域、参数、判断的错误,修复后完整代码如下:

playpoints = 0
comppoints = 0
playhealth = 100
comphealth = 100
play = input("Would you like to play a game? (Y//N)").lower()

import random
player = random.randint(0, 10)
comp = random.randint(0,10)

def hit(player, comp):
    global playpoints, comppoints, comphealth
    playpoints += 10
    comppoints -= 5
    comphealth -= 10
    return hit

def miss(player, comp):
    global playpoints, playhealth, comppoints
    playpoints -= 5
    playhealth -= 10
    comppoints += 10
    return miss

def both(player, comp):
    global comphealth, comppoints, playhealth, playpoints
    comphealth -= 10
    comppoints -= 5
    playhealth -= 10
    playpoints -= 5
    return both
    
def shoot(result):
    if result == hit:
        print("You shot me!\n")
        print("Health Totals:\n" + "You: " + str(playhealth) + " Me: "+ str(comphealth))
    elif result == miss:
        print("Yes! I got you!")
        print("Health Totals:\n" + "You: " + str(playhealth) + " Me: "+ str(comphealth))
    else:
        print("What are the odds of that!")
        print("Health Totals:\n" + "You: " + str(playhealth) + " Me: "+ str(comphealth))
          
if play == "y":
    # 先判断随机数匹配对应逻辑
    if player > comp:
        result = hit(player, comp)
    elif player < comp:
        result = miss(player, comp)
    else:
        result = both(player, comp)
    # 把result传给shoot
    shoot(result)
   
print("Points\n"+"You: " + str(playpoints) + " Me:" + str(comppoints) )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:15:02