r/learnpython • • Dec 24 '20

Just made my first "full" program ever! It's a game where you rob people and try to avoid the Cops. Show me some tricks, easier ways to do this, or even cool add ons I could incorporate!

I'm really proud of myself. I'm sure that it isn't cool at all to anyone else - but this is 2 months of me studying Python every day for a hour.

What are some cool things I can add?

What about easier or alternative ways to do this?

import random

def Robbery():
    total = 0
    lootlist = []
    lootposs = ["Watch", "Computer","Diamond"]
    attempts = int(input("Pick a number of times"))
    counter = 0
    watch_total = 0
    computer_total = 0
    diamond_total = 0
    game = "on"
    sentence = random.randint(0,15)
    print(f"----------------------------------------------------------------------")
    print("\n----------START OF THE GAME----------\n")
    for nums in range(attempts):
        Outcome = random.randint(0, 10)
        if Outcome in [0,1,2,3,4]:
            stolen = random.randint(0,1000)
            total = total + stolen
            counter = counter + 1
            print(f"----------------------------------------------------------------------")
            print(f"\nNumber {counter} attempt was successful:")
            print(f"-------------------------------------------")
            print(f"You stole {stolen} dollars.")
            print(f"You have stolen {total} dollars so far")
            print(f"You have stolen {watch_total} watch, {computer_total} computer, and {diamond_total} diamond so far")
        elif Outcome in [5,6,7]:
            loot = random.choice(lootposs)
            if loot == "Watch":
                watch_total = watch_total + 1
            elif loot == "Computer":
                computer_total = computer_total + 1
            else:
                diamond_total = diamond_total + 1
            lootlist.append(loot)
            counter = counter + 1
            print(f"----------------------------------------------------------------------") 
            print(f"\nNumber {counter} attempt was successful:")
            print(f"-------------------------------------------")
            print(f"You stole a {loot}!")
            print(f"You have stolen {total} dollars so far!")
            print(f"You have stolen {watch_total} watch, {computer_total} computer, and {diamond_total} diamond so far!")
        else:
            counter = counter + 1
            game = "off"
            print(f"\n----------------------------------------------------------------------")
            print(f"\nNumber {counter} attempt YOU WERE CAUGHT :( \n")   
            print(f"You robbed {counter} times, stole {total} dollars!")
            print(f"You took {watch_total} watch, {computer_total} computer, and {diamond_total} diamond!")
            print(f"You went to prison for {sentence} years!")
            break
    if game == "on":
        print(f"\n----------------------------------------------------------------------")     
        print(f"\nNumber {counter} attempt YOU WERE NEVER CAUGHT!!!!! :) \n \n")
        print(f"You robbed {counter} times, stole {total} dollars")
        print(f"You took {watch_total} watch, {computer_total} computer, and {diamond_total} diamond")
418 Upvotes

46 comments sorted by

25

u/ffrkAnonymous Dec 24 '20

One of the ideas of programming is DRY, Don't Repeat Yourself. So a next possible step (because the first step is working code) is to look for places where the code is the same. For example, your print(). That can get refactored into a loop or function. The rule of thumb (not hard and fast) is 3-times. So, it's not urgent , but something to keep in mind as you expand your game.

Zanfar mentioned classes. I would suggest "namedtuples", then classes later.

Speaking of classes, I always recommend this post by Al Sweigart. https://inventwithpython.com/blog/2014/12/02/why-is-object-oriented-programming-useful-with-a-role-playing-game-example/

And he has books where you can get more ideas. https://inventwithpython.com/#invent

1

u/MinnesotaLuke Dec 24 '20

These links are gold. Thank you!!

As for the loop or function can you provide an example? I've realized that I'm so visual in python opposed to understanding when somebody tells me

1

u/ffrkAnonymous Dec 24 '20

of course. For example,

print(f"----------------------------------------------------------------------")
print(f"\nNumber {counter} attempt was successful:")
print(f"-------------------------------------------")

you can pull this out and turn it into a function:

