I am one week into a coding bootcamp so forgive my simplistic and probably sloppy coding, but I was wondering how I could put in a running tally of wins for my two player dice rolling game. I am able to produce the final score and loop the function back around to start again if the players want to keep playing but I would like to keep a running tally of wins so the players know how many times each player has won. Here is my function:
def DiceRoll():
Dice1 = random.randint(1, 20)
Dice2 = random.randint(1, 12)
Dice3 = random.randint(1,6)
Dice4 = random.randint(1, 20)
Dice5 = random.randint(1, 12)
Dice6 = random.randint (1, 6)
DoubleDice1 = (((Dice1 + Dice2)*2) + Dice3)
DoubleDice2 = (((Dice1 + Dice3)*2) + Dice2)
DoubleDice3 = (((Dice2 + Dice3)*2) + Dice1)
DoubleDice4 = (((Dice4 + Dice5)*2) + Dice6)
DoubleDice5 = (((Dice4 + Dice6)*2) + Dice5)
DoubleDice6 = (((Dice5 + Dice6)*2) + Dice4)
TripleDice1 = ((Dice1 + Dice2 +Dice3) * 3)
TripleDice2 = ((Dice4 + Dice5 +Dice6) * 3)
print("Player 1, Roll?")
Roll = input("Y/N?")
if Roll =="y":
print("Ok!")
if Roll == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice1, Dice2, Dice3)
Score1 = Dice1 + Dice2 + Dice3
if Dice1 == Dice2:
Score1 = DoubleDice1
print(Score1)
elif Dice1 ==Dice3:
Score1 = DoubleDice2
print(Score1)
elif Dice2 == Dice3:
Score1 = DoubleDice3
print(Score1)
elif Dice1 == Dice2 ==Dice3:
Score1 = TripleDice1
print(Score1)
else:
print(Dice1 + Dice2 + Dice3)
print("""
""")
print("Player 2, Roll?")
Roll2 = input("Y/N?")
if Roll2 =="y":
print("Ok!")
if Roll2 == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice4, Dice5, Dice6)
Score2 = (Dice4 + Dice5 + Dice6)
if Dice4 == Dice5:
Score2 = DoubleDice4
print(Score2)
elif Dice4 == Dice6:
Score2 = DoubleDice5
print(Score2)
elif Dice5 == Dice6:
Score2 = DoubleDice6
print(Score2)
elif Dice4 == Dice5 ==Dice6:
Score2 = TripleDice2
print(Score2)
else:
print(Dice4 + Dice5 + Dice6)
print("""
""")
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
if Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
if Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
Since there is no loop in your function, I assume that you have that control loop in the program that calls DiceRoll. To make a clean tally, you'll need to return the win/lose designation to that program, something like this:
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
else:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
Now, back in your main program, we'll have something like:
p1_wins = 0
p2_wins = 0
ties = 0
while game_on:
result = DiceRoll()
if result == 1:
p1_wins += 1
elif result = 2
p2_wins += 1
else:
ties += 1
I've kept this at the level of programming I think you're using. First you get to understand it. In a few more boot camp sessions, come back to see how you'd like to improve your coding.
The most simplistic solution would be to have the DiceRoll function return which player won.
winner = None
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
elif Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
return winner
Then in the loop that calls DiceRoll, just check the returned result.
Now, you've got a lot of repeated code in this function. You're basically doing everything twice. This makes it a prime candidate for breaking into another function. I would suggest making a function that takes the player as a parameter, and then does the dice rolls for just that player, and returns the score. Then you could just call the function for each player, compare the results, and determine the winner from that.
One last thing. If a player chooses not to roll, it's exiting the program. That should probably be changed to be considered a forfeit, and have it exit at the outer loop so you can display the final tally.
Related
As you can see, I'm a complete beginner at Python so any help would be appreciated. My issue is that I'm trying to test the code for all the scenarios, but I'm unable to test the tiebreaker. Sure, I could just insert Player1Score = Player2Score (which I've hash tagged to show the location) but that would just send the program into an endless loop, which defeats the purpose of the tiebreaker. So is there any way that I can I can have the program only go through the tiebreaker segment once and then let a single player win?
(I apologize if I've made any errors with my question, I'm new to stackoverflow as well)
import random
def DiceGame():
Count = 0
Player1Score = 0
Player2Score = 0
while Count <= 4:
Count += 1
print ("\n It is Round",Count, "\n")
print ("It is Player 1's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player1Score += Score
print ("Player 1, your score so far is",Player1Score)
print ("It is Player 2's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player2Score += Score
print ("Player 2, your score so far is",Player2Score)
#Player1Score = Player2Score
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame()
elif Player1Score >= Player2Score:
print ("Player 1 wins!")
elif Player1Score <= Player2Score:
print ("Player 2 wins!")
def Rolls():
Roll1 = random.randint(1,6)
Roll2 = random.randint(1,6)
print ("You got a",Roll1)
print ("You got a",Roll2)
Score1 = Roll1 + Roll2
if Score1 == 2 or Score1 == 4 or Score1 == 6 or Score1 == 8 or Score1 == 10 or Score1 == 12:
print ("Your total is even so you get an extra 10 pts.")
Score2 = Score1 + 10
print ("Your score for this round is" ,Score2)
elif Score1 == 3 or Score1 == 5 or Score1 == 7 or Score1 == 9 or Score1 == 11:
print ("Your total is odd so you lose 5 pts.")
Score2 = Score1 - 5
if Score2 <= 0:
print ("Your score has gone below 0pts. It will therefore be reset to 0pts")
Score2 = 0
print ("Your score for this round is" ,Score2)
return Score2
DiceGame()
If you really want to, you can add temporary player scores to test the function, and then remove them again if you see they work. Usually running it would just be good enough, but as you mentioned it would loop forever. This does kinda show that it works though, I guess, but I agree it's not optimal.
def DiceGame(count, p1, p2):
Count = count
Player1Score = p1
Player2Score = p2
...
Then at the bottom of your file call it as DiceGame(5, 1, 1), and in your tiebreaker call it as DiceGame(0, 0, 0). This will force a tie on the first run, and will run it normally the second time.
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame(0, 0, 0)
... # code inbetween
# end of file
return score2
DiceGame(5, 1, 1)
I am making a two-person dice game where there are five rounds, but I want to keep the scores the same from the previous rounds, how do I do that?
The rules of the game are as follows:
• The points rolled on each player’s dice are added to their score.
• If the total is an even number, an additional 10 points are added to their score.
• If the total is an odd number, 5 points are subtracted from their score.
• If they roll a double, they get to roll one extra die and get the number of points rolled added to
their score.
• The score of a player cannot go below 0 at any point.
• The person with the highest score at the end of the 5 rounds wins.
• If both players have the same score at the end of the 5 rounds, they each roll 1 die and
whoever gets the highest score wins (this repeats until someone wins).
import random
import time
total_player2score = 0
total_player1score = 0
rounds = 0
player_1 = 0
player_2 = 0
while rounds != 5:
total_player2score = total_player2score + player_2
total_player1score = total_player1score + player_1
rounds = rounds + 1
number = random.randint(1, 6)
number2 = random.randint(1, 6)
total_player1score = number + number2
print("*"*50)
print("Round {}!".format(rounds))
print("*"*50)
print("Player 1's turn. Type 'roll' to roll the dice.")
player1_input = input(">>> ")
if player1_input == "roll":
time.sleep(0.5)
print("Player 1's first roll is", number)
print("Player 1's second roll.Type 'roll' to roll the dice")
player1_input = input(">>> ")
if player1_input == "roll":
time.sleep(0.5)
print("player 1's second roll is", number2)
if total_player1score % 2 == 0:
total_player1score = total_player1score + 10
print("Player 1's total is even so 10 points will be added")
print("*"*50)
print("Player 1 has", total_player1score, "points")
else:
total_player1score = total_player1score - 5
total_player1score = max(0, total_player2score)
print("player 1's total is odd so 5 points will be deducted")
print("*"*50)
print("Player 1 has", total_player1score, "points")
number = random.randint(1, 6)
number2 = random.randint(1, 6)
total_player2score = number + number2
print("*"*50)
print("Player 2's turn. Type 'roll' to roll the dice")
player2_input = input(">>> ")
if player2_input == "roll":
time.sleep(0.5)
print("Player 2's first roll is", number)
print("Player 2's second roll.Type 'roll' to roll the dice")
player2_input = input(">>> ")
if player2_input == "roll":
time.sleep(0.5)
print("player 2's second roll is", number2)
if total_player2score % 2 == 0:
total_player2score = total_player2score + 10
print("Player 2's total is even so 10 points will be added")
print("*"*50)
print("Player 2 has", total_player2score, "points")
else:
total_player2score = total_player2score - 5
total_player2score = max(0, total_player2score)
print("player 2's total is odd so 5 points will be deducted")
print("*"*50)
print("Player 2 has", total_player2score, "points")
def writeUp(score_1,score_2,nameoffile):
with open(f"{nameoffile}.txt","a") as logz:
print(f"score1 {score_1}\nscore2 {score_2}",file=logz)
def readUp(nameoffile):
with open(f"{nameoffile}.txt","r") as data:
lines = data.readlines()
last_2 = lines[:2]
score_1,score_2 = None,None
for element in last_2:
splitt = element.split(' ')
if element.find('score1') != -1:
score_1 = int(splitt[1])
elif element.find('score2') != -1:
score_2 = int(splitt[1])
return score_1,score_2
sci1,sci2 = 50,50
writeUp(sci1,sci2,'mysaves')
sc1,sc2 = readUp('mysaves')
print(sc1,sc2)
#this should help, the function given creates a txt file and store scores into it
I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:
Randomly pick a number from 1-6 for two players.
Each player starts with 100 points.
Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.
Play until one of the player's score is lower or equal to zero.
The run is Python 3.7.2, and here is the code:
import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
I tried several times. When I run it, there were two problems:
One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.
The result just keep coming up with "It's a tie."
I was confused with the result and had no idea how to fix it...
Really appreciate any and all help! Thanks|ू・ω・` )
Your code only rolls the dice (gets a random number set) once.
Move the dice roll inside the while loop like so:
import random
player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
I want to code a rock paper scissors game with a scoring system that allows the user to wish to play again and the score adds on and not restarting to 0.
My code is here: https://pastebin.com/eRqEuwtY (It's also attached on this message)
Your help is appreciated.
import random
score1 = int(0)
score2 = int(0)
def main():
while True:
player = input('What do you choose to play (R, P, S)? ')
computer = random.choice(["R", "P", "S"])
print("You chose", (player), "and the computer chose", (computer))
if computer == player:
print("It's a tie")
print("Score: You =", score1, "Computer =", score2)
if computer == "R" and player == "S":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "P" and player == "R":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "S" and player == "P":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "S" and player == "R":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
if computer == "R" and player == "P":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
if computer == "P" and player == "S":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
play_again = input("Would you like to play again? Y/N ")
if play_again == "Y":
main()
else:
print("You scored", score1, "and the computer scored", score2)
exit()
main()
Your problem is that you print the score + 1 if you win. This does not save the new score to the variable!
Example:
print("You won")
score += 1
print("Score: You =", score1, "Computer =", score2)
Another problem in your code is that you call the main function again every time the user wants to play again. This is endless recursion and will result in an error if you hit the recursion limit. It's better to do it like this:
def main():
play_again = "Y"
while play_again == "Y":
#code...
play_again = input("Would you like to play again? Y/N ")
print("You scored", score1, "and the computer scored", score2)
main()
As Jasper pointed out, you need to save the new score to the respective variable. Here is a rework of your code, including some improvements:
import random
def main():
SYMBOLS = ["R", "P", "S"]
INPUTS_YES = ["Y", "YES", "I LOVE THIS GAME SO MUCH"]
INPUTS_NO = ["N", "NO", "PLZ STOP THIS"]
INPUTS_ALL = INPUTS_YES + INPUTS_NO
keep_playing = True
score_player = 0
score_computer = 0
while keep_playing:
symbol_player = input("What do you choose to play? (R, P, S)").upper()
while not symbol_player in SYMBOLS:
print("invalid input")
symbol_player = input("What do you choose to play? (R, P, S)").upper()
symbol_computer = random.choice(SYMBOLS)
print("You chose ", symbol_player, " and the computer chose ", symbol_computer)
difference = (SYMBOLS.index(symbol_player) - SYMBOLS.index(symbol_computer)) % 3
if difference == 0:
print("It's a tie")
if difference == 1:
score_player += 1
print("You won")
if difference == 2:
score_computer += 1
print("Computer won")
print("Score: You = ", score_player, ", Computer = ", score_computer)
play_again = input("Would you like to play again? Y/N").upper()
while not play_again in INPUTS_ALL:
print("invalid input")
play_again = input("Would you like to play again? Y/N").upper()
if play_again in INPUTS_NO:
keep_playing = False
print("You scored", score_player, "and the computer scored", score_computer)
if __name__ == "__main__":
main()
I was wondering if someone could tell me how to have the computer choose a new choice after every round. I got the lower portion of the code to cover all choices but it turns out my code runs where the computer uses the same choice every time. Is there a way to set my code so the computer chooses something new from the list. Thanks!
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
computerChoice = random.choice(gameList)
print(computerChoice)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
if userAnswer == "Rock" and computerChoice != "Paper":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice != "Scissors":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice != "Rock":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Paper":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Scissors":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Rock":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Rock":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Scissors":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Paper":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
else:
print("Whatever you just inputed doesn't work noodlehead, try again!")
continue
x = computerChoice()
print(userChoice(x))
Move this inside your while loop:
computerChoice = random.choice(gameList)
Currently you are saving a single choice, and then using it every time. Where as this would create a new choice each time:
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(gameList)
# Compare to see who won.
Note that gameList must be available inside that scope, so you will have to either pass it in as a function parameter or include it inside the function. That does change the nature of the function somewhat:
def game():
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
userScore, computerScore, rounds = game_loop()
def game_loop(available_options: list=["Rock", "Paper", "Scissors"]):
computerScore = 0
userScore = 0
rounds = 0
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(available_options)
// compare and score (preferably in their own functions)
return userScore, computerScore, rounds
try this
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
return random.choice(gameList)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
#all your if statements and stuff
computerChoice = computerChoice()
print(userChoice(computerChoice()))