游戏陷入困境

时间:2019-08-29 11:14:18

标签: python

我正在Udemy.com上学习Python课程,我们正在通过构建RPG游戏来练习Python。到目前为止,该游戏对于单个玩家来说还算不错,但是当我们增加3个玩家时,游戏似乎在执行了全部3个玩家攻击后就陷入了僵局。

概念是大约有3位玩家,在游戏开始时会显示玩家统计数据,在所有玩家互相攻击之后(包括敌人在内),玩家统计数据如下所示在图片中,游戏再次要求所有三位玩家的输入,但是它只运行了一次,如下图所示。

我遵循了逐字逐句的代码,并且还发布了与此有关的问题。所以我认为我应该尝试StackoverFlow。 下面是我的代码,请看看为什么它不按原样循环。

主文件

# -*- coding: utf-8 -*-
from game_class.invin import Item
from game_class.game import player
from game_class.magic import Spell
import time

# Player and Enemies magic create
Fire_Shot = Spell('Fire Shot', 10, 45, "Black Magic")
Thunder_Storm = Spell("Thunder Storm",25,65,"Black Magic")
Ninja_Summon = Spell("Ninja Summon",45,75,"Ninjustu")
The_End = Spell("THE END",80,300,"Finisher")
Heal = Spell("HEAL ME",60,140,'Heal')


player_magic = [Fire_Shot,Thunder_Storm,Ninja_Summon,Heal,The_End]


enemy_magic = [
    {'Name': "Big Punch", 'cost': 30, "DMG": 45},
    {'Name': "Slap", 'cost': 15, "DMG": 25},
    {'Name': "Rock Throw", 'cost': 20, "DMG": 30},
    {'Name': "Kick", 'cost': 45, "DMG": 60}
]


boss_magic = [
    {'Name': "STORM", 'cost': 10, "DMG": 45},
    {'Name': "DARK BACK-BITTING", 'cost': 10, "DMG": 25},
    {'Name': "D.D.T", 'cost': 10, "DMG": 30}
]


# Items create
potion = Item("Potion", 'Potion', 'Heals for 50 HP', 50)
high_potion = Item("Potion+", 'Potion', 'Heals for 120 HP', 120)
super_potion = Item("Ultra Potion", 'Potion', 'Heal for 250 HP', 250)
elixir = Item("Elixir", 'Elixir', 'Give 1 EVERYTHING BACK', 9000)
high_elixir = Item("Omega Elixir", 'Elixir', 'Give all  EVERYTHING BACK', 9000)
bomb = Item("Bomb",'Attack','Deals 350 Damage',350)

player_items = [ {"item":potion,"quantity":3},
    {'item':high_potion,"quantity":2}
    ,{"item":super_potion,"quantity":1}
    ,{'item':elixir,"quantity":2}
    ,{'item':high_elixir,"quantity":1}
    ,{"item": bomb, "quantity": 2} ]


# PLAYER CREATE
Player1 = player('Night Man  ',1000, 100, 145, 140, player_magic, player_items)
Player2 = player('Ray Wills  ', 1000, 100, 155, 135, player_magic, player_items)
Player3 = player("Randy Orton",1000, 100, 150, 120, player_magic, player_items)
Enemy1 = player("Door Keeper",1500, 200, 250, 150, enemy_magic, None)
BOSS = player("Boss Man",1200, 200, 45, 300, boss_magic, None)


players = [Player1,Player2,Player3]



# Game starts

run = True
i = 1

while run is True:
    print ("=======================================")
    print("\n\n")

    print("  NAME                        HP                                 MP\n")

    for player in players:
        player.get_stats()


    for player in players:

        print("\n")
        player.chose_action()
        print("=========\n")
        print (player.name)
        print ("=============")
        choice = input("CHOSE ACTION: ")
        index = int(choice) - 1


        if index == 0:
            dmg = player.gen_dmg()
            Enemy1.get_dmg(dmg)
            print(player.name+ " attacked for " + str(dmg) + " damage points")



        elif index == 1:
            player.chose_magic()
            magic_choice = (int(input("Chose Spell: ")) - 1)

            spell = player.magic[magic_choice]
            magic_dmg = spell.gen_spell_dmg()
            current_mp = player.get_mp()
            if magic_choice == -1:
                continue


            if spell.cost > current_mp:
                print ("\nNOT ENOUGH MANA")
                continue

            if spell.stype == "Heal":
                player.heal(magic_dmg)
                print (str(magic_dmg) +' HP restored')
                print("Remaining Magic Points: " + str(player.get_mp()) +
                    "/" + str(player.get_max_mp()))


            elif spell.stype == "Black Magic" or spell.stype == "Ninjustu" or spell.stype == "Finisher":
                player.reduce_mp(spell.cost)
                Enemy1.get_dmg(magic_dmg)
                print (str(spell.name) + ' did damage of '+ str(magic_dmg) +" points")
                print ("Remaining Magic Points: " + str(player.get_mp()) +"/" +str(player.get_max_mp()))

        elif index == 2:
            player.chose_item()
            item_choice = (int(input("Chose Spell: ")) - 1)
            if item_choice == -1:
                continue

            item = player.items[item_choice]['item']
            if player.items[item_choice]['quantity'] == 0:
                print("No Item...")
                continue
            player.items[item_choice]['quantity'] -= 1


            if item.itype == 'Potion':
                player.heal(item.prop)
                print("\n"+ str(item.name) + " used and healed for "+ str(item.prop) + " HP")
            elif item.itype == "Elixir":
                player.hp = Player1.maxhp
                player.mp = Player1.maxmp
                print ("\n"+"STATS RESTORED BECASUE OF " +str(item.name))
            elif item.itype == "Attack":
                Enemy1.get_dmg(item.prop)
                print ("You used a Bomb & that dealt damage of: " + str(item.prop))

    enemy_choice = 1
    enemy_dmg = Enemy1.gen_dmg()
    Player1.get_dmg(enemy_dmg)


    print("========================================")
    print("\n")
    print ("ENEMY ATTACKED YOU FOR " + str(enemy_dmg) + " POINTS")
    print ("ENEMY HP: "+str(Enemy1.get_hp()) +'/'+ str(Enemy1.get_maxhp()))


    if Enemy1.get_hp() == 0:
        print('')
        print ('ENEMY DEAD')
        run = False
    elif Player1.get_hp() == 0:
        print('')
        print('YOU DIED')
        run = False


    elif index == 3:
        print("Arigato Gozaimasu for playing")
        time.sleep(1)
        print ("BYE BYE")
        run = False