def print_header():
    print(stuff)
    print(more stuff)
    print(more more stuff)

Then your original code replaces that with the function call:

counter = counter+1
print_header()
print(f"You stole...)

Now your code is "easier to see" what it's meant/trying to do, rather than the details of how it does it.

print_header()
print_action_status()
print_footer()

Later on because you already wrote single-purpose functions, you'll already be set for unit-testing.

5

u/[deleted] Dec 24 '20

Damn... That post about classes was probably the best explanation I've seen. I think it helped that the example used was something I'm familiar with. Either way, I understand more about classes than I did before. Thank you!

2

u/0161WontForget Dec 24 '20

I haven’t seen that post about classes! Bookmarked it.

Classes are something my brain sometimes lags with as I don’t use them that regularly in projects so thanks for this.

6

u/[deleted] Dec 24 '20

The code is really good to be your first "full" program, congrats. Later, i will play the game

1

u/MinnesotaLuke Dec 24 '20

Thank you so much

6

u/RaykanGhost Dec 24 '20

Nice, there's one thing I'd like to point out, for perfectionism's sake, your "attempts" variable is kind of a bomb:

If the player inputs anything that can't be converted into an integer, the program crashes. There's a number of ways to fix this, personally I'd go with the "Try & Except" method, which basically tries the input, and if the player doesn't input a number, you expect a ValueError, print a message and automatically try again.

Another thing you could do is not repeating the "print" function so many times, though realistically it just helps code readability, it's a good skill to have.

Regardless this is a neat little game, keep up the good work!

1

u/MinnesotaLuke Dec 24 '20

Omg great point about the errors.. I'm gonna add that

The print function I only did because in my environment (Juypter notebook) it really looks so terrible in one line lol

3

u/[deleted] Dec 24 '20

Well done. Why not challenge yourself to have a game menu with start, play again and quit options. What about a high score the persists? Could you use OOP here? Those things should keep you busy for another couple of months.

1

u/MinnesotaLuke Dec 24 '20

Omg this sounds amazing. I guess I'll have to look up how to do this since at the moment I have no idea how to add external elements like this

237

u/zanfar Dec 24 '20

I want to be clear, this is a really good beginner result. What I'm posting below is not a criticism, it's intended to be constructive help.

  • lootposs = ["Watch", "Computer","Diamond"]:

    This is a good practice, you've kept UI text out of variable names, and put choices into data structures. This lets you do things like correct spelling, increase options, or translate code easily in the future.

    However

    you then immediately break this good practice with:

      watch_total = 0
      computer_total = 0
      diamond_total = 0

    and if loot == "Watch":

    Now if you have to correct spelling or something similar, your code breaks. "Watch" in this case is something akin to a "Magic Number"--a value in your code that has dependencies or context outside your program.

    Consider keeping your loot counters in another list--then you can reference everything by index; better yet, go pro and use a list of dictionaries or other objects:

      loot = [
          { "name": "Watch", "count": 0 },
          { "name": "Computer", "count": 0 },
          { "name": "Diamond", "count": 0 },
      ]
    
      elif Outcome in [5,6,7]:
          loot_idx = random.randrange(len(loot))
          loot[loot_idx]["count"] += 1

    Now, your code does not depend on the spelling or amount of choices at all. Your loot output will need a bit more work to keep up, but I'm confident you can handle it :)

  • attempts = int(input("Pick a number of times"))

    This is a bit nitpicky for beginner-level code, but you really need to validate user input and handle exceptions. What if someone enters "a"? or what about nothing?

  • game = "on":

    This should really be a boolean value so that it's clear it's a flag or toggle. were_caught = False would both make the use of the variable, and it's possible states more clear.

  • for nums in range(attempts):

    In Python, when we don't intend to use a variable (exactly as in this case) it's convention to use _ to make that intention clear. However, you also include counter = counter + 1 in every loop, which has the same value as nums. So I would suggest using for round in range(1, attempts+1) which makes it clear exactly what you are tracking. You can then replace counter with round and remove all the instances of counter = counter + 1.

  • Outcome = random.randint(0, 10)

    Python convention is that variables use snake_case--that is, no capitalization.

  • if Outcome in [0,1,2,3,4]:

    You know that Outcome is an integer between 0 and 9, so this is better stated as if Outcome <= 4:. Creating a new list and then searching it is a (small, in this case) waste of memory and time.

Some of these are really nitpicky, and the others are good practice--but ultimately insignificant in a program of your size, so don't get down about them.

For a next step, I would encourage you to explore these options:

  • Build an input validation routine so that the user can't break your program, and then use it to play rounds until the user wants to give up their criminal lifestyle. Essentially, a push-your-luck gameplay style.

  • Extend your loot options and give them values, then make the total game score the sum of the money stolen, and the value of the loot stolen.

  • For all the marbles: this program begs to become a Class. Consider reading up on classes and re-factoring into a Game class that takes the type of loot as initialization variables. Basically, build a class that can play your above game using the code:

      if __name__ == "__main__":
          g = RobberyGame("Watch", "Computer", "Diamond")
          g.play()

I'm off to do this myself, 'cause I enjoy doing exactly this. Congrats and thanks for the idea!

34

u/industrial_by_trade Dec 24 '20

go pro and use a list of dictionaries

The example code for this is exactly what I should be using for my own project. I was slicing a list of lists and I thought it looked ugly.

12

u/kwelzel Dec 24 '20

Very good comment. Regarding the loot variable

loot = [
    { "name": "Watch", "count": 0 },
    { "name": "Computer", "count": 0 },
    { "name": "Diamond", "count": 0 },
]

I would prefer a dictionary indexed by name:

loot_count = [
    { "Watch": 0 },
    { "Computer": 0 },
    { "Diamond": 0 },
]

You can still get a random item loot_item = random.choice(loot_count) and then increase its count by loot_count[loot_item] += 1, but when debugging it's clear what item was chosen just from the content of loot_item.

13

u/zanfar Dec 24 '20

This is another good suggestion. You'd need to actually use a dictionary, though :)

loot_count = {
    "Watch": 0,
    "Computer": 0,
    "Diamond": 0,
}

However, I still don't like indexing things by UI values. I doubt it makes a functional difference, but I try to avoid even the possibility of doing something like if loot_item == "Watch":

It also makes separating the loot definitions from the loot count "harder"--say if you wanted to make the game multiplayer--but admittedly not by much.

This is actually something I've bounced back-and-forth on, and probably far above the level of /r/learnpython, but I've used an enum-indexed dictionary of dataclasses in the past to cross both bridges: putting context in the key without injecting UI properties:

class LootType(IntEnum):
    WTCH = auto()
    COMP = auto()
    DIAM = auto()

@dataclass
class LootDef:
    singular: str
    plural: str
    value: str

loot: Dict[LootType, LootDef] = {
    LootType.WTCH: LootDef("Watch", "Watches", 750),
    LootType.COMP: LootDef("Computer", "Computers", 1200),
    LootType.DIAM: LootDef("Diamond", "Diamonds", 5000),
}

@dataclass
class PlayerCareer:
    name: str
    cash: int
    stolen: Dict[LootType, int] = field(default_factory=lambda: defaultdict(int))

loot_key = random.choice(LootType)
player.stolen[loot_key] += 1

print(f"{player.name} has stolen a {loot[loot_item].singular")
worth = player.cash
if player.cash > 0:
        print(f"* ${player.cash} in Cash")
for loot_key in LootType:
    if player.stolen[loot_key] > 0:
        value = player.stolen[loot_key] * loot[loot_key].value
        worth += value
        print(f"* ${value} in {item.plural}")
print(f"For a total net worth of ${worth}")

You could also freeze the LootDef and use it as an index, but that feels wrong to me for some reason. All of this is probably a more than a little Architecture Astronauting, but it feels right to me for some reason.

It also lets you set the various LootTypes to a magic number that you can use to query something like a database or external data file to load in something like internationalization data or images. That is, LootType.WTCH = 93 is asset 93, and that can remain constant and magic without compromising any other code while still allowing cross reference with other datasets.

Again, all far above /r/learnpython

2

u/kwelzel Dec 24 '20

Oh, you're completely right about the dictionary. Must have been half asleep when writing this, at least what I wrote was clear enough to understand me. I also completely agree that using Enums would be best here, even though it might be over-egineered for a text based game about being a thief.

1

u/doulikepeaches Dec 24 '20

This is awesome and so helpful to many beginners!!!

2

u/Johan2212 Dec 24 '20

You can validate your inputs with inputplus module (PyInputPlus).

Also incrementing in python is normally done with the '+=' operator :-)

