循环不正确然后崩溃

时间:2015-03-08 22:39:59

标签: python function loops

我有一段我正在为学校项目工作的代码,基本的想法是两个角色之间的争斗,用户可以为每个角色输入2个属性:力量和技能。现在还有技能和力量的修饰符,即玩家的技能和力量属性的差异,除以5然后分别向下舍入。然后每个玩家都有一个掷骰子,取决于谁获得了更高的掷骰,该玩家获得了添加到他们给定属性的技能和力量修饰符,而丢失的那个获得了从他们的分数中扣除的修饰符。然后重复直到其中一个的强度属性达到0,然后该玩家死亡并且游戏结束。

在我的代码中,骰子滚动功能运行两次,然后由于我无法识别的未知原因而崩溃。

import random
import time
import math
import sys

strength_mod = 0
skill_mod = 0

def delay_print(s):
    for c in s:
        sys.stdout.write( '%s' % c )
        sys.stdout.flush()
        time.sleep(0.05)

def str_mod(charone_str,chartwo_str):
    if charone_str > chartwo_str:
        top = charone_str
        bottom = chartwo_str
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc
    elif chartwo_str > charone_str:
        top = chartwo_str
        bottom = charone_str
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc
    elif charone_str == chartwo_str:
        top = charone_str
        bottom = chartwo_str
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc

def skl_mod(charone_skl, chartwo_skl):
    if charone_skl > chartwo_skl:
        top = charone_skl
        bottom = chartwo_skl;
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc
    elif chartwo_skl > charone_skl:
        top = chartwo_skl
        bottom = charone_skl
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc
    elif charone_skl == chartwo_skl:
        top = charone_skl
        bottom = chartwo_skl
        calc = top - bottom
        calc = calc / 5
        calc = math.floor(calc)
        return calc

def mods():
    global strength_mod
    global skill_mod
    strength_mod = str_mod(charone_strength, chartwo_strength)
    skill_mod = skl_mod(charone_skill, chartwo_skill)
    print "\nFor this battle, the strength modifier is:",strength_mod
    time.sleep(0.20)
    print "For this battle, the skill modifier is: ",skill_mod
    time.sleep(0.20)
    diceroll(charone, chartwo)
    print "\n"+str(charone)+"'s","dice roll is:",player1
    time.sleep(1)
    print "\n"+str(chartwo)+"'s","dice roll is:",player2

def diceroll(charone, chartwo):
    print "\n"+str(charone)+" will roll the 6 sided dice first!"
    time.sleep(0.5)
    global player1
    player1 = random.randint(1,6)
    delay_print("\nRolling dice!")
    global player2
    player2 = random.randint(1,6)
    time.sleep(0.5)
    print "\nNow",chartwo,"will roll the 6 sided dice!"
    time.sleep(0.5)
    delay_print("\nRolling dice!")

def battle(charone_str, chartwo_str, charone_skl, chartwo_skl, str_mod, skl_mod):
    global charone_strength
    global charone_skill
    global chartwo_strength
    global chartwo_skill
    if player1 == player2:
        print "\nThis round is a draw! No damage done"
    elif player1 > player2:
        charone_strength = charone_str + str_mod
        charone_skill = charone_skl + skl_mod
        chartwo_strength = charwo_skl - str_mod
        chartwo_skill = chartwo_skl - skl_mod
        print "\n"+charone+" won this round"
        print "\n"+"Character 1:",charone
        print "Strength:",charone_strength
        print "Skill:",charone_skill
        time.sleep(1)
        print "\nCharacter 2:",chartwo
        print "Strength:",chartwo_strength
        print "Skill:",chartwo_skill
    elif player2 > player1:
        chartwo_strength = chartwo_str + str_mod
        chartwo_skill = chartwo_skl + skl_mod
        charone_strength = charone_str - str_mod
        charone_skill = charone_skl - skl_mod
        print "\n"+chartwo+" won this round"
        print "\nCharacter 2:",chartwo
        print "Strength:",chartwo_strength
        print "Skill:",chartwo_skilll
        time.sleep(1)
        print "\n"+"Character 1:",charone
        print "Strength:",charone_strength
        print "Skill:",charone_skill

    if charone_skill >= 0:
        charone_skill = 0
    elif chartwo_skill >= 0:
        chartwo_skill = 0

    if charone_strength <= 0:
        print charone,"has died!",chartwo,"wins!"
    elif chartwo_strength <= 0:
        print chartwo,"has died!",charone,"wins!"

charone = raw_input("Enter the name of character one: ")
chartwo = raw_input("Enter the name of character two: ")
time.sleep(1.5)
print "\n",charone,"encounters",chartwo
delay_print("\nBattle Initiated!")

charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
while charone_strength > 100 or charone_strength < 50:
    print "That number is not between 50-100"
    charone_strength = int(raw_input("\nEnter the strength score for "+str(charone)+" (between 50 and 100): "))
else:
    pass

charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
while charone_skill > 100 or charone_skill < 50:
    print "That number is not between 50-100"
    charone_skill = int(raw_input("Enter the skill score for "+str(charone)+" (between 50 and 100): "))
else:
    pass
time.sleep(1.0)

