gpt4 book ai didi

python-2.7 - 我在错误检查和循环方面遇到麻烦

转载 作者:行者123 更新时间:2023-12-03 08:53:22 25 4
gpt4 key购买 nike

这是一个多文件代码,因此将需要所有部分来运行它,因为代码按预期工作,可以从文本文件中选择2个神奇宝贝,并让用户和计算机选择攻击类型。

我遇到的问题是使Battle函数循环,然后通过错误检查来防止作弊,以确保使用了有效的攻击并且仅输入了str。

我没有要求您全力以赴为我做所有工作,但我被困住了,不知道还要做些什么,因此对您的帮助将不胜感激

import random
from fileopenpoke import select_random

f = open('pokemon.txt', 'r',)
l = f.read().splitlines()

# important things
# the attacks
Attack = ["Air", "Water", "Grass"]

# Score/attack
def poke_score():
score = random.choice(Attack)
return score

# things
user_poke = select_random(l)
enemy_poke = select_random(l)
enemy_score = poke_score()

# staging
print ("5 matches Best 3 out of 5")
print user_poke, "Vs.", enemy_poke
print ("Select Attack")

# user select attack
def make_score():
score = raw_input("Air Water or Grass")
return score
user_score = make_score()
# error checking
# output and battle sequence
def battle():
global user_score, enemy_score
etal = 0
utal = 0
match = 0
# forfeits match if no attack or incorrect attack is given

if user_score == "Air" and enemy_score == "Grass":
etal = etal + 1
match = match + 1
print enemy_poke, "used", enemy_score, user_poke, "used", user_score, enemy_poke, "Match Won!"
print "current score", utal, "/", etal
print "match", match
return etal, match

elif user_score == "Grass" and enemy_score == "Water":
etal = etal + 1
match = match + 1
print enemy_poke, "used", enemy_score, user_poke, "used", user_score, enemy_poke, "Match Won!"
print "current score", utal, "/", etal
print "match", match
return etal, match

elif user_score == "Water" and enemy_score == "Air":
etal = etal + 1
match = match + 1
print enemy_poke, "used", enemy_score, user_poke, "used", user_score, enemy_poke, "Match Won!"
print "current score", utal, "/", etal
print "match", match
return etal, match

elif user_score == enemy_score:
match = match + 1
print enemy_poke, "used", enemy_score, user_poke, "used", user_score, "Match was a Tie!!"
print "match", match
return match

else:
utal = utal + 1
match = match + 1
print enemy_poke, "used", enemy_score, user_poke, "used", user_score, user_poke, "Match Won!"
print "current score", utal, "/", etal
print "match", match
return utal, match


battle()

这是文件导入,很小,不需要,但是对我的分配来说是必需的
# pokemon list
import random
def select_random(l):
pokepick = random.choice(l)
return pokepick

这是口袋妖怪 list ,它很大,因此生病了,只需将其链接
https://www.dropbox.com/s/trlv60u48rllfc0/pokemon.txt?dl=0

最佳答案

错误检查用户输入的一种简单方法是使用while循环。例如:

def make_score():
while True:
score = raw_input('Air, Water, or Grass? ')
if score in Attack: break
else:
print 'Invalid selection.'
return score

这将循环输入,直到用户输入与您的列表项之一(在“攻击”列表中)匹配的字符串为止。

关于python-2.7 - 我在错误检查和循环方面遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34890645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com