我有错误检查和循环的麻烦

时间:2016-01-20 02:42:55

标签: python-2.7 loops error-handling

这是一个多文件代码,因此需要运行它的所有部分,因为代码按预期工作,即从文本文件中选择2个口袋妖怪并让用户和计算机选择攻击类型。

我遇到的问题是让战斗功能循环,然后通过错误检查防止作弊,以确保使用了有效的攻击并且只输入了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

这是口袋妖怪列表,其相当大的生病只是链接它 https://www.dropbox.com/s/trlv60u48rllfc0/pokemon.txt?dl=0

1 个答案:

答案 0 :(得分: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

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