chartwo_strength = int(raw_input("\nEnter the strength score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_strength > 100 or chartwo_strength < 50:
    print "That number is not between 50-100"
    chartwo_strength = int(raw_input("\n Enter the strength score for "+str(chartwo)+" (between 50 and 100): "))
else:
    pass

chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
while chartwo_skill > 100 or chartwo_skill < 50:
    print "That number is not between 50-100"
    chartwo_skill = int(raw_input("Enter the skill score for "+str(chartwo)+" (between 50 and 100): "))
else:
    pass

time.sleep(2)
print "\nCharacter 1:",charone
print "Strength:",charone_strength
print "Skill:",charone_skill
time.sleep(1)
print "\nCharacter 2:",chartwo
print "Strength:",chartwo_strength
print "Skill:",chartwo_skill
time.sleep(1)

while charone_strength != 0 or chartwo_strength != 0:
    ent = raw_input("Press Enter to roll! ")
    mods()
    diceroll(charone,chartwo)
    battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)
else:
    play = raw_input("\nWould you like to play again?")
    if play in ["yes","y","Yes","Y"]:
        execfile("gcse.py")
    else:
        print "Goodbye"

1 个答案:

答案 0 :(得分:2)

这段代码是编程的一个很好的例子:

  • 大量使用全局变量
  • 名称非常相似的多个变量(即charone_strengthcharone_str
  • 在不同的上下文中重用名称(在全局范围内,str_mod是一个函数,但在函数battle假设是一个整数

您的直接问题:在第182行,您致电

battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, str_mod, skl_mod)

应该是

battle(charone_strength, chartwo_strength, charone_skill, chartwo_skill, strength_mod, skill_mod)

但很困惑,因为函数strength_mod被称为str_mod


这是一个大大清理过的版本。 (欢迎提出进一步的改进建议。)

from   __future__ import division, print_function
from   random import randint
import sys
from   time import sleep

# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
    # Python 2.x
    inp = raw_input
    rng = xrange
else:
    # Python 3.x
    inp = input
    rng = range

PRINT_DELAY = 0.02
PAUSE_DELAY = 0.2
TF_VALUES   = {
    'y': True,  'yes': True,  't': True, '': True,
    'n': False, 'no':  False, 'f': False
}

def get_int(prompt="Enter an integer: ", lo=None, hi=None):
    while True:
        try:
            i = int(inp(prompt))
            if (lo is None or lo <= i) and (hi is None or i <= hi):
                return i
        except ValueError:
            pass

def get_tf(prompt="Yes or no? ", tf_values=TF_VALUES):
    while True:
        s = inp(prompt).strip().lower()
        tf = tf_values.get(s, None)
        if tf is not None:
            return tf

def pause(delay=PAUSE_DELAY):
    sleep(delay)

def roll(die_sides=6):
    return randint(1, die_sides)

def slow_print(s, delay=PRINT_DELAY):
    for ch in s:
        print(ch, end='', flush=True)
        sleep(delay)
    print('')   # end of line

def wait_for_enter(prompt):
    inp(prompt)


class Fighter:
    @classmethod
    def get_fighter(cls, prompt):
        print(prompt)
        name   = inp    ("Name: ")
        health = get_int("Health: (50-100) ", 50, 100)
        skill  = get_int("Skill:  (50-100) ", 50, 100)
        return cls(name, health, skill)

    def __init__(self, name, health, skill):
        self.name   = name
        self.health = health
        self.skill  = skill

    def is_alive(self):
        return self.health > 0

    def health_mod(self, other_fighter):
        delta = abs(self.health - other_fighter.health)
        return int(delta / 5)

    def skill_mod(self, other_fighter):
        delta = abs(self.skill - other_fighter.skill)
        return int(delta / 5)

    def attack(self, other_fighter):
        wait_for_enter("Hit Enter to fight!")
        # figure out mod values
        health_mod = self.health_mod(other_fighter)
        skill_mod  = self.skill_mod (other_fighter)
        self_roll  = roll()
        other_roll = roll()
        slow_print(
            "Health mod: {}   Skill mod: {}   {} rolls {}   {} rolls {}"
            .format(
                health_mod, skill_mod,
                self.name,  self_roll,
                other_fighter.name, other_roll
            )
        )
        # figure out who won this round
        if self_roll == other_roll:
            print("Draw! No damage done.")
        else:
            winner, loser = (self, other_fighter) if self_roll > other_roll else (other_fighter, self)
            print("{} hits {}!".format(winner.name, loser.name))
            winner.health += health_mod
            winner.skill  += skill_mod
            loser.health  -= health_mod
            loser.skill   -= skill_mod
        # show results
        print('')
        print(self)
        print(other_fighter)
        print('')

    def __str__(self):
        return "{}: health {}, skill {}".format(self.name, max(self.health, 0), max(self.skill, 0))


def fight():
    f1 = Fighter.get_fighter("\nFirst fighter:")
    pause()
    f2 = Fighter.get_fighter("\nSecond fighter:")
    pause()

    slow_print("\n{} encounters {}\nBattle Initiated!".format(f1.name, f2.name))
    while f1.is_alive() and f2.is_alive():
        f1.attack(f2)

    winner, loser = (f1, f2) if f1.is_alive() else (f2, f1)
    print("{} has died; {} wins!".format(loser.name, winner.name))

def main():
    while True:
        fight()
        if not get_tf("Would you like to play again? (Y/n)"):
            print("Goodbye!")
            break

if __name__=="__main__":
    main()