Looks good thou

2

u/MinnesotaLuke Dec 24 '20

Can you explain what the first thing means?

As for the second, I knooooww but I still get in the habit of doing it long hand 🤣🤣🤣

1

u/Johan2212 Dec 24 '20

If you import the PyImportPlus module it's doing the validation for you.
try using the following code and use letters or floats as the input - You might need to install the module through pip :-)

import pyinputplus as pyip

test = pyip.inputInt('Write an integer: ')

2

u/0161WontForget Dec 24 '20

Congrats!

I’d add some randomness in regards to how many watches, computers and diamonds they steal and append with += after each round.

Also try to make it more interactive and the possibility of being caught by a policeman. Perhaps add a day and night mode, so if you rob in the day you have a higher probability of being caught than at night.

Also perhaps how you rob people, gunpoint, knifepoint had an effect with how much loot you can effectively get?

This is a nice little program OP, I may even build on top of what you’ve done myself and add some of these features in!

1

u/MinnesotaLuke Dec 24 '20

Omg great ideas thank you so much

2

u/[deleted] Dec 24 '20

Im a beginner too, but no where near your level. How do i play your game after i copy and paste your code in sublime?

3

u/MinnesotaLuke Dec 24 '20

Hey. After you run this chunk of code then the next line enter this

Robbery ()

