首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本冒险作战原型

文本冒险作战原型
EN

Code Review用户
提问于 2021-12-11 12:36:31
回答 1查看 118关注 0票数 5

我对Python和编程非常陌生,因为我上了一所编程学校,我从书中学到了很多东西,这并不适合我,而且我落后于每个人。目前我正试图改变这种状况,并表明我有能力用我的Python“知识”来做一些事情,目前我正在做一个基本的文字游戏,你可以选择哪种武器来对抗狼,谁的健康来自字典,你可以选择的武器的统计数据也是如此。现在我要做的是设置它,这样我就不需要对整个损坏的想法重复相同的代码了,我想把它写在一个函数中,这样我就可以为每种武器类型调用函数,节省空间,减少代码。如果有人能告诉我如何做到这一点,和/或对我的代码的任何建议,以及如何在不使用大量面向对象编程的情况下使代码更短,这将意味着世界。

感谢任何人帮助或只是阅读这篇文章,并抽出时间在他们一天。

代码语言:javascript
复制
import time
import random

weapons = {
    "melee": {

        "katana": {

            "speed": 6,
            "strength": 50,
            "range": 5,
            "critical_chance": 50,
            "critical_multiplier": 2,
            "damage": 100

        },

        "dull_sword": {

            "speed": 3,
            "strength": 15,
            "range": 4,
            "critical_chance": 10,
            "critical_multiplier": 1.2,
            "damage": 30

        },

        "sharp_sword": {

            "speed": 3,
            "strength": 25,
            "range": 4,
            "critical_chance": 25,
            "critical_multiplier": 1.5,
            "damage": 45

        },
        "broken_machete": {

            "speed": 4,
            "strength": 20,
            "range": 3,
            "critical_chance": 15,
            "critical_multiplier": 1.3,
            "damage": 30

        },

        "repaired_machete": {

            "speed": 5,
            "strength": 30,
            "range": 3,
            "critical_chance": 20,
            "critical_multiplier": 1.4,
            "damage": 60

        },

        "mace": {

            "speed": 2.1,
            "strength": 60,
            "range": 4,
            "critical_chance": 10,
            "critical_multiplier": 1.1,
            "damage": 40

        }

    },

    "long_range": {

        "longbow": {

            "speed": 3,
            "strength": 55,
            "range": 100,
            "critical_chance": 100,
            "critical_multiplier": 1.5,
            "damage": 120

        },

        "slingshot": {

            "speed": 5,
            "strength": 10,
            "range": 50,
            "critical_chance": 25,
            "critical_multiplier": 1.1,
            "damage": 20

        },

        "short_bow": {

            "speed": 4,
            "strength": 15,
            "range": 60,
            "critical_chance": 20,
            "critical_multiplier": 1.2,
            "damage": 40
        },

        "broken_longbow": {

            "speed": 2,
            "strength": 30,
            "range": 70,
            "critical_chance": 50,
            "critical_multiplier": 1.3,
            "damage": 60

        }


    },

    "throwable": {

        "small_rock": {

            "speed": 7,
            "strength": 7,
            "range": 20,
            "critical_chance": 10,
            "critical_multiplier": 1,
            "damage": 10

        },

        "dynamite": {

            "speed": 2.1,
            "strength": 100,
            "range": 20,
            "critical_chance": 20,
            "critical_multiplier": 1.7,
            "damage": 120
        },

        "makeshift_explosive": {

            "speed": 2.3,
            "strength": 60,
            "range": 15,
            "critical_chance": 15,
            "critical_multiplier": 1.5,
            "damage": 95

        }

    }


}

