首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python CS GO案例模拟器

Python CS GO案例模拟器
EN

Code Review用户
提问于 2017-07-30 22:30:37
回答 1查看 2.1K关注 0票数 7

我是Python的初学者,有1-2个月的经验。请评估我的密码。我用字典来储存箱子。cases_data存储在另一个文件中。结构正确吗?我的代码似乎有很多空格,我如何重构它以提高可读性呢?代码按预期成功运行,但代码是否适合于可维护性(添加新特性)?我是否遵循Python标准?这是否符合工业标准?我做这个项目是为了休闲。

代码语言:javascript
复制
cases = {
"wildfire" : {
    "blue" : ['Tec-9 | Jambiya', 'USP-S | Lead Conduit', 'SSG 08 | Necropos', 'Dual Berettas | Cartel', 'MAC-10 | Lapis Gator', 'PP-Bizon | Photic Zone'],
    "purple" : ['MAG-7 | Praetorian', 'FAMAS | Valence', 'Five-SeveN | Triumvirate', 'Glock-18 | Royal Legion'],
    "pink" : ['Desert Eagle | Kumicho Dragon', 'Nova | Hyper Beast', 'AWP | Elite Build'],
    "red" : ['AK-47 | Fuel Injector', 'M4A4 | The Battlestar'],
    },
"chroma 2" : {
    'blue' : ['AK-47 | Elite Build', 'MP7 | Armor Core', 'Desert Eagle | Bronze Deco', 'P250 | Valence', 'Sawed-Off | Origami'],
    'purple' : ['AWP | Worm God', 'MAG-7 | Heat', 'CZ75-Auto | Pole Position', 'UMP-45 | Grand Prix'],
    'pink' : ['Five-SeveN | Monkey Business', 'Galil AR | Eco', 'FAMAS | Dijinn'],
    'red' : ['M4A1-S | Hyper Beast', 'MAC-10 | Neon Rider'],
    },
}


import random
from cases_data import *

stattrrak=['StatTrrak',]
knives=['Karambit', 'Flip knife', 'M9 Bayonet', 'Bayonet', 'Flachion', 'Shaddow Daggers', 'Bowie Knife']
wear = ['battle scarred', 'well worn', 'field tested', 'minimal wear', 'factory new']


print ("Hello! Welcome to CS GO case lottery!")
print ("Available cases: Wildfire and Chroma 2")
print ("Winning a purple skin gives you 1 additional key!")
print ("Winning a pink skin gives you 3 additional keys!")
print ("Winning a red skin gives you 7 additional keys!")
print ("Winning a knife gives you 15 additional keys!")

global caseKeys
caseKeys = 1
def skin_wear():
    x = random.choice(wear)
    return x
def case_run():
    global caseKeys
    chance1 = random.randint(1, 100)
    while caseKeys >0:
        resp = input("Which case would you like to open? ")
        for i in cases:
            if resp.lower() == i:
                caseKeys -= 1
                colours = list(cases[i].items())

                #print ("Colours: %s" % colours)
                chance = random.randint(1, 100)
                for x, y in enumerate([25, 10, 5, 2]):
                    if chance >=y:
                        trakChance= random.randint(1, 100)
                        skinRarity = colours[x][0]
                        skin = random.choice(colours[x][1])
                        if trakChance <= 35:
                            print ("You've won a %s (%s) (%s skin) (StatTrrak)" % (skin, skin_wear(), skinRarity))
                            print ("With a chance of %s" % chance)

                        else:
                            print ("You've won a %s (%s) (%s skin)" % (skin, skin_wear(), skinRarity))
                            print ("With a chance of %s" % chance)
                        if skinRarity == 'purple':
                            caseKeys += 1
                        elif skinRarity == 'pink':
                            caseKeys += 3
                        elif skinRarity == 'red':
                            caseKeys += 7
                        print ("Keys left: %s" % caseKeys)
                        break                   
                    elif chance == 1:
                        print ("You've won a %s, Congratulations!" % random.choice(knives))
                        print ("With a chance of %s" % chance)
                        print ("Nice! 15 more keys!")
                        caseKeys += 15
                        print ("Keys left: %s" % caseKeys)
                        break
                break

        if resp.lower() != i:
            print ("Please see list for cases")
    else:
        print ("You've run out of keys")




    if caseKeys == 0:
        resp2=input("Would you like to try again? ")
        if resp2.lower() == 'yes' or 'y':
            resp3=int(input("How many keys? "))
            caseKeys = resp3
            case_run()
        else:
            sys.exit()

case_run()
EN

回答 1

Code Review用户

回答已采纳

发布于 2017-07-31 09:43:18

