Python入门游戏代码逻辑问题求助:条件判断与循环异常
Python游戏逻辑问题修复方案
问题1:启动输入判断始终输出':('
错误代码:
go = input("") if go != "yes" or go != "sim": print(':(') else: print(':)')
错误原因:逻辑运算符误用。or表示任意一个条件成立就执行分支,无论输入"yes"还是"sim",总有一个!=条件为真,导致永远进入:(分支。
修复代码:
go = input("") # 改用and判断输入既不是yes也不是sim if go != "yes" and go != "sim": print(':(') else: print(':)') # 更简洁的写法(推荐) if go not in ("yes", "sim"): print(':(') else: print(':)')
问题2:商店模块while循环无法停止
错误代码:
while action != "exit" or destination != "sair":
错误原因:循环条件逻辑错误。or导致只要其中一个条件不满足就持续循环,比如输入"exit"后,destination != "sair"依然成立,循环不会终止。
修复代码:
# 只有当既没输入exit也没输入sair时,才继续循环 while action != "exit" and destination != "sair":
更直观的写法:
# 当输入exit或sair时,终止循环 while not (action == "exit" or destination == "sair"):
问题3:目的地判断的条件错误
错误代码:
if destination != "shop" or destination != "loja": print('invalid answer! (resposta inválida)')
错误原因:和问题1一致,or逻辑错误,无论输入"shop"还是"loja",总有一个!=条件成立,导致永远输出无效提示。
修复代码:
if destination != "shop" and destination != "loja": print('invalid answer! (resposta inválida)') # 更简洁的写法(推荐) if destination not in ("shop", "loja"): print('invalid answer! (resposta inválida)')
额外优化建议
商店循环中,输入错误时应跳过后续商店界面渲染,直接重新输入:
while action != "exit" and destination != "sair": destination = str(input('')) if destination not in ("shop", "loja"): print('invalid answer! (resposta inválida)') continue # 跳过后续代码,重新进入输入环节 # 输入正确时才渲染商店界面 print(""" ^ ^___^ ________ ) ) / ● ● \ Meow | | / / \ W / | |\ | / / / || | | ;| | ( ( /| || | | _|¡_ | \ \ / | || | | (____) | __\ \/ /| || |______________________________ | || | \__/| |_>|_> /\ | () | / / |________| _________________________________________/ / ___|___ _________________________________________\/ | rusty | (adaga usada) | dagger| | 50$ | |_______| () () _______________()_____________________________()_________________ ()_____________()_____________________________()_________________() () | () ___|___ |wooden | (vara de madeira) |stick | | 150$ | |_______| Type what you want to buy (digite o que você quer comprar) Or type "exit" to go to map (ou digite sair para voltar ao mapa) """) action = input('') # 后续购买逻辑...
内容的提问来源于stack exchange,提问作者Igor Tunner
相关产品推荐
相关产品推荐