enemies_animals = {

    "dead": {

        "zombie": {

            "health": 150,
            "speed": 6,
            "damage": 20,
            "attack_speed": 4,
            "range": 3

        },

        "zombie_wolf": {

            "health": 250,
            "speed": 8,
            "damage": 25,
            "attack_speed": 4,
            "range": 3

        },

        "zombie_bear": {

            "health": 350,
            "speed": 4,
            "damage": 35,
            "attack_speed": 4,
            "range": 4

        }

    },

    "animals": {

        "chicken": {

            "health": 20,
            "speed": 6

        },

        "wolf": {

            "health": 100,
            "speed": 12,
            "damage": 20,
            "attack_speed": 3,
            "range": 3

        },

        "bear": {

            "health": 200,
            "speed": 6,
            "damage": 25,
            "attack_speed":  3,
            "range": 4

        },

        "cow": {

            "health": 50,
            "speed": 6

        },

        "large_bat": {

            "health": 100,
            "speed": 14,
            "damage": 15,
            "attack_speed": 5,
            "range": 2

        }

    },

    "regular_enemies": {

        "bandit": {

            "health": 100,
            "speed": 10,
            "damage": 10,
            "attack_speed": 5,
            "range": 3

        },

        "hoarder": {

            "health": 120,
            "speed": 10,
            "damage": 20,
            "attack_speed": 4,
            "range": 3

        },

        "mage": {

            "health": 90,
            "speed": 10,
            "damage": 25,
            "attack_speed": 3.3,
            "range": 15

        },

        "marksman": {

            "health": 75,
            "speed": 12,
            "damage": 50,
            "attack_speed": 2.2,
            "range": 50

        },

        "heavy_bandit": {

            "health": 150,
            "speed": 7,
            "damage": 15,
            "attack_speed": 3.4,
            "range": 4

        },

        "heavy_hoarder": {

            "health": 170,
            "speed": 7,
            "damage": 20,
            "attack_speed": 3.7,
            "range": 4

        }

    }

}

wolf = enemies_animals["animals"]["wolf"]["health"]


user = input("Write down your username: ")
time.sleep(0.5)

userInput = input("Welcome, for this test please choose either to attack, or to run: ")
time.sleep(0.5)

if userInput.lower() == "attack":

    time.sleep(0.5)
    weapon_type = input("Choose which type of weapon to use (melee/long_range/throwable): ")

    if weapon_type.lower() == "melee":

        time.sleep(0.5)
        weapon_list = []
        for key in weapons[weapon_type]:
            weapon_list.append(key)
        print(f'Choose from weapons: {weapon_list}')

        time.sleep(0.5)
        weapon = input("choose which weapon to use(seen from the list above): ")
        critical_chance = weapons[weapon_type][weapon]["critical_chance"]

        if random.randint(1, 100) == weapons[weapon_type][weapon]["critical_chance"]:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon]["strength"]) / 2) * 3 * weapons[weapon_type][weapon]["critical_multiplier"]
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")
                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

        else:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon]["strength"]) / 2) * 3
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")

                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

    elif weapon_type == "long_range":

        time.sleep(0.5)
        weapon_list = []
        for key in weapons[weapon_type]:
            weapon_list.append(key)
        print(f'Choose from weapons: {weapon_list}')

        time.sleep(0.5)
        weapon = input("choose which weapon to use(seen from the list above): ")
        critical_chance = weapons[weapon_type][weapon]["critical_chance"]

        if random.randint(1, 100) == weapons[weapon_type][weapon]["critical_chance"]:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon][
                "strength"]) / 2) * 3 * weapons[weapon_type][weapon]["critical_multiplier"]
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")
                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

        else:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon]["strength"]) / 2) * 3
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")
                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

    elif weapon_type == "throwable":

        time.sleep(0.5)
        weapon_list = []
        for key in weapons[weapon_type]:
            weapon_list.append(key)
        print(f'Choose from weapons: {weapon_list}')

        time.sleep(0.5)
        weapon = input("choose which weapon to use(seen from the list above): ")
        critical_chance = weapons[weapon_type][weapon]["critical_chance"]

        if random.randint(1, 100) == weapons[weapon_type][weapon]["critical_chance"]:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon][
                "strength"]) / 2) * 3 * weapons[weapon_type][weapon]["critical_multiplier"]
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")

                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

        else:

            total_damage = ((weapons[weapon_type][weapon]["damage"] + weapons[weapon_type][weapon]["strength"]) / 2) * 3
            attack = wolf - total_damage

            if attack <= 0:

                dead_wolf = wolf

                if random.randint(1, 5) == 5:

                    time.sleep(0.5)
                    print(f"{user} killed a wolf with a critical hit and got it's meat! ")

                else:

                    time.sleep(0.5)
                    print(f"{user} killed the wolf with a critical hit!")
            else:

                time.sleep(0.5)
                print(f"The wolf has {attack} health! ")

else:

    time.sleep(0.5)
    print(f"{user}, choose to run away!")
EN

回答 1

Code Review用户

发布于 2021-12-12 00:37:56

从书上学到很多东西不适合我

