找斯图的游戏

2024-06-06 20:55:19 发布

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

我在上Python课程Udemy.com网站我们正在通过构建一个RPG游戏来练习Python。到目前为止,这个游戏对于一个玩家来说还不错,但是当我们增加了3个玩家的时候,游戏似乎在执行了所有3个玩家的攻击之后就卡住了。你知道吗

游戏的概念是大约有3名玩家,游戏开始时会显示玩家数据,在所有玩家都互相攻击之后,这也包括敌人,玩家数据会打印出来,如下图所示,游戏会再次要求所有三名玩家输入,但它只运行一次,如下图所示。

我逐字逐句地遵循代码,还发布了一个关于它的问题。所以我想我应该试试StackoverFlow。 下面是我的代码,请看看为什么它不在循环中,因为它应该。你知道吗

main文件

# -*- 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

英文比

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


魔术.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)


游戏.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


Tags: nameselfgetdefmagicbarmpitem
1条回答
网友
1楼 · 发布于 2024-06-06 20:55:19

如果我们比较“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循环再次运行。这就形成了一个无休止的循环。你知道吗

相关问题 更多 >