欢迎来到Python,这是空格的语言。仅次于空格本身。更重要的是,您的代码是可以的,不过,我建议您对其进行大量更改,以使其更好。

  • Python有一个名为PEP8的样式指南,我建议您遵循这个样式指南,以便其他Python用户能够更容易地阅读和理解您的代码。
  • 不要使用global,通常有一种方法可以绕过使用它。在这个例子中,实际上不需要它。使用global是一种不好的习惯,而且是非常不鼓励的。
  • 不需要sys.exit。如果您只是从函数中returned,您的代码将以相同的方式工作。
  • 把你的职能分开。open_case应该是您的函数之一,而main应该是另一个函数。
  • 使用__main__。这会防止代码运行,如果您import它。
  • 由于您在项目的其他属性上使用random.choice,所以对于skin_wear来说,单独使用它是没有意义的。
  • if trakChance <= 35:周围的if会使您的代码变湿。相反,您可以使用F-弦。f"{‘(StatTrack)’如果track_chance <= 35‘}“
  • 打破breaks到处!我会在需要的时候推荐你使用控制流语句,而不是当他们没有的时候。使用不当会导致混淆,并可能导致意大利面码
  • 您有一个bug,resp2.lower() == 'yes' or 'y'总是True。这是因为它检查orresp2.lower() == 'yes'的左手边。如果这是真的,则跳过检查右手边,否则检查右手边。因此,如果resp2n,那么语句的结果是y。这是真的。相反,使用in并构建一个元组或集合。例如:如果在(‘是’,‘y’)中出现了更低的():
  • 您的代码需要字典的实现细节正确工作:这个新实现的保持顺序的方面被认为是实现细节,不应该依赖于使用OrderedDict
  • 您可能希望将全局常量存储在Python之外的文件中。其中一种方法是在JSON中。

使用以上大多数内容,我将您的代码更改为:

代码语言:javascript
复制
import random

CASES = {
    "wildfire" : {
        "blue" : ['Tec-9 | Jambiya', 'USP-S | Lead Conduit', 'SSG 08 | Necropos', 'Dual Berettas | Cartel', 'MAC-10 | Lapis Gator', 'PP-Bizon | Photic Zone'],
        "purple" : ['MAG-7 | Praetorian', 'FAMAS | Valence', 'Five-SeveN | Triumvirate', 'Glock-18 | Royal Legion'],
        "pink" : ['Desert Eagle | Kumicho Dragon', 'Nova | Hyper Beast', 'AWP | Elite Build'],
        "red" : ['AK-47 | Fuel Injector', 'M4A4 | The Battlestar'],
        },
    "chroma 2" : {
        'blue' : ['AK-47 | Elite Build', 'MP7 | Armor Core', 'Desert Eagle | Bronze Deco', 'P250 | Valence', 'Sawed-Off | Origami'],
        'purple' : ['AWP | Worm God', 'MAG-7 | Heat', 'CZ75-Auto | Pole Position', 'UMP-45 | Grand Prix'],
        'pink' : ['Five-SeveN | Monkey Business', 'Galil AR | Eco', 'FAMAS | Dijinn'],
        'red' : ['M4A1-S | Hyper Beast', 'MAC-10 | Neon Rider'],
    },
}
KNIVES = ['Karambit', 'Flip knife', 'M9 Bayonet', 'Bayonet', 'Flachion', 'Shaddow Daggers', 'Bowie Knife']
WEAR = ['battle scarred', 'well worn', 'field tested', 'minimal wear', 'factory new']
BONUS_KEYS = {
    'purple': 1,
    'pink': 3
    'red': 7
}


def open_case(case):
    chance = random.randint(1, 100)
    for (rarity, skins), y in zip(list(case.items()), [25, 10, 5, 2]):
        if chance < y:
            continue
        track_chance = random.randint(1, 100)
        skin = random.choice(skins)
        wear = random.choice(WEAR)
        item = f"{skin} ({wear}) ({rarity} skin){' (StatTrack)' if track_chance <= 35 else ''}"
        return item, chance, BONUS_KEYS.get(rarity, 0)
    return random.choice(KNIVES), chance, 15


def case_run(keys):
    while keys:
        resp = input("Which case would you like to open? ")
        try:
            case = CASES[resp.lower()]
        except KeyError:
            print ("Please see list for cases")
            continue
        else:
            item, chance, bonus_keys = open_case(case)
            print(f"You've won a {item}")
            print(f"With a chance of {chance}")
            if bonus_keys:
                print(f"Nice! {bonus_keys} more keys!")
            keys += bonus_keys - 1
            print(f"Keys left: {keys}")
    else:
        print ("You've run out of keys")

def main():
    keys = 1
    while True:
        case_run(keys)

        resp = input("Would you like to try again? ")
        if resp.lower() in ('yes', 'y'):
            keys = int(input("How many keys? "))
        else:
            break


if __name__ == '__main__':
    print ("Hello! Welcome to CS GO case lottery!")
    print ("Available cases: Wildfire and Chroma 2")
    print ("Winning a purple skin gives you 1 additional key!")
    print ("Winning a pink skin gives you 3 additional keys!")
    print ("Winning a red skin gives you 7 additional keys!")
    print ("Winning a knife gives you 15 additional keys!")

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

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

复制
相关文章

相似问题

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