首页 > 解决方案 > 能够选择一个数字并显示该数字的值

问题描述

我正在创建一个基于回合的游戏,我希望能够让 user1 选择一个数字,并且无论该数字对应什么都应该打印出它是什么,然后 user2 应该能够再次这样做并在选择 2 张牌时中断

import random

class Pokemon():
    def __init__(self,name,stage,atk_type,hp):
        self.name = name
        self.stage = stage
        self.atk_type = atk_type
        self.hp = hp

    def __str__(self):
                return(f"name: {self.name}\nstage: {self.stage}\natk_type: {self.atk_type}\nhp: {self.hp}\n")


def menu():

    print("Pick Your Pokemon:\n 1. Squirtle\n 2. Charizard\n 3. Exit")
    choice = input("Pick Your Pokemon! : ")
    
    Charizard = Pokemon("Charizard", "Stage 2 ", ["atk_type - Fire", "Attacks - Flamethrower, Ember, Fire Blast , Damage 12"], 120)
    print(Charizard)
    Squirtle = Pokemon("Squirtle", "Basic", ["atk_type - Water", "Attacks - Bubble, Tackle, Water Pulse, AQUA Jet, Damage 3"], 60)
    print(Squirtle)
    Charmander = Pokemon("Charmander","Basic", ["atk_type - Fire ", "Attacks - Ember, Scratch, Fire Punch, Tackle, Damage 4"], 60)
    print(Charmender)

if __name__ == "__main__":
    menu()

我尝试了很多解决方案,但它一直在循环,有人可以用简单的代码提供帮助。谢谢你!

标签: python

解决方案


我认为这就是你的意思:

import random

class Pokemon():
    def __init__(self,name,stage,atk_type,hp):
        self.name = name
        self.stage = stage
        self.atk_type = atk_type
        self.hp = hp

    def __str__(self):
                return(f"name: {self.name}\nstage: {self.stage}\natk_type: {self.atk_type}\nhp: {self.hp}\n")


def menu():
    count = 0
    while(count<2):
        print("Pick Your Pokemon:\n 1. Squirtle\n 2. Charizard\n 3. Exit")
        choice = input("Pick Your Pokemon! : ")
        
        Charizard = Pokemon("Charizard", "Stage 2 ", ["atk_type - Fire", "Attacks - Flamethrower, Ember, Fire Blast , Damage 12"], 120)
        
        Squirtle = Pokemon("Squirtle", "Basic", ["atk_type - Water", "Attacks - Bubble, Tackle, Water Pulse, AQUA Jet, Damage 3"], 60)
        
        if(choice=="1"):
            print(Squirtle)
            count += 1
        elif(choice=="2"):
            print(Charizard)
            count += 1
        elif(choice=="3"):
            break
        else:
            continue
    

if __name__ == "__main__":
    menu()

请告诉我这是否是您需要的。

基本上,您需要使用“选择”变量检查用户输入的内容,并根据变量等于什么,打印正确的对象。

每次选择后将 count 变量增加 1,以便循环在 2 次选择后停止。


计数变量的解释:

第一步是说 count 等于 0: count = 0 然后,将主循环放在一个 while 循环中,条件是只有在 count 小于 count 时循环才会开始: while(count<2): 所以它开始一次,因为 count 等于 0。

然后,每当用户做出有效选择时,您就说计数应该增加。(意味着它应该给自己加一个)像这样:count += 1

因此,当做出两个选择时,选择变量等于 2 并且循环停止。


推荐阅读