#πŸ”’ Numpad Minesweeper (first ever project)

91 messages Β· Page 1 of 1 (latest)

neon lake
#

Hello everyone, i started learning python not so long ago and it's the first language im learning and also the only experience i have with programming/coding, as you will be able to tell by looking at the first code i ever wrote on my own (without any help), i liked doing everything on my own but now i want some opinions and feedback + recommendations on how this code could be better, i know it could potentially be alot shorter and cleaner atleast.

import random
"""Numpad MineSweeper"""
number = random.randint(1, 9)
points = 0
guess = 0
guesses = [1, 2, 3, 4, 5, 6, 7, 8, 9]

while guess != number: 
    guess = int(input("Press a number! (1 to 9) "))
    if guess <= 0 or guess > 9:
        print("Invalid")
    elif guess in guesses:
        guesses.remove(guess)
        points += 1
    else:
        print(f"You already clicked {guess} ")  
    print(guesses)
    print(f"Points: {points}")
    if points >= 8:
        print("You win!! ")
        break  
else:
    print(f"BOOM!!! {number} was the bomb. Points: {points}")
    
orchid starBOT
#

@neon lake

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

shrewd hound
#

ok - it's short, so you don't really need to do this... but the first suggestion for code improvement in a game is breaking it up into subroutines

#

it'd be a nice learning experience to see how this could work

#

once you've done this, you could add a display function, which displays your minefield after each go

neon lake
neon lake
proud summit
#

It strikes me as a bit odd that the guess isn't checked until the end of the loop. If the user guesses 6 and 6 is the bomb, the entire loop body will run, and then guess != number is checked at the end of the loop. In theory, other if branches could be entered, even if the user guessed the bomb.

#

It looks like that is actually a bug. If you guess the bomb on the last point, it looks like that will count as a win.

neon lake
#

I just tested this and you're 100% correct, it counted as a win

#

i couldn't have noticed that bug honestly i always thought i was just always lucky to always guess right on the last two remaining numbers lol, should've known it was a little too lucky

proud summit
#

An easy fix for that would be to do something like change the while to a while True, use break to to exit the loop for both failure and wins, and use a flag to indicate if the loop was exited due to a failure or win condition.

neon lake
#

i see, i'll try that out for sure, thanks alot!

proud summit
#

You're welcome. (The part I missed from that suggestions was the condition that is now the loop's condition would be moved to the first if condition in the loop, and you'd break there if they guessed the bomb).

neon lake
#

btw i've seen people use the while loop like that (while True:) but i never really understood how it works, or rather why it works like that

#

i mean usually you have a condition that starts the loop but if its always set on True then.. my brain kind of hurts while thinking about this lol

shrewd hound
#

tbh i tend to avoid while True / infinite loops

Some people frown upon them, which sort of keeps me away from them, though it's all valid code as long as you know why you've made the choice

proud summit
#

There's nothing special about a while True loop. A while loop loops while the condition is True/truthy. True is always True/truthy though, so the loop will loop forever; assuming it doesn't contain a break. They're useful when using the loop's condition is unweildy, or if you actually want an infinite loop.

neon lake
#

that does sound useful, and it's the only fix i know for that bug atm but is there another way that bug could be fixed while also using the same while condition? or any while condition other than an infinite while true loop? im thinking maybe i'll need it for when i decide to add more conditions or expand my code in a way that needs it somehow

shrewd hound
analog light
#

there's basically no different between breaking and using a condition

analog light
shrewd hound
analog light
#

sorry which one

proud summit
shrewd hound
#

we're solving someone else's code, not talking about me

neon lake
analog light
#

but i feel like just people other people dont like something doesnt mean you should either

shrewd hound
#

basically... the loop is meant to repeat about 10 times / until a condition is met

So it seems a bit hacky to stop it doing that, and then put the condition elsewhere

neon lake
proud summit
#

while (guess := input()) != number:

neon lake
proud summit
#

I'm not going to claim I like := there, but it's an option.

shrewd hound
#

i don't like that either

analog light
#

makes sense

proud summit
#

I like := less the more I see it, but given the constraints, I can't think of an alternative off hand

neon lake
#

asking for input in the while condition

shrewd hound
#

if it's confusing, it's not the best

#

keep things clean

proud summit
neon lake
#

and why dont you guys like it being there? any reason?

proud summit
#

Shoving too much onto one line hurts readability, and readability comes before pretty much everything else in most cases.

shrewd hound
#

well - an input always returns a string, for a start

#

so if you're comparing it to a number, you'd need to cast it

proud summit
neon lake
shrewd hound
#

yes... but again, you're getting increasing complexity

neon lake
#

oh so its just because its a long line in general

#

got it

shrewd hound
#

it's just going to be a horrible thing, when it doesn't need to be

proud summit
#

At the end of the day, I'd go for the while True with a condition elsehwhere. I only suggested the assignment expression in the condition because you said you wanted to avoid while True.

neon lake
#

yeah it seems like the while True option is the cleanest out of the two

shrewd hound
#

how about a while that's based on whether it actually needs to continue looping?

neon lake
#

but it was nice knowing different options honestly thank you

shrewd hound
#

When should the code stop looping?

proud summit
#

You could also put if number != guess in the body as a duplicated condition and skip the rest of the body. You could see if that's cleaner.

neon lake
#

so a failure and a success

shrewd hound
#

Yep - so have a condition that changes, and stick that in the while.

neon lake
#

and it loops after either an invalid input or a correct guess

shrewd hound
#

well ... it loops until the game is "won" or "lost"

#

or "ended"

#

If that's the logic, put that into the condition

#

rather than just looping infinitely

neon lake
#

but also when someone types in an invalid number or a number that they already typed, but yeah

#

ill try different approaches

shrewd hound
#

so you could test for

while !game_ended:

or something like that

#

at least it's then logical when you look at the while

#

so you can read the code and understand at what point the loop should cease

#

if it's a break, it could end anywhere - it's a bit wild

neon lake
#

soo that's about 3 different options that i could try now lol

#

thank you both honestly, great help

shrewd hound
#

I'd seriously not do a while True: without trying other options first.

neon lake
#

ill post the different options when im done with them later if you want to check

shrewd hound
#

I don't mind either way. It's more if you're wanting structural advice really.

neon lake
#

any advice is appreciated honestly, im still learning the basics lol

shrewd hound
#

oooh also...

While / Else

Not a fan

#

once a while has finished looping, it's left the loop anyway!

shrewd hound
#

ok I've made a version

#

it's actually ages since I posted code in here though

#
import random
"""Numpad MineSweeper"""
number = random.randint(1, 9)
points = 0
guess = 0
guesses = [1, 2, 3, 4, 5, 6, 7, 8, 9]

game_running = True
#print("number: ", number)

def doAGuess():
    return int(input("Press a number! (1 to 9) "))


while game_running:
    print(guesses)
    print(f"Points: {points}")
    guess = doAGuess()
    if guess <= 0 or guess > 9:
        print("Invalid")
    elif guess in guesses:
        guesses.remove(guess)
        points += 1
        if guess == number:
            print(f"BOOM!!! {number} was the bomb. Points: {points}")
            game_running = False
        elif points >= 8:
            print("You win!! ")
            game_running = False
        else:
            game_running = True # not needed but just saying
    else:
        print(f"You already picked {guess} ")  
    
print("Game Over")
#

So I tried to follow what I think was your logic.

#

I've got one function, doAGuess(), which returns an integer

#

Then the loop keeps looping until game_running == False

orchid starBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.