I need to have both defined programs repeat 5 times
Here is my success criteria:
The program will allow each player to roll two 6-sided dice
The program will calculate and output the points each round for a players total score
The program will allow the players to play 5 rounds
The program will allow each player to roll 1 die each until someone wins if both players have the same score after 5 rounds
The program will output who has won at the of the 5 rounds
The program will let the player roll an extra die and get the number of points rolled added to their score if they roll a double
The program will not allow the score to go below 0 at any point
import random
def player_one():
global score1
print("Player One is up first")
roll = str(input("Please enter ROLL to roll the dice >")).upper()
num1 = random.randint(1,6)
num2 = random.randint(1,6)
if roll == "ROLL":
showscore1 = print("You rolled a",num1,"and a",num2)
else:
exit()
score1 = num1 + num2
if (score1 % 2) == 0:
score1 = score1 + 10
else:
score1 = score1 - 5
if score1 < 0:
score1 = 0
else:
score1 = score1
print("Your score was",score1)
return score1
player_one()
import time
time.sleep(3)
def player_two():
global score2
print("Player Two is up first")
roll = str(input("Please enter ROLL to roll the dice >")).upper()
num1 = random.randint(1,6)
num2 = random.randint(1,6)
if roll == "ROLL":
showscore1 = print("You rolled a",num1,"and a",num2)
else:
exit()
score2 = num1 + num2
if (score2 % 2) == 0:
score2 = score2 + 10
else:
score2 = score2 - 5
if score2 < 0:
score2 = 0
else:
score2 = score2
print("Your score was",score2)
return score2
player_two()
time.sleep(2)
if score1 > score2:
print("Player One has won the game!")
else:
print("Player Two has won the game!")
Not needed but if you could add some more of my success criteria to my program would be helpful, but for now I'm really looking for the loop. Thanks
The additional success criteria would be:
The program will allow each player to roll 1 die each until someone wins if both players have the same score after 5 rounds
The program will output who has won at the of the 5 rounds
The program will let the player roll an extra die and get the number of points rolled added to their score if they roll a double
If you use
for x in range(0,5):
function()
the function will be run 5 times. Also, using global is bad practice. You should return the values from the function and assign them to variables. I recently did this same challenge, and this is my solution: https://pastebin.com/Zc1nj0Mi
Related
I have to create a program for one of my classes that will follow the basic rules of the game "Craps". This involves getting two random dice rolls and checking if the total shows for a win, a loss, or a reroll until a win or loss. That part isn't the issue at hand though. Where I am stuck is introducing a win/loss counter for these rolls. If someone could please guide me on implementing this into my code, or revising the code so it is possible to do so.
#Imports
import random
#Variable declaration
D1 = 0
D2 = 0
DTotal = 0
WinningValues = [7,11]
LosingValues = [2,3,12]
WinTotal = 0
LoseTotal = 0
def gameloop():
D1 = random.randint(1,6)
D2 = random.randint(1,6)
DTotal = D1 + D2
print("You rolled", D1, "and", D2,"for a total of", DTotal)
if DTotal in WinningValues:
print("You win")
Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
craps(Cont)
elif DTotal in LosingValues:
print("You lose")
Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
craps(Cont)
else:
print("You roll again")
craps(Cont="Y")
def showstats(WinTotal, LoseTotal):
print("You won a total of",WinTotal,"and lost a total of",LoseTotal,"times.")
def craps(Cont):
if Cont == "Y":
gameloop()
if Cont == "S":
print("Executing")
showstats(WinTotal, LoseTotal)
if Cont == "X":
quit()
#Program running
Cont = input("Would you like to play a game of craps? Type Y to play or X to quit: ")
if Cont == 'Y':
gameloop()
elif Cont == 'X':
quit()
I have tried implementing WinTotal += 1 after print("You win") but it comes back with a local variable referenced before assignment error that I have tried debugging but just haven't had any luck with it, let alone understanding it.
some cases not added like..
if someone pressed wrong key but he/she wanted to play again.
Code:-
import random
win,lose=0,0
asking=input("Would you like to play a game of craps? Type Y to play or any other key to quit: ")
while asking=="Y":
WinningValues = [7,11]
LosingValues = [2,3,12]
while True:
D1 = random.randint(1,6)
D2 = random.randint(1,6)
total=D1+D2
print("You rolled", D1, "and", D2,"for a total of", total)
if total in WinningValues:
print("You win")
win+=1
break
elif total in LosingValues:
print("You lose")
lose+=1
break
else:
print("You roll again")
asking=input("Type Y to roll again, S to see your stats, or any other key to exit: ")
if asking=="S":
print("You won a total of",win,"and lost a total of",lose,"times.")
asking=input("Type Y to roll again or any other key to quit: ")
if win or lose:
print("Your Stats are: ")
print("Win: "+str(win))
print("Lose: "+str(lose))
else:
print("You have not played any game")
Output:-
#Testcase1 When user not played any game..!
Would you like to play a game of craps? Type Y to play or any other key to quit: A
You have not played any game
#Testcase2 User played and wanted to know stats of his/her game and when exit also see his/her stats.
Would you like to play a game of craps? Type Y to play or any other key to quit: Y
You rolled 4 and 3 for a total of 7
You win
Type Y to roll again, S to see your stats, or any other key to exit: Y
You rolled 5 and 5 for a total of 10
You roll again
You rolled 6 and 4 for a total of 10
You roll again
You rolled 3 and 3 for a total of 6
You roll again
You rolled 1 and 4 for a total of 5
You roll again
You rolled 5 and 3 for a total of 8
You roll again
You rolled 1 and 2 for a total of 3
You lose
Type Y to roll again, S to see your stats, or any other key to exit: Y
You rolled 2 and 6 for a total of 8
You roll again
You rolled 6 and 4 for a total of 10
You roll again
You rolled 4 and 1 for a total of 5
You roll again
You rolled 1 and 1 for a total of 2
You lose
Type Y to roll again, S to see your stats, or any other key to exit: S
You won a total of 1 and lost a total of 2 times.
Type Y to roll again or any other key to quit: A
Your Stats are:
Win: 1
Lose: 2
So I'm relatively new to python and I'm having issues with fixing the leaderboard part of the code. I've spent a lot of time but I haven't been able to make it work. I know there are a few examples of answers to the same question on stack overflow but so far none of them have worked. Is there any way to make it work?
#task2
import random #When the user rolls the dice this will give them a random number
import time #It'll pause the sequence for a specific amount of time
enter = 0 #the number of times a user enters Username and Password
tries = 0 #this is the number of times a user fails to enter the correct verification
rolling = 0 #this is the number of rounds the game continues to loop, which is 5
i = 0 #required for for...loop
rounds = 0 #this is for last while statements where the winner is decided
p1sc = 0 #for total score of player 1 which is added or taken away each round
p2sc = 0 #for total score of player 2 which is added or taken away each round
while enter == 0: #if enter becomes anything other than 0, the game will start
try:
leaderboard_list = [0,0,0,0,0,'-','-','-','-','-']
file = open('leaderboard.txt', 'x')
for item in leaderboard_list:
file.write('%s\n' % item)
file.close
except:
print("")
code = input("Input the authorization code to play this game: ")
if code == ("password"): #Checking whether the input code is "dice" or not
print("You have entered authorization code correctly, enjoy the game!")
player1 = input("What would Player 1 like to be called? ") #asking user 1 to input the name they want to be called
player2 = input("What would Player 2 like to be called? ") #asking user 2 to input the name they want to be called
print(player1,"and",player2 +", prepare to play, the game will now start...")
time.sleep(1)
enter = 1
else:
print("\nIncorrect authorization code please try again!")
tries = 1 + tries #required for next if statement
if tries == 4: #If user enters wrong password or username 4 times than the user have to wait 1 minute and try again until the user gets username and password correct
print("You have entered incorrect authorization code too many times, please try again after 1 minute!")
time.sleep(60) #For 1 minute the user won't be able to try again
tries = 0
else:
print()
if enter == 1:
for i in range(0,5): #this will allow the upcoming code to be looped only 5 times
while rolling == 0: #if rolling is 1 then player 2 has to roll the dices this continues, until i is in range(0,5)
p1 = input("\n"+ str(player1) +", press r to roll the dice: ")
if p1!= "r":
print()
else:
p1dice1 = random.randint(1,6) #allows any number to be chosen from 1 to 6
p1dice2 = random.randint(1,6)
p1dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p1dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p1dice2)
p1total = p1dice1 + p1dice2
rolling = 1 #for next while loop statement which is for player 2
if p1dice1 == p1dice2: #if statements according to the game rule
print("You rolled a double.Well done! You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p1dice3)
p1total = p1total + p1dice3
else:
p1total = p1total
if p1total%2 == 0: #To check whether the number is odd or even
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p1sc,"as a total score.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5 #after it is subtracted from 5, elif statement is used as only after subtracting the number; the number can be less than, equal or greater than 0
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5. Now,you have",p1sc,"as a total score.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p1sc,"as a total score.")
else:
print()
while rolling == 1: #if rolling is 0 then player 1 has to roll the dices this continues, until i is in range(0,5)
p2 = input("\n"+ str(player2) +", press r to roll the dice: ")
if p2!= "r":
print()
else:
p2dice1 = random.randint(1,6)
p2dice2 = random.randint(1,6)
p2dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p2dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p2dice2)
p2total = p2dice1 + p2dice2
rolling = 0 #for player 1 to roll the dices again
rounds = rounds + 1 #for the game to loop 5 times and be checked by upcoming while rounds == 5
if p2dice1 == p2dice2:
print("You rolled a double.Well done!You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p2dice3)
p2total = p2total + p2dice3
else:
p2total = p2total
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p2sc,"as a total score.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5. Now,you have",p2sc,"as a total score.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p2sc,"as a total score.")
else:
print()
while rounds == 5:
while p1sc == p2sc:
print("\nAs you both have the same score, now you both will have to keep rolling 1 dice until someone wins!")
time.sleep(2)
p1 = input("\n"+ str(player1) +", press y to roll the dices: ")
if p1 != "y":
print()
else:
p1dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p1dice1)
p1total = p1dice1
if p1total%2 == 0:
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
p2 = input("\n"+ str(player2) +", press y to roll the dices: ")
if p2 !="y":
print()
else:
p2dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p2dice1)
p2total = p2dice1
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
if p1sc > p2sc:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player1)+" is the winner with "+str(p1sc)+" points.")
print(str(player2)+", better luck next time. Your total score is "+str(p2sc)+".")
rounds = 6 #to stop the loop
else:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player2)+" is the winner with "+str(p2sc)+" points.")
print(str(player1)+", better luck next time. Your total score is "+str(p1sc)+".")
rounds = 6 #to stop the loop
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
for x in range(0,4): #Shuffles the list down depending on how high the scoore was
curr = leaderboard_list[x]
if leaderboard >= curr:
for i in range(5, x + 1, -1):
leaderboard_list[i + 4] = leaderboard_list[i + 3]
leaderboard_list[i - 1] = leaderboard_list[i - 2]
leaderboard_list[x] = leaderboard
leaderboard_list[(x + 5)] = winner
break
else:
pass
file = open('score.txt', 'w+') #Writes the updated highscore list into the txt file
for item in leaderboard_list:
file.write('%s\n' % item)
file.close()
print("""The highscores for this game are """) #Prints the highscore list
for x in range(5):
print(x + 1,") ", leaderboard_list[x], " by ", leaderboard_list[x + 5])
The error message:
Traceback (most recent call last):
File "main.py", line 190, in <module>
leaderboard_list[j] = int(leaderboard_list[j])
IndexError: list out of range
Thanks! Any help would be appreciated!
The relevant part of your code is this:
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
When posting a question here, it's probably best to keep it small like that.
Anyway, you are iterating over range(0,4). This gives you:
[0, 1, 2, 3] as values for j.
So essentially, your for-loop is doing the following:
leaderboard_list[0] = int(leaderboard_list[0])
leaderboard_list[1] = int(leaderboard_list[1])
leaderboard_list[2] = int(leaderboard_list[2])
leaderboard_list[3] = int(leaderboard_list[3])
And this crashes with an IndexError.
That means that one (or all) of these indexes do not exist. The list is probably either empty, or less than 4 lines long.
The easiest way to debug this is to simply print the list before you do this operation:
print(*leaderboard_list)
And the operation that you're trying to do (turn them all into int values) can be done like this:
leaderboard_list = map(int, leaderboard_list)
Good luck on your Python journey!
I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break
I have created a dice game which displays the scores at the end of each round. I would like to know how to separately add up the scores of both players so it displays the total score of 5 rounds.
This is the code below:
import random
import time
def bothDice():
count=0
while count<5:
count=count+1
score=0
print("Round",count)
print("Player One rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player One rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
else:
score=score-5
print("======","Your combined score is ", score,"======")
score=0
print("Player Two rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player Two rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
else:
score=score-5
print("======","Your combined score is ", score,"======")
def main():
bothDice()
main()
How would I make the scores of each round add together?
Thanks
I'd suggest you to re-write your code -- For instance, you can use a for loop instead of a while loop to keep track of rounds. I think use of dict or list is useful. I added two dictionaries for both players, result_p1 and result_p2 that store scores per round. The score can be negative (not sure if intended).
Here is the code below:
import random
import time
def bothDice():
count=0
# New dicts that store counts
result_p1 = {}
result_p2 = {}
while count<5:
count=count+1
score=0
print("Round",count)
print("Player One rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player One rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
else:
score=score-5
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
print("======","Your combined score is ", score,"======")
# Store result of this round for player 1
if score != 0:
result_p1[count] = score
else:
result_p1[count] = 0
score=0
print("Player Two rolls first dice")
time.sleep(1)
dice1=(random.randint(1,6))
print("you rolled a ",dice1)
print("Player Two rolls second dice")
time.sleep(1)
dice2=(random.randint(1,6))
print("you rolled a ",dice2)
score=dice1+dice2
if score%2==0:
score=score+10
else:
score=score-5
if dice1==dice2:
print("You rolled a double- You get an extra roll")
for x in range (1):
print("You rolled a:")
extraDice=(random.randint(1,6))
print(extraDice)
extraScore = score+extraDice
score = extraScore
print("======","Your combined score is ", score,"======")
# Store result of this round for player 2
if score != 0:
result_p2[count] = score
else:
result_p2[count] = 0
# Print sum of results using f-string in python 3.
print(f"Player 1 scores: {result_p1}")
print(f"Player 2 scores: {result_p2}")
print(f"Sum of player 1 score: {sum(result_p1.values())}")
print(f"Sum of player 2 score: {sum(result_p2.values())}")
def main():
bothDice()
main()
This might be useful if my print statement didn't make sense.
Here is an output of the new print statements.
Player 1 scores: {1: 9, 2: 13, 3: 17, 4: 0, 5: 19}
Player 2 scores: {1: 17, 2: 13, 3: 13, 4: -2, 5: -2}
Sum of player 1 score: 58
Sum of player 2 score: 39
Edit: Added if statements before adding score to player dict to check if score is negative. If negative -> add 0 instead.
I can't exit the program when the condition at start of the code is met and it also prevents the rest of the code from working when it is not met. However if you remove the conditions from the start the code works fine. How do I get the conditions at the start to work properly? P.S I know the code can be condensed.
import sys
user1 = (input("User 1 type your name " )).lower
user2 = (input("User 2 type your name ")).lower
if user1 != "bob":
sys.exit()
if user2 != "fred":
sys.exit()
from random import randint
total = 1
score1 = 0
score2 = 0
while total <6:
roll = (input("User 1 x press 1 to roll the dice "))
if roll == "x":
dice = randint(1,6)
print("You got",dice)
score1 = score1+dice
print("User 1 your score is",score1)
roll2 = (input("\nUser 2 press x to roll the dice "))
if roll2 == "x":
dice = randint(1,6)
print("You got",dice)
score2 = score2+dice
print("User 2 your score is",score2)
total = total+1
if total == 6:
print("\nUser1 your total score is",score1)
print("User2 your total score is",score2)
while total >= 6:
if score1 == score2:
print("It's a tie! Whoever rolls the highest number wins")
roll = (input("User 1 press x to roll the dice"))
if roll == "x":
dice = randint(1,6)
print("You got",dice)
score1 = score1+dice
print("User 1 your score is",score1)
roll2 = (input("\nUser 2 press x to roll the dice"))
if roll2 == "x":
dice = randint(1,6)
print("You got",dice)
score2 = score2+dice
print("User 2 your score is",score2)
if score1 > score2:
print("\nUser 1 wins")
break
if score1 < score2:
print("\nUser 2 wins")
break
lower is actually a method, and you have to call it. Instead of writing .lower try writing .lower()