Python中的Pokemon游戏:类/对象,战斗和Deepcopy

时间:2018-07-28 14:17:25

标签: python class object if-statement while-loop

我是python的新手,我正在尝试制作Pokemon游戏(例如gameboy和nds游戏)。我已经创建了口袋妖怪和教练课程,我想实现战斗机制。我以为它可以正常工作,但是后来我发现,如果输掉了这场战斗,程序将进入无限循环。

我做了很多尝试来发现错误,我发现当它退出“ while alive(pokemon1)和alive(pokemon2)”循环时,pokemon1 hp会恢复为完整hp,但pokemon2仍保持当前hp(I已经放了一张纸来展示它)。这对我来说没有意义,因为这两个培训人员的代码相同。有人知道为什么会这样吗?我希望它能在循环和战斗结束时继续保持两个口袋妖怪的当前生命值。

这是我的代码示例:

import copy
import random

class Pokemon(object):
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp
    def ataque(self, oponent):
        oponent.hp = oponent.hp - 150 #just for a test

class Trainer(object):
    def __init__(self, name, *pokemon):
        self.name = name
        self.pokemon, self.pokemonname = [], []
        for pkmn in pokemon:
            self.pokemon.append(copy.deepcopy(pkmn))
            self.pokemonname.append(pkmn.name)

weavile = Pokemon ('Weavile', 150) #change the hp to more than 150 if you want to win
garchomp = Pokemon ('Garchomp', 250)
roserade = Pokemon ('Roserade', 160)
ambipom = Pokemon ('Ambipom', 160) 

me = Trainer('You', weavile) #or choose ambipom to win
cynthia = Trainer('Cynthia', garchomp)

def alive(pokemon): #check if the pokemon is alive
    if pokemon.hp>0:
        return True
    if pokemon.hp<=0:
        pokemon.hp=0
        return False

def battle(trainer1, trainer2): #battle between two trainers
    fight1, fight2 = True, True
    while fight1 and fight2:
        print ('Choose a pokemon:', trainer1.pokemonname)
        pokemon1 = eval(input())
        while not alive(pokemon1):
            print (pokemon1.name, 'is out of batlle. Choose another pokemon')
            pokemon1 = eval(input())
        pokemon2 = random.choice(trainer2.pokemon)
        while not alive(pokemon2):
            pokemon2 = random.choice(trainer2.pokemon)
        print (trainer1.name, 'chose', pokemon1.name, '\n', trainer2.name, 'chose', pokemon2.name)
        while alive(pokemon1) and alive(pokemon2):
            pokemon1.ataque(pokemon2)
            if alive(pokemon2):
                pokemon2.ataque(pokemon1)
            print (pokemon1.name, pokemon1.hp)
            print (pokemon2.name, pokemon2.hp)
        print (trainer1.pokemon[0].name, trainer1.pokemon[0].hp) #here its returning the original hp
        print (trainer2.pokemon[0].name, trainer2.pokemon[0].hp) #here its returning the current hp, as it should
        if not any(alive(pokemon) for pokemon in trainer1.pokemon):
            fight1 = False
        if not any(alive(pokemon) for pokemon in trainer2.pokemon):
            fight2 = False

battle(me, cynthia)

如果按照我在此处编写的方式运行代码,则需要在列表中选择一个口袋妖怪(只有一个:weavile-为简化起见),所以只需键入weavile。在那之后,weavile将攻击,然后被garchomp攻击。 Weavile将在第一次命中时被击败(0 hp),但是在循环“ while alive(pokemon1)...”之后,它将表明weavile仍然具有150 hp,即使它已经存在,它仍会继续要求您选择一个神奇宝贝死了。

如果您想获胜:在“我”对象中选择“ ambipom”而不是“ weavile”,或在“ weavile”对象中将“ wehple hp”更改为150以上。如果这样做,它将按我的意愿运行并结束战斗。

0 个答案:

没有答案