7
\$\begingroup\$

I'm a beginner in Python, 1-2 months experience. Please assess my code. I used a dictionary to store cases. The cases_data is stored in another file. Is the structuring right? My code seems to have a lot of whitespace, how can I restructure it for readability? The code runs successfully as intended, but is the code suited for maintainability (adding new features)? Am I following the Python standard? Is this satisfactory for industrial standard? I did this project for leisure.

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()
\$\endgroup\$
5
\$\begingroup\$

Welcome to Python, language of the whitespace. Second only to whitespace itself. More seriously your code is alright, however I'd recommend you change it a lot to make it better.

  • Python has a style guide called PEP8, I recommend that you follow this style guide so that other Python users can more easily read and understand your code.
  • Don't use global, there normally is a way around using it. In this example there's actually no need for it. Using global is a bad habit to get into, and is heavily discouraged.
  • There's no need for sys.exit. Your code will work the same way if you just returned from the function.
  • Split up your function. open_case should be one of your functions, and a main should be another.
  • Use __main__. This prevents code from running if you import it.
  • Since you're using random.choice on the other attributes of the item, it doesn't make sense to me for skin_wear to be on it's own.
  • The if else around if trakChance <= 35: makes your code wet. Instead you can use an f-string.

    f"{' (StatTrack)' if track_chance <= 35 else ''}"
    
  • Breaks breaks everywhere! I'd recommend you use control flow statements when needed, but not when they're not. Improper use can lead to confusion, and can make spaghetti code.

  • You have a bug resp2.lower() == 'yes' or 'y' is always True. This is as it checks the left hand side of or, resp2.lower() == 'yes'. If this is true, then it skips checking the right hand side, otherwise it checks the right hand side. So if resp2 is n, then the result of the statement is y. Which is truthy.

    Instead use in and build a tuple or a set. Such as:

    if resp2.lower() in ('yes', 'y'):
    
  • Your code requires an implementation detail on dictionaries to work correctly:

    The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon

    Instead use an OrderedDict.

  • You may want to store your global constants in a file outside of Python. One way to do this is in JSON.

Using most of the above I changed your code to:

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()
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Clear and understandable, thank you. This project burnt half of my brain. \$\endgroup\$ – Ali S Jul 31 '17 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.