1

这是我第一次尝试 Python 编码,或者任何与此相关的编码。我制作了这个简单的小游戏,它似乎运行良好,但我想为它添加另一个选项。

代码生成一个随机角色,HP,攻击力,XP和等级,然后生成一条HP和攻击力的龙,游戏然后决定每次攻击谁,如果玩家获胜,他可以获得一些Xp并升级,如果龙赢了玩家就死了,它会要求你再玩一次。

我想补充的是,如果我在战斗中,不想继续,我想问用户他们是否想继续战斗,如果不是,游戏结束。

我试过这样做,但我失败了。另外,如果有什么我可以做的来增强我的代码。

提前致谢。

import random

def charGen():
    char = [random.randint(1,10),random.randint(1,3), 0, 0]#[hp, power,xp,level]
    return char
def drgnGen():
    drgn = [random.randint(1,5),random.randint(1,5)]
    return drgn
def playAgain():
    print('do you want to play again?(y)es or no')
    return input().lower().startswith('y')


def xpValues(levels):
    for i in range(levels):
        n=0
        n=((i+2)**2)
        xpLevels.append(n)


def xpIncrement(XP,xpLevels,char):
    #returns the level of the character( the bracket in which the character XP level lies within) 
    #level = char[3]
    for i in range(len(xpLevels)):
        if XP>= xpLevels[i] and XP<xpLevels[i+1]:
            #level = i+1
            return i

def levelUp(char,level):
     if level+1>char[3]:
         char[0] += 1
         char[3] += 1
         print ('you are now at level %s!, your health now is %s points'%((level+1),char[0]))




def isNotDead(char):
    if char[0]>0:
        return True
    else:
        return False

while True:
    XP = 5 #the default XP gain after battle win
    char = charGen() #generate the character

    xpLevels=[]
    xpValues(15)
    print (xpLevels)
    print ('______________________________________')
    print ('Welcome to the Battle of the dragons!')
    print ("you are a fierce Warrior with %s health points and A power of %s points" %(char[0],char[1]))
    print ('------------------------------------------------------------------------')
    while isNotDead(char):
        print(' ')
        print ('While adventuring you have met a scary looking dragon')
        print('Without hesitation you jump to fight it off!')
        print('=============================================')
        print(' ')
        drgn = drgnGen() #generate a dragon
        while True:


            roll = random.randint(0,1)
            if roll == 0:
               print("the dragon hits you for %s points" %drgn[1])
               char[0] = char[0] - drgn[1]
               if isNotDead(char) :
                   print("you have %s health left!" %char[0])
                   input('Press Enter to continue')
                   print(' ')
               else:
                    print("you're dead!Game Over")
                    print(' ')
                    break


            else:
                print("you hit the dragon for %s points"%char[1])
                drgn[0] = drgn[0] - char[1]

                if drgn[0] >0:
                    print("the dragon have %s health left!" %drgn[0])
                    input('Press Enter to continue')
                    print(' ')
                else:
                    char[2]+= XP
                    print("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
                    levelUp(char,(xpIncrement(char[2],xpLevels,char)))                    
                    input('Press Enter to continue')
                    break


    if not playAgain():
        break
4

1 回答 1

0

获得所需内容的快速解决方法是设置几个标志来标记用户是否在战斗。您也可以将打印输出延迟到最内层循环结束,以避免重复太多print

new_dragon = True
while new_dragon:
    print(' ')
    print ('While adventuring you have met a scary looking dragon')
    print('Without hesitation you jump to fight it off!')
    print('=============================================')
    print(' ')
    drgn = drgnGen() #generate a dragon
    fighting = True
    while fighting:
        message = []
        roll = random.randint(0,1)
        if roll == 0:
           message.append("the dragon hits you for %s points" %drgn[1])
           char[0] = char[0] - drgn[1]
           if isNotDead(char) :
               message.append("you have %s health left!" %char[0])
           else:
               message.append("you're dead!Game Over")
               fighting = False
               new_dragon = False
        else:
            message.append("you hit the dragon for %s points"%char[1])
            drgn[0] = drgn[0] - char[1]

            if drgn[0] >0:
                message.append("the dragon have %s health left!" %drgn[0])
            else:
                char[2]+= XP
                message.append("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
                levelUp(char,(xpIncrement(char[2],xpLevels,char)))                    
                continue_flag = False
        for m in message:
            print (m)
        print ('')
        if fighting:
            r = input("Press enter to continue or enter q to quit")
            if r is 'q':
                fighting = False

为了更普遍地改进代码:

  • 为 Player 和 Dragon 创建一个 Character 类以及继承 Character 类的共享属性的类
  • 只需比较是否 new_xp > xpLevels[previous_xp] 就可以大大简化是否升级的检查
  • 如果只使用嵌套的 while 循环继续扩展程序,程序很快就会变得过于复杂。您需要的是单个while 循环、游戏的每个阶段/状态的函数(或类)、记录游戏当前状态的变量(例如存在的任何龙)以及决定下一步做什么的条件。
  • 使用类给事物提供清晰的描述性名称,例如 player.power 而不是 char[2]

比如下面...

import random

class Character:
    def __init__(self, max_hp, max_power):
        self.hp = random.randint(1, max_hp)
        self.power = random.randint(1, max_power)
    def is_dead(self):
        return self.hp <= 0
    def hit_by(self, enemy):
        self.hp -= enemy.power

class Player(Character):
    def __init__(self):
        Character.__init__(self, max_hp=10, max_power=3)
        self.xp = 0
        self.level = 0
        self.xp_thresholds = [(i + 2) ** 2 for i in range(15)]
    def battle_win(self):
        self.xp += battle_win_xp
        if self.level < len(self.xp_thresholds) and self.xp > self.xp_thresholds[self.level + 1]:
            self.level_up()
    def level_up(self):
        self.hp += 1
        self.level += 1
        print('you are now at level %s!, your health now is %s points' % (self.level + 1, self.hp))

def begin():
    game.player = Player()
    print('______________________________________')
    print('Welcome to the Battle of the dragons!')
    print("you are a fierce Warrior with %s health points and A power of %s points" %(game.player.hp, game.player.power))
    print('------------------------------------------------------------------------')
def new_dragon():
    print('While adventuring you have met a scary looking dragon')
    print('Without hesitation you jump to fight it off!')
    print('=============================================')
    game.dragon = Character(5, 5)
def fight():
    player, dragon = game.player, game.dragon
    if random.randint(0, 1):
        player.hit_by(dragon)
        print("the dragon hits you for %s points" % dragon.power)
        if player.is_dead():
            print("you're dead! Game over")
            return
        else:
            print("you have %s health left!" % player.hp)
    else:
        dragon.hit_by(player)
        print("you hit the dragon for %s points" % player.power)
        if dragon.is_dead():
            print("Horaay!you have killed the dragon!and your experience points are now %s"%player.xp)
            player.battle_win()
            game.dragon = None
            return
        else:
            print ("the dragon have %s health left!" %dragon.hp)
    print "Press enter to continue (q to quit)"
    if input() is 'q':
        game.finished = True
def play_again():
    print 'do you want to play again?(y)es or no'
    if input().lower().startswith('y'):
        game.__init__()
    else:
        game.finished = True
battle_win_xp = 5 #the default XP gain after battle win
class Game:
    def __init__(self):
        self.dragon = None
        self.player = None
        self.finished = False
game = Game()
while not game.finished:
    if not game.player:
        begin()
    elif game.player.is_dead():
        play_again()
    elif not game.dragon:
        new_dragon()
    else:
        fight()
于 2013-01-16T05:13:22.440 回答