循环不正确,然后崩溃

2024-05-16 02:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,我正在为一个学校项目工作,基本思想是两个角色之间有一场战斗,用户可以为每个角色输入两个属性:力量和技能。现在也有技能和力量的修饰符,这是球员的技能和力量属性的差异,除以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"

Tags: themodrawtimetopcalcsleepstrength
1条回答
网友
1楼 · 发布于 2024-05-16 02:12:38

这段代码是如何而不是编程的一个很好的例子:

  • 大量使用全局变量
  • 名称非常相似的多个变量(即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()

相关问题 更多 >