我明白;我也是这样。做这样的项目真的会对你有帮助。保持这种状态--这是学习如何编程的一个非常重要的习惯。

关于你的代码的好东西-你的武器和敌人的数据库结构不是完全疯狂;你的程序工作!这不算什么,特别是对于初学者来说。

我将把这些建议保留在初级到中级水平。

如果您删除数据库并将其放入一个单独的文件中,您的代码将更加简洁。JSON是最简单的格式,它几乎是当前字典文字中的剪贴。您目前包括一个层次结构,其中有针对每种武器和敌人类型的子词典。这是一种索引形式,但有很多种形式的索引,我将建议,就您的目的而言,如果没有这个层次结构,可能更容易获得一个更平坦的数据库格式,并为每个武器和敌人包括一个type字段。可以在运行时按类型进行索引。

您可以将名称enemies_animals简化为enemies

您的武器和敌人的名字可以使用正常的空格而不是下划线,空间将更好地为您的用户界面。

与其将敌人对象分配给wolf变量,不如将其赋值给一个名为enemy的变量。变量和使用它的代码不应该关心它是狼--您应该进行概括。

删除你的sleeps -他们没有帮助任何人。

不要将武器类型名称硬编码到提示字符串中。相反,从数据库中的武器类型动态地形成此字符串。

attack是个用词不当的词,应该称为health

您对randint的使用更好--用randrange表示。

你的关键机会检查不正确。您应该检查小于<的值,而不是相等。否则,你的有效关键命中率将永远是1%。

处理变量重用和识别代码的公共部分。金科玉律是干的-不要重复你自己。

对于逃逸检查,首先做一件简单的事情--return

建议

game-database.json

代码语言:javascript
复制
{
  "weapons": {
    "katana": {
      "type": "melee",
      "speed": 6,
      "strength": 50,
      "range": 5,
      "critical_chance": 50,
      "critical_multiplier": 2,
      "damage": 100
    },
    "dull sword": {
      "type": "melee",
      "speed": 3,
      "strength": 15,
      "range": 4,
      "critical_chance": 10,
      "critical_multiplier": 1.2,
      "damage": 30
    },
    "sharp sword": {
      "type": "melee",
      "speed": 3,
      "strength": 25,
      "range": 4,
      "critical_chance": 25,
      "critical_multiplier": 1.5,
      "damage": 45
    },
    "broken machete": {
      "type": "melee",
      "speed": 4,
      "strength": 20,
      "range": 3,
      "critical_chance": 15,
      "critical_multiplier": 1.3,
      "damage": 30
    },
    "repaired machete": {
      "type": "melee",
      "speed": 5,
      "strength": 30,
      "range": 3,
      "critical_chance": 20,
      "critical_multiplier": 1.4,
      "damage": 60
    },
    "mace": {
      "type": "melee",
      "speed": 2.1,
      "strength": 60,
      "range": 4,
      "critical_chance": 10,
      "critical_multiplier": 1.1,
      "damage": 40
    },
    "longbow": {
      "type": "long range",
      "speed": 3,
      "strength": 55,
      "range": 100,
      "critical_chance": 100,
      "critical_multiplier": 1.5,
      "damage": 120
    },
    "slingshot": {
      "type": "long range",
      "speed": 5,
      "strength": 10,
      "range": 50,
      "critical_chance": 25,
      "critical_multiplier": 1.1,
      "damage": 20
    },
    "short bow": {
      "type": "long range",
      "speed": 4,
      "strength": 15,
      "range": 60,
      "critical_chance": 20,
      "critical_multiplier": 1.2,
      "damage": 40
    },
    "broken longbow": {
      "type": "long range",
      "speed": 2,
      "strength": 30,
      "range": 70,
      "critical_chance": 50,
      "critical_multiplier": 1.3,
      "damage": 60
    },
    "small rock": {
      "type": "throwable",
      "speed": 7,
      "strength": 7,
      "range": 20,
      "critical_chance": 10,
      "critical_multiplier": 1,
      "damage": 10
    },
    "dynamite": {
      "type": "throwable",
      "speed": 2.1,
      "strength": 100,
      "range": 20,
      "critical_chance": 20,
      "critical_multiplier": 1.7,
      "damage": 120
    },
    "makeshift explosive": {
      "type": "throwable",
      "speed": 2.3,
      "strength": 60,
      "range": 15,
      "critical_chance": 15,
      "critical_multiplier": 1.5,
      "damage": 95
    }
  },
  "enemies": {
    "zombie": {
      "type": "dead",
      "health": 150,
      "speed": 6,
      "damage": 20,
      "attack_speed": 4,
      "range": 3
    },
    "zombie wolf": {
      "type": "dead",
      "health": 250,
      "speed": 8,
      "damage": 25,
      "attack_speed": 4,
      "range": 3
    },
    "zombie bear": {
      "type": "dead",
      "health": 350,
      "speed": 4,
      "damage": 35,
      "attack_speed": 4,
      "range": 4
    },
    "chicken": {
      "type": "animal",
      "health": 20,
      "speed": 6
    },
    "wolf": {
      "type": "animal",
      "health": 100,
      "speed": 12,
      "damage": 20,
      "attack_speed": 3,
      "range": 3
    },
    "bear": {
      "type": "animal",
      "health": 200,
      "speed": 6,
      "damage": 25,
      "attack_speed": 3,
      "range": 4
    },
    "cow": {
      "type": "animal",
      "health": 50,
      "speed": 6
    },
    "large bat": {
      "type": "animal",
      "health": 100,
      "speed": 14,
      "damage": 15,
      "attack_speed": 5,
      "range": 2
    },
    "bandit": {
      "type": "regular",
      "health": 100,
      "speed": 10,
      "damage": 10,
      "attack_speed": 5,
      "range": 3
    },
    "hoarder": {
      "type": "regular",
      "health": 120,
      "speed": 10,
      "damage": 20,
      "attack_speed": 4,
      "range": 3
    },
    "mage": {
      "type": "regular",
      "health": 90,
      "speed": 10,
      "damage": 25,
      "attack_speed": 3.3,
      "range": 15
    },
    "marksman": {
      "type": "regular",
      "health": 75,
      "speed": 12,
      "damage": 50,
      "attack_speed": 2.2,
      "range": 50
    },
    "heavy bandit": {
      "type": "regular",
      "health": 150,
      "speed": 7,
      "damage": 15,
      "attack_speed": 3.4,
      "range": 4
    },
    "heavy hoarder": {
      "type": "regular",
      "health": 170,
      "speed": 7,
      "damage": 20,
      "attack_speed": 3.7,
      "range": 4
    }
  }
}

