establishing a win streak in dice game - python

Hi all. Really, REALLY stuck here. I've updated my code below.
I'm trying to establish a counter to track games played, correct guesses and > incorrect guesses plus, when the number of consecutive correct guesses
= 4 or user stops playing, game summary is provided.
I cannot get the counter to work correctly.
Help appreciated!
import math
import dice
import random
# Print introduction and game explanation
print ("")
print ("")
print ("Would you like to play a game?")
print ("The game is...'Petals Around the Rose'. Cool eh?")
print ("Pay attention - the name of the game is important.")
print ("Each round, five dice are rolled and")
print ("You'll be asked for the score. (Hint? The score")
print ("will always be either 'zero' or an even number).")
print ("Your challenge is to deduce how the computer has")
print ("calculated the score.")
print ("You need to input your guess, after which")
print ("You'll learn if you were right. If not, you'll")
print ("be told the correct score & asked to roll again.")
print ("If you can guess correctly four times in a row,")
print ("You'll be declared the winner and receive the")
print ("majestic title of 'Potentate of the Rose'")
print ("")
# Define win count (four correct guesses in a row required)
win_count = 0
# Obtain input from user:
answer = input("Are you up for the challenge? Enter 'y' or 'n' : ")
# If answer = no, exit game
if answer == 'n':
print("Really? fine then. See ya!")
exit()
# If answer = yes, commence game
elif answer == 'y':
print("")
print ("Ok...here comes the first roll!")
print("")
# import dice representation
import dice
# Roll random dice x 5
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
die3 = random.randint(1, 6)
die4 = random.randint(1, 6)
die5 = random.randint(1, 6)
dice.display_dice(die1, die2, die3, die4, die5)
# Obtain player's guess for the roll
roll_guess = int(input("Enter your guess for this roll: "))
# Define die results for all dice for guess purposes to
# match the 'petals around the rose'. So, if roll a 2, 4 or 6,
# the result is zero. If return a 3, the result is 2. If
# return a 5, the result is 4.
def roll_result(die1):
if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
die1 = 0
elif die1 == 3:
die1 = 2
elif die1 == 5:
die1 = 4
return die1
def roll_result(die2):
if die2 == 1 or die2 == 2 or die2 == 4 or die2 == 6:
die2 = 0
elif die2 == 3:
die2 = 2
elif die2 == 5:
die2 = 4
return die2
def roll_result(die3):
if die3 == 1 or die3 == 2 or die3 == 4 or die3 == 6:
die3 = 0
elif die3 == 3:
die3 = 2
elif die3 == 5:
die3 = 4
return die3
def roll_result(die4):
if die4 == 1 or die4 == 2 or die4 == 4 or die4 == 6:
die4 = 0
elif die4 == 3:
die4 = 2
elif die4 == 5:
die4 = 4
return die4
def roll_result(die5):
if die5 == 1 or die5 == 2 or die5 == 4 or die5 == 6:
die5 = 0
elif die5 == 3:
die5= 2
elif die5 == 5:
die5 = 4
return die5
# tally all 5 dice rolls
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
# Compare user input to dice result
if roll_guess == total_roll_result:
print("")
print('Well done! You guessed it!')
print("")
elif guess % 2 == 0:
print("")
print("No sorry, it's", total_roll_result, "not", roll_guess)
print("")
else:
print("")
print ("No, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
# Obtain user input if continuing to play
another_attempt = input("Are you up to play again? If so, enter y or n ")
print("")
# Commence loop and win count.
while another_attempt == 'y' and win_count <4:
# Commence win count
win_count = 0
# Commence games played count
games_played = 0
# Commence incorrect guesses count
incorrect_guesses = 0
# If user has not yet gotten 4 guesses in a row:
if win_count < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = dice.display_dice(die1, die2, die3, die4, die5)
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
roll_guess = int(input('Enter your guess for this roll: '))
print("")
if roll_guess == total_roll_result:
# Update win count
win_count += 1
# Update games played count
games_played += 1
print("")
print('Nice work - you got it right!')
elif roll_guess %2 == 0:
# reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print("Nah, sorry, it's", total_roll_result, "not", roll_guess)
else:
# Reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print ("Nah, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
another_attempt = input("Are you up to play again? ")
# Quit loop if user no longer wishes to play
# Provide game summary
if another_attempt == 'n':
print ("")
print ("Game Summary")
print ("------------")
print ("")
print ("You played ", games_played, "games.")
print ("")
print ("You had ", correct_guesses, "overall and ")
print ("")
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
if win_count == 4:
# Inform player has correctly guessed 4 in a row
# Print congratulations message
print ("")
print ("")
print ("You've done it! You've successfully guessed")
print ("Four times in a row. Looks like you worked ")
print ("out the secret. Now, stay stum & tell no one!")
print ("")
# Provide game summary
print ("Game Summary")
print ("")
# Provide tally of games played & print:
print ("You played ", games_played, "games.")
print ("")
# Provide tally of correct guesses & print:
print ("You had ", correct_guesses, "overall and ")
print ("")
# Provide tally of total incorrect guesses & print:
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
def game_stats():
win_count
games_played
incorrect_guesses

You look very lost here. This part does not make any sense
def win_count():
win_count() == 0
correct == total_roll_result
I think you mean something like this
win_count = 0
correct = total_roll_result == roll_guess
Note
When you say
def win_count:
# some code
you are defining win_count as a function! But clearly you want win_count to be an integer counting something.

Related

Python -- 3 dices game question by using while loop

I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass

How would I be able to test the below code so that I can see how the tiebreaker would function?

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)