It's pretty boring but still

1

u/[deleted] Dec 24 '20

Dont downplay your hard work! I cant wait to run it

1

u/MinnesotaLuke Dec 31 '20

in sublime im not really sure tbh

1

u/shaq_disel Dec 24 '20

give it a try using pycharm as your IDE

1

u/Rad-Hi Dec 31 '20

I just started python and copy pasted the code but nothing popped up when I ran it. Is that meant to happen?

1

u/MinnesotaLuke Dec 31 '20

Hey. Copy and paste the code (I just added "import random" at the top for it to run properly.

Then either last line, or the very next line you make do "Robbery()" without the quotations.

1

u/Rad-Hi Jan 01 '21

thx a lot!

1

u/N3belherr Dec 24 '20

Absolute newbie question:

How do I run this?

I copied it in my Code OSS, imported random but i doesn't start.

3

u/0161WontForget Dec 24 '20

You need to call that function.

So at the end do Robbery() and it’ll run

1

u/N3belherr Dec 24 '20

Oh I feel so stupid. Thanks!

4

u/0161WontForget Dec 24 '20

No problem! We’ve all been there brother! All part of the experience.

1

u/robstersgaming Dec 24 '20

RemindMe! 1 day

1

u/RemindMeBot Dec 24 '20

I will be messaging you in 1 day on 2020-12-25 19:03:41 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


InfoCustomYour RemindersFeedback

1

u/Xadios468 Dec 24 '20

Man I’ve been learning code for about a year, but this shows me that I’ve got a long way to go in the creativity department lmao. Great job op!

0

u/[deleted] Dec 24 '20

[deleted]

3

u/[deleted] Dec 24 '20

He spent two months teaching himself something new. Why the need to crap all over that by being rude?

2

u/[deleted] Dec 24 '20

[removed] — view removed comment

1

u/MinnesotaLuke Dec 24 '20

lmao yeah thats me. Merry Christmas brah

1

u/[deleted] Dec 24 '20

[removed] — view removed comment