invin.py

class Item:
    def __init__(self, name,itype,desc,prop):
        self.name = name
        self.itype = itype
        self.desc = desc
        self.prop = prop


magic.py

import random

class Spell():
    def __init__(self, name, cost,dmg,stype):
        self.name = name
        self.cost = cost
        self.dmg = dmg
        self.stype = stype


    def gen_spell_dmg(self):
        low = self.dmg - 15
        high = self.dmg + 10
        return random.randrange(low,high)


game.py

# -*- coding: utf-8 -*-
from .magic import Spell
import random



class player:
    def __init__(self,name, hp , mp , atk  ,df ,magic,items):
        self.hp = hp
        self.name = name
        self.items = items
        self.mp = mp
        self.magic = magic
        self.df = df
        self.maxhp = hp
        self.atkH = atk + 25
        self.atkL= atk - 10
        self.actions=['Attack',"Magic","Items"]
        self.maxmp = mp + 10

    def gen_dmg(self):
        return random.randrange(self.atkL,self.atkH)


    def get_dmg(self,dmg):
        self.hp -= dmg
        if self.hp < 0:
            self.hp = 0
        return self.hp


    def get_hp(self):
        return self.hp

    def get_maxhp(self):
        return self.maxhp


    def get_max_mp(self):
        return self.maxmp

    def get_mp(self):
        return self.mp


    def reduce_mp(self,cost):
        self.mp -= cost


    def spell_cost(self, i):
        return self.magic[i]["cost"]


    def chose_action(self):
        print ("Actions")
        print ("===========")
        i = 1
        for item in self.actions:
            print("  " + str(i)+":" + str(item))
            i += 1

    def chose_magic(self):
        print ("Spells")
        print ("===========")
        i = 1
        for spell in self.magic:
            print ("        " + str(i) + ": " + str(spell.name) +  str( " (Cost: " + str ( spell.cost ) +")" ) )
            #the 3rd str helps to print it without the brackets
            i += 1


    def chose_item(self):
        print ("Items")
        print ("===========")
        i = 1
        for item in self.items:
            print("        " + str(i) + ": " +
                  str(item['item'].name) + str(" (" + str(item['item'].desc) + ") ") + " (x"+str(item['quantity'])+")")
            #the 3rd str helps to print it without the brackets
            i += 1


    def heal(self,dmg):
        self.hp += dmg




    def get_stats(self):
        hp_bar = ''
        bar_ticks = ( (self.hp/self.maxhp) * 100 ) / 4

        mp_bar = ''
        mp_bar_ticks = ( (self.mp/self.maxmp) * 100 ) / 10

        while bar_ticks > 0:
            hp_bar += '█'
            bar_ticks -= 1
        while len(hp_bar) < 25:
            hp_bar = " "

        while mp_bar_ticks > 0:
            mp_bar += '▒'
            mp_bar_ticks -= 1
        while len(mp_bar) < 10:
            mp_bar = " "

        hp_string = str(self.hp) + "/"+str(self.maxhp)
        current_hp = ''
        if len(hp_string) < 9:
            decreased = 9 - len(hp_string)
            while decreased > 0:
                current_hp += ' '
                decreased -= 1
            current_hp += hp_string
        else:
            current_hp = hp_string




        mp_string = str(self.mp) +"/"+str(self.maxmp)
        current_mp = ''
        if len(mp_string) < 9:
            mp_decreased = 9 - len(mp_string)
            while mp_decreased > 0:
                current_mp += ' '
                mp_decreased -= 1
            current_mp += mp_string
        else:
            current_mp = mp_string



        print("                                _________________________           __________")
        print(str(self.name) + "          " + str(hp_string) +
              " |"+ hp_bar+"| " + str(mp_string) + " |"+mp_bar+"|")

该游戏是RPG副本,可以通过使用while循环来工作。

每位玩家都有一个回合,然后在所有3位玩家都进攻后显示其状态。

This is how the loop should show player stats after all 3 players attacked

But I'm getting this

1 个答案:

答案 0 :(得分:1)

如果我们比较“ This is how the loop should show player stats after all 3 players attacked”和“ But I'm getting this”的屏幕截图,则通过查看代码可以看到问题是由player.get_stats()的第二次运行引起的。此方法在game.py文件中定义。

在该方法内部,我们可以看到以下两行代码:

while len(hp_bar) < 25:
    hp_bar = " "

如果while循环曾经运行,它将永远被卡住。这是因为如果len(hp_bar) < 25True,则代码执行hp_bar = " ",这反过来使len(hp_bar)现在等于1。现在,这将获取while循环以再次检查len(hp_bar) < 25,并返回True(因为len(hp_bar)1),因此while循环再次运行。这样会产生无限循环。