Elif prints wrong message

I asked a similar question before, except the solution did not seem to work. I am writing a dice rolling game that if any one of the player's numbers matches the computer's numbers, the player wins and a message prints "You win." If otherwise, the elif statement means the computer wins and it prints "You lose."
My problem is that the elif statement won't print "you lose." it just keeps printing "you win."
import random
die1 = 0
die2 = 0
die3 = 0
roll1 = 0
roll2 = 0
roll3 = 0
def dice_roll():
dieroll = random.randint(1, 6)*2
return dieroll
for die in range(12):
die1 = int(input(f'Choose a number between 2 and 12: '))
die2 = int(input(f'Choose a number between 2 and 12: '))
die3 = int(input(f'Choose a number between 2 and 12: '))
roll1 = dice_roll()
roll2 = dice_roll()
roll3 = dice_roll()
if die1 or die2 or die3 == roll1 or roll2 or roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
elif die1 or die2 or die3 != roll1 or roll2 or roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Lose! - Thanks for playing!')
Inside of your for loop, the parameters of the if statement have been declared incorrectly. Here's an example to help clarify it:
a=1
b=3
if a or b == 2:
print(True)
else:
print(False)
The if statement in the above example will always print True because you are asking the following: "if a holds a value that is True/greater than 0 or if b is equal to 2: print True" In your case:
if die1 or die2 or die3 == roll1 or roll2 or roll3
You are declaring your parameters as "if die1, roll2, or roll3 have any True/greater than 0 values or if die3 is equal to roll1: ...", so just change this to the actual values you want them compared to as Abhigyan Jaiswal's answer says and it will work correctly.
If you want to check if any of die1, die2, die3 matches any of roll1, roll2, roll3 then you can use:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
if {die1, die2, die3} & {roll1, roll2, roll3}:
print('You win. Thanks for playing.')
else:
print('You lose. Thanks for playing.')
This checks if the set of {die1, die2, die3} and the set of {roll1, roll2, roll3} have any elements in common.
Also, and by the way, random.randint(1, 6)*2 is not equivalent to rolling two dice. It's rolling one die and doubling the result; so all the odd numbers are excluded, and the probabilities are flattened. If you want to simulate rolling two dice, you want random.randint(1,6) + random.randint(1,6).
Adding on to khelwood's answer, you can use this method if you prefer this syntax
From your code logic, it seems that the player automatically wins when they make at least 1 correct guess(which I am not sure if this is your intention).
if die1 == roll1 or die2 == roll2 or die3 == roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
else:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Lose! - Thanks for playing!')
Python evaluates each condition that is separated by the keyword. A non-null value would always return True
Hence if you are doing this method
elif die1 or die2 or die3 != roll1 or roll2 or roll3:
die1 die2 roll2 roll3 will always return True and that is what causing your program to always print "You lose"
#You can do this as well
if die1 == roll1 or die2 == roll2 or die3 == roll3:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Win! - Thanks for playing!')
else:
print(f'Roll # 1 was {roll1}')
print(f'Roll # 2 was {roll2}')
print(f'Roll # 3 was {roll3}')
print(f'You Loose! - Thanks for playing!')

Python3 can't repeat the loop after else statement (googled it and did'nt find a solid resault)

can't repeat the loop after the "else statement" (googled it and did'nt find a solid resault)
example:
I'm trying to make a dice game
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
user_input = input("Roll the Dice? [Y/N] ")
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while user_input:
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
else:
print('Invalid')
continue
user_input = input("Roll again? [Y/N] ")
print(user_input)
Your while loop needs a condition. While x == 1: or while 1:
If you use x = 1. When the value of x is other than 1, the while loop will stop or when a break is used.
If you use while 1, it will continue to loop until you use break.
Another point, you want to have the user_input within the while loop so that it can ask the user if they would like to roll again.
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
x = 1
while x == 1:
user_input = input("Roll the Dice? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
Answer: As noted by Klaus, removing the continue in the while user_input will fix the loop, to only re-roll when the user responds 'y'
Changing print(dice_roll()) to just dice_roll() (function call without printing it's return value) will keep this program from printing 'None' after dice rolls.
If you want it to print the return, you can change the
print(" The sum is", dices_sum) to
return(" The sum is", dices_sum)
try this
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while 1:
user_input = input("Roll? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input == 'y':
dice_roll()
elif user_input == 'N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
There are two problems that you need to fix.
Since your function dice_roll ends without return syntax, python interpreter will add return None at the end of the function. I change 'print(dice_roll())' to 'dice_roll()'.
In your while loop, if elif else syntax has covered all situations, the code will never go to
user_input = input("Roll again? [Y/N] ")
print(user_input)
So, I just put these two lines in front of 'if elif else'. and remove ' again'.

How log my score best out of three and use different symbols for the players? Python

I'm making a 2-play Battleship game in python and have been struggling with this for a while now:
I apologise if the question is poorly worded but I was to know how I can make my game log the match score at the end of the three games with something like:
print('Match score is' + score + 'Player' + (whoever) + 'wins!)
I'm not entirely sure how to implement this myself I have a range for games in range(3), but I don't know how to log the final score.
Also, how can I change the symbol for player_two so that I am not using an 'X' for both players? I've tried changing the input_check() but I get more errors than I did before.
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
else:
return player_two
# Allows new game to start
def play_again():
global ship_points
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns(turns) == player_one:
# print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
You can use style string formatting to print the log.
print('Match score is %d : %d(Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
For more information about string formatting, check this link.
To change the symbol for Player 2, you can change the following code.
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"

Categories