Python代码

代码语言:javascript
复制
import json
import random
from collections import defaultdict


def load_database():
    with open('game-database.json') as f:
        data = json.load(f)

    return data['weapons'], data['enemies']


def index_weapons(weapons):
    indexed = defaultdict(list)
    for weapon_name, weapon in weapons.items():
        weapon['name'] = weapon_name
        indexed[weapon['type']].append(weapon)
    return indexed


def choose_weapon(weapons):
    weapons_by_type = index_weapons(weapons)
    types = '/'.join(weapons_by_type.keys())
    weapon_type = input(f'Choose which type of weapon to use ({types}): ')

    names = '/'.join(
        weapon['name']
        for weapon in weapons_by_type[weapon_type]
    )
    weapon_name = input(f'Choose from weapons ({names}): ')
    return weapons[weapon_name]


def use_weapon(weapon):
    damage = (weapon['damage'] + weapon['strength']) * 3 / 2
    critical = random.randrange(100) < weapon['critical_chance']
    harvest = False
    if critical:
        damage *= weapon['critical_multiplier']
        harvest = random.randrange(5) == 0

    return damage, critical, harvest


def attack_enemy(enemy, damage):
    health = enemy['health'] - damage
    alive = health > 0
    return health, alive


def run_game():
    weapons, enemies = load_database()

    user_name = input('Write down your username: ')

    choice = input('Welcome. For this test please choose either to attack, or to run: ')
    if choice.lower() != 'attack':
        print(f'{user_name} chose to run away!')
        return

    weapon = choose_weapon(weapons)

    damage, critical, harvest = use_weapon(weapon)
    harvest_suffix = ' and got its meat' if harvest else ''
    victory_suffix = ' with a critical hit' if critical else ''

    enemy_name = 'wolf'
    enemy = enemies[enemy_name]
    health, alive = attack_enemy(enemy, damage)
    if alive:
        print(f'The {enemy_name} has {health} health!')
    else:
        print(f'{user_name} killed the {enemy_name}{victory_suffix}{harvest_suffix}!')


if __name__ == '__main__':
    run_game()
票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/270902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档