I had to build a game which awards players based on their guess. The user guesses a number and the algorithm compares that to a randomly-generated 2-digit number and awards the player accordingly.
Problem: The player needs to play this game 3 times before the game ends. When I loop it 3 times with a while loop it only loops by asking the user for their guess and does not print or return the award message. When I remove the while loop and use a for loop it only runs once and prints the message.
How do I solve this looping issue and run this program thrice?
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1
def lottery_game():
for x in range(play):
lottery = random.randrange(10,99)
lot = list(map(int, str(lottery)))
guess = int(input("Choose a 2 digit number: "))
n_guess = list(map(int, str(guess)))
if guess == lottery:
return "You won: " + str(jackpot) + " Euros"
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
return "You won: " + str(award2) + " Euros"
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
return "You won: " + str(award3) + " Euros"
else:
return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"
while i <= 3:
lottery_game()
i = i + 1
According to your code, you're not initialising your i variable before your while you shoud definitely do it. But for your use case, you shouldn't use a while, you should use a for loop like this:
for i in range(0,3):
This will run the code in the loop three times.
You need to
replace return with print statement:
replace while i <= 3 with for i in range(3)
Here is updated code:
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
def lottery_game():
lottery = random.randrange(10, 99)
lot = list(map(int, str(lottery)))
guess = int(input('Choose a 2 digit number: '))
n_guess = list(map(int, str(guess)))
if guess == lottery:
print(f'You won: {jackpot} Euros')
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
print(f'You won: {award2} Euros')
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
print(f'You won: {award3} Euros')
else:
print(f'I am sorry, you won: {noaward} Euros. Try again')
for i in range(3):
lottery_game()
Sample output:
Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
Choose a 2 digit number: You won: 100 Euros
Choose a 2 digit number: You won: 10000 Euros
you have not initialized i
Before the while statement add i=1
Related
I'm trying to write a simple program to test out the basics of Python I've been learning. I decided to do a simple tongue in cheek gambling script that checks a user entered number against a 1,100 random generated number. I want to multiply the users stake by a different amount depending on how close to the random number the user guessed, but cant seem to get it to check within a range using == or <= etc. Or at least cant work it out.
i.e, user stakes 10 on number 15.
if the random number is 20 it's within 5 of the users number so multiply the stake by 25.
if the random number is 25 its within 10 or less of the users number so multiply by 10 etc.
Here's what I've got, would love to hear any advice on this!
if random_number == int(playernumber):
playerstake = int(playerstake) * 100
print("\nCongratulations, you hit the JACKPOT and won £" + str(playerstake) + "!!!")
#+/- 1
elif int(playernumber) == int(random_number) + 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
#+/- 5
elif int(playernumber) == int(random_number) + 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
etcetc
I understand this currently doesn't work because I'm == random number + 1
so 12 would be 13.
Apologies if I've done something frowned upon here, this was my first script I tried to tackle and wanted to see the potential ways to have done this 'properly'. Thanks for the replies!
If I'm understanding correctly, much simpler code:
dist = abs(guess - rand_num)
if dist == 0:
multiplier = 100
elif dist <= 1:
multiplier = 50
elif dist <= 5:
multiplier = 20
elif dist <= 10:
multiplier = 10
else:
multiplier = 0
player_stake += player_stake * multiplier
if dist == 0:
print("Congratulations you've won")
else:
print("Congratulations you guessed {0} within {1} and won ${3}".format([multiplier, rand_num, player_stake])
Here's a simple solution. I'll let you discover how it works!
pn = int(player_number)
rn = random_number
if rn == pn:
print("You won!")
elif rn in range(pn-1, pn+1+1): # range goes up to the final value (less than), so you need a +1
print("You won +- 1!")
elif rn in range(pn-5, pn+5+1):
print("You won +- 5!")
else:
print("You lost!")
The next chlallenge would be to make the 'checks', +-1, +-5, an array of values, but that was outside the scope of your question.
Don't repeat yourself. You could replace your if clauses with a lookup table. With only 3 things, its a toss-up whether this is better, but generally, if the logic is the same within multiple conditional clauses, its good to pull that logic out into a single implementation. The lookup table lets you change the boundaries used for selection without touching the logic.
# assumes `diff`, `random_number` and `playerstake` defined at time of use
exact_text = f"Congratulations, you hit the JACKPOT and won £{playerstake}"
near_text = f"Congratulations, you guessed within {diff} of {random_number} and won £{playerstake}"
# lookup table: (diff, payout, text)
odds = [
(0, 100, exact_text),
(1, 50, near_text),
(5, 20, near_text)
]
playernumber = int(playernumber)
playerstake = int(playerstake)
player_diff = abs(random_number - playernumber)
for diff, payout, text in odds:
if player_diff <= diff:
playerstake *= payout
print(text)
break
else:
print(f"You were {player_diff} away from the random number")
So I ran into trouble with this code again with output. Basically, there are some key features I need it to print, but whenever I manage to get it to print one thing it completely messes up the rest of the printing. So for example, I need it to print Roll # 1 (1 - 3) was (whatever number) not Roll (whatever number) if that makes sense. But I also need it to only max out to 3 rolls. This is where my second issue comes in; whenever I try to code it to subtract the bet from the bank when a user doesn't match any rolls, it counts my subtraction as a fourth roll and screws up the math. So instead of Roll #1 through #3 its now up to Roll #4
My third problem is, I need to the program to continue looping until the user enters 0 (zero) to end the script or the bank amount reaches 0 (zero).
You should redesign your program. First of all, you are generating new results for each condition check at
if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
Your code is not properly indented.
[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
And so on...
Have a function that simulates a single dice roll, like:
def roll():
return random.randint(1, 6)
And handle the rest in your main function like:
prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
A couple changes get the result you want
Pass the roll count to the rollDice function
Add an else to the bottom of the if block to check 0 bank
Here is the updated code:
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet # no match
if bank == 0:
print('You have no money left. Thanks for playing!')
exit()
Output
You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!
i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)
I'm trying to debug some code I have written for homework, but I cannot fix an error that occurs no matter what I try.
I've tried copying some code from my friends, but no matter what code I try I keep getting this error.
#NEA 2019 DICE GAME
from time import sleep as wait
from random import randint as rand
#Here I have imported my modules that I will use later on.
Check1 = 0
#Here I create a check variable, for use in the usernames section.
print("welcome to Dice Game!")
print("Main Menu: \n 1. Play Game \n 2. Register User \n 3. View Leaderboard \n 4. Quit Game")
MenuChoice = int(input("Please enter the number of the option you would like to choose."))
#Nice greeting for the user, and a menu.
elif MenuChoice == 1:
while Check1 == 0:
Namae = input("Player One, Please enter your username: \n")
with open('Usernames.txt') as openfile:
if Namae in openfile.read():
print("Username",Namae, "Valid!")
Check1 = 1
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
#This 'if' statement allows the user to log in using a universal passkey, or allows an administrator to log in using a backdoor.
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username",Namae, "Invalid!")
#This block allows a user to log in as player 1.
while Check1 == 1:
Namae2 = input("Player Two, Please enter your username: \n")
if Namae == Namae2:
print("Both players can't have the same username!")
Namae2 = ''
with open('Usernames.txt') as openfile:
if Namae2 in openfile.read():
print("Username", Namae2, "Valid!")
Check1 = 0
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username", Namae2, "Invalid!")
#This block allows a user to log in as player 2.
P1total = 0
P2total = 0
for i in range (1,5):
print("Game starting!")
wait(1)
print("ROUND", i)
print(Namae, " Press 'Enter' to roll")
#This gives the player a message box to allow them to roll.
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This is the command to roll the dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This gives the player another dice if they roll a double.
else:
Roll3 = 0
#This sets the value of Roll3 to zero, to prevent a NameError later on.
TempTotal = Roll1 + Roll2 + Roll3
print("The total of the dice is", TempTotal)
#These lines add together all of the dice.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#These lines check if the dice total is even, then adds 10 if it is.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#These lines check if the dice total is odd, then subtracts 5 if it is.
P1total = P1total + TempTotal
if P1total < 0:
P1total = 0
#These lines make sure that the total cannot go below 0, and sets it to 0 if it does.
print(Namae, "Your total is", P1total)
#This prints the current total for player 1.
print(Namae2," Press 'OK' to roll")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This rolls the two dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This adds another dice if the player rolls a double.
else:
Roll3 = 0
#This sets Roll3 to 0 to prevent a NameError later on in the code.
TempTotal = Roll1 + Roll2 + Roll3
#This adds up the dice to create a total.
print("The total of the dice is", TempTotal)
#This tells the player what the dice rolled.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#This adds 10 points to the total if they roll an even number.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#This takes away 5 points from the total if they roll an odd number.
P2total = P2total + TempTotal
if P2total < 0:
P2total = 0
print(Namae2, "Your total is", P2total)
if P1total == P2total:
print("There is a draw! \n Both players will roll 1 die.")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that there cannot be a draw
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
while Roll1 == Roll2:
print("Another Draw!")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that if the first reroll ends in a draw, there will keep being rerolls until there is no longer a draw.
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
if Roll1 > Roll2:
print(Namae, "Wins!")
#Prints a winning message.
else:
print(Namae2, "Wins!")
#This prints a winning message
elif P1total > P2total:
print(Namae, "wins!")
Winner = Namae
WinScore = P1total
#This prints a message if player 1 wins
else:
print(Namae2, "wins!")
Winner = Namae2
WinScore = P2total
#This prints a message if player 1 wins.
#Winscore and Winner are used to append the winner to a file later on.
LeaderboardFile = open("Leaderboard.txt", "a+")
#This opens the file to be appended
FullFileInput = Winner + "," + str(WinScore) + "\n"
#This combines the two variables from earlier into one, to make it easier to append.
LeaderboardFile.write(FullFileInput)
#This appends FullFileInput to the file.
LeaderboardFile.close
#Closes the File.
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
#Opens the file for reading.
Array = []
#Creates an empty array
FileLength = len(open("Leaderboard.txt").readlines())
#This reads how many lines the file has
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
#This splits the file every time there is a comma
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
#This sorts the list in descending order, using score.
x = 1
for counter in range(0,5):
print(len(SortedArray))
holder = SortedArray[(len(SortedArray)-x)]
#This causes an error, for seemingly no reason.
print(x, ":",holder[0], holder[1])
#This prints the leaderboard, one line at a time.
x = x + 1
#Increments x by 1.
elif MenuChoice == 3:
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
Array = []
FileLength = len(open("Leaderboard.txt").readlines())
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
x = 1
for counter in range(5):
holder = SortedArray[(len(SortedArray)-x)]
print(x, ":",holder[0], holder[1])
x = x + 1
#Lines 198 to 211 are all copied and pasted from the leaderboard earlier.
#This code is a formatting disaster, I'm sorry.
After messing around with the game for a bit, with the error appearing every time it attempted to show the leaderboard, I have some files.
Leaderboard.txt:
Contains scored in the format:
Username1,score
Username2,score
And so on...
Usernames.txt:
Contains all valid usernames.
I would expect the result to be something along the lines of:
Top 5 Scores:
1: Alpha 100
2: Beta 91
3: Gamma 85
4: Delta 76
5: Epsilon 69
Instead, the code prints:
Top 5 Scores:
1: Alpha 1
2: Alpha 1
(this always prints the first value in the file twice, without sorting it.)
And then I get the error:
Traceback (most recent call last):
File "main.py", line 200 in <module>
holder = SortedArray[(len(SortedArray)-x)]
IndexError: list index out of range.
The 'IndexError: list index out of range' means that your list indices are out of range. You are trying to refer to some index that doesn't even exist.
holder = SortedArray[(len(SortedArray)-x)]
x = x + 1
For example if x becomes greater than (len(SortedArray) you will get a negative index that can trigger that error.
I hope you don't mind, but I rewrote a part of your code.
elif MenuChoice == 3:
print("Top 5 Scores:")
Array = []
try:
with open("Leaderboard.txt", "r") as LeaderboardFile:
for l in LeaderboardFile.readlines():
name, score = l.split(',')
name = name.strip()
score = int(score.strip())
Array.append([name, score])
except Exception:
print('FileNotFound')
Array = sorted(Array, key = lambda x: x[1], reverse=True)
for i in range(5):
print(f'{i+1}: {Array[i][0]} {Array[i][1]}')
Please, note for next time that because this question is very specific to your own code it is less suitable for SO, but more for https://codereview.stackexchange.com/.
Good luck with your homework assignment.
I am making this code for a school project and whenever it enters an even number, it is supposed to check if that number is in the list then add 10 to it. instead, it just skips the +10 bit and instead minuses 5 from it. here is the code:
import random
print("Lets Play")
play1 = input("Player 1 name?")
play2 = input("Player 2 name?")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")
diceNumber = float(random.randint(2,12))
diceNumber2 = float(random.randint(2,12))
diceNumber3 = random.randint(2,12)
diceNumber4 = random.randint(2,12)
diceNumber5 = random.randint(2,12)
diceNumber6 = random.randint(2,12)
diceNumber7 = random.randint(2,12)
diceNumber8 = random.randint(2,12)
diceNumber9 = random.randint(2,12)
diceNumber0 = random.randint(2,12)
print(play1, "Your number is...")
print(diceNumber)
print(play2, "Your number is...")
print(diceNumber2)
evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]
if (diceNumber) == (evennumber):
(diceNumber01) = (diceNumber) + float(10)
else:
(diceNumber01) = (diceNumber) - float(5)
evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]
if (diceNumber2) == (evennumber):
float(diceNumber2) + float(10)
else:
float(diceNumber2) - float(5)
print (play1, "Your total points is",diceNumber01,)
print (play2, "Your total points is",diceNumber2,)
You should use the in operator to check if a value is among the values in a list.
Change:
if (diceNumber) == (evennumber):
to:
if (diceNumber) in (evennumber):
You have a some excess and issues in here, here's a brief summary and some changes.
Only two dice being used, no need to create 10
No clear purpose for dice values being float
Can check for evens using if not x % 2, also if we were to use even list as shown, the only relevant evens are 2 through 12
diceNumber == evennumber is checking one value to see if it equals and entire list, if used properly would be if diceNumber in evennumber
This statement float(diceNumber2) + float(10) assigns the result to nothing
Here is a cleaned up version with some modifications, I recommend using random.choice here and just select a random number from a range of numbers so you don't have to randomly generate a new int in range everytime, results will be the same.
from random import choice
print("Lets Play")
play1 = input("Player 1 name: ")
play2 = input("Player 2 name: ")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")
die = list(range(2, 13))
d_1 = choice(die)
print(play1, "Your number is...\n{}".format(d_1))
d_2 = choice(die)
print(play2, "Your number is...\n{}".format(d_2))
if not d_1 % 2:
d_1 += 10
else:
d_1 -= 5
if not d_2 % 2:
d_2 += 10
else:
d_2 -= 5
print (play1, "Your total points is",d_1)
print (play2, "Your total points is",d_2)
Lets Play
Player 1 name: vash
Player 2 name: stampede
Hi vash & stampede, let's roll the dice
vash Your number is...
5
stampede Your number is...
2
vash Your total points is 0
stampede Your total points is 12