Program exits when players number of turns = 6. Python Battleship Game - python

I'm making a 2-player battleship game in python. I've made it so that each 'game' allows a total of 6 turns (3 from each player), after which a message will appear saying 'The number of turns has ended'.
Once this happens, they will be asked to play again. If they answer 'yes' or 'y', the game should reload. However it doesn't. The board loads but the program then exits. I believe the issue lies with my play_again() function but I'm not quite sure what it is.
I want to make it so that the players can play as many games as they want until they decide to answer 'no' or 'n'. How do I go about implementing this?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
}
player_two = {
"name": "Player 2",
"wins": 0,
}
colors = {"reset":"\033[00m",
"red":"\033[91m",
"blue":"\033[94m",
"cyan":"\033[96m"
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("Find and sink the ship!")
del board[:]
build_game_board(board)
print(colors['blue'])
show_board(board)
print(colors['reset'])
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
return player_two
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
break
elif answer in negative:
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('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
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" 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"
print(colors['cyan'])
show_board(game_board)
print(colors['reset'])
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
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 number of turns has ended.")
print(colors['red'])
show_board(game_board)
print(colors['reset'])
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
play_again()
if __name__ == "__main__":
main()

It also worked for me when I added an invocation to main in your play_again() function:
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
main()
break
elif answer in negative:
print("Thanks for playing!")
exit()

Try modifying main with:
turns = 0
while turns < 6:
# Process turn...
if turns == 5:
# Show endgame board
if play_again():
turns = -1
turns += 1
And have play_again return True on positive input ['y', 'yes'] and False otherwise.

The problem is that your play_again() call, upon receiving "Y" as answer, loads the board, but then simply returns. Where? Well, to the place it was called from - the for loop in main(). And unfortunately, it is the last iteration of said for loop, so the loop then ends and the program exits.
You should've put another loop around the for loop:
while True:
for turns in range(6):
...

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 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"

Python Battleships Game

I am currently making a simple Battleships game using Python 3, but I can't seem to get the board to display. Here is my code;
# Battleships
def main():
pass
if __name__ == '__main__':
main()
from random import randint
# this initialises the board
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print (" ".join(row))
# this starts the game and prints the board
print ("Let's play Battleship!")
print_board(board)
# defines the location of the ship
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
# asks the player to make a guess
for turn in range(5):
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
# if the player guesses correctly, then the game ends cleanly
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
else:
# if the player guesses outside the board, then the following message appears
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print ("Oh dear, you've hit an island!")
# a warning if the guess has already been made by the player
elif(board[guess_row][guess_col] == "X"):
print ("That guess has already been made.")
# if the guess is wrong, then the relevant board place is marked with an X
else:
print ("You've missed my battleship!")
board[guess_row][guess_col] = "X"
# prints the turn and updates the board accordingly
print ("Turn " + str(turn+1) + " out of 5.")
print_board(board)
# if the user has had 5 guesses, it's game over
if turn >= 3:
print ("You sunk my battleship! We're gonna need a bigger boat.")
The game accepts the co-ordinates, but doesn't print anything to do with the board or if the player makes a repeated guess or one that's outside the field of play.
Any help would be much appreciated!
Your code asks for 5 sets of guesses before it does anything with them, because the code to respond to a guess is outside of the loop asking for the guesses. I'm, ahem, guessing that in your testing you never entered enough guesses to get past that loop. Move the guess-processing code into the loop, and you should at least see reactions to those guesses.
You are iterating over the loop THEN all the if statements. Put all the if statements inside the for loop. Add a counter saying if you hit my ship add one point (score += 1) then
if score >= 3:
print ("You sunk my battleship! We're gonna need a bigger boat.")
import random
from datetime import date
grid = []
def createGrid():
global grid
grid = []
for i in range(0,10):
grid.append([])
for j in range(0,10):
grid[i].append("W")
def renderGrid():
global grid
for i in range(0,10):
for j in range(0,10):
block = grid[i][j]
if block == "s": block = "W"
print(block,end=" ")
print()
print()
def placeGrid():
xsize = 10
ysize = 10
shipBlocks = 17
length = 2
submarineException = True
while shipBlocks > 0:
x = random.randint(0,xsize-1)
y = random.randint(0,ysize-1)
value = 1
cx = 0
cy = 0
if random.randint(0,1) == 1:
value = -value
if random.randint(0,1) == 1:
cx = value
else:
cy = value
broken = False
for b in range(0,length):
xpos = x+cx*b
ypos = y+cy*b
if xpos<0 or xpos>xsize-1 or ypos<0 or ypos>ysize-1: broken = True
if broken: continue
for b in range(0,length):
grid[x+cx*b][y+cy*b] = "s"
shipBlocks = shipBlocks - length
if length == 3:
if submarineException:
submarineException = False
else:
length+=1
else:
length+=1
def runGame():
name = input("Enter your username: ")
global grid
createGrid()
placeGrid()
hits = 0
while True:
won = True
for row in grid:
for character in row:
if character == "s":
won = False
if won:
print("You have won the game in "+str(hits)+" hits!")
renderGrid()
y = input("Hit X: ")
x = input("Hit Y: ")
try:
x = int(x)-1
y = int(y)-1
if x < 0 or y < 0:
raise
if grid[x][y] == "s":
grid[x][y] = "S"
print("Ship hit.")
elif grid[x][y] == "S":
print("You already hit here.")
continue
hits+=1
except Exception as e:
print("Error, number from 1 to 10 please.")
#stackoverflow saves lives
runGame()

Beginner Python-Looping to the beginning of a programme

I will start fresh! I have included the full code so you can get a picture for what i am trying to do. Prob (1) I can not loop back to the very beginning. Prob (2) It is not looping # the While higher_or_lower part of the code. it just goes through the if and else higher_or_lower statements. Thanks
done = False
while done == False:
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess)
input("Correct!\nWell done\n\n")
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the number game. Goodbye")
done = True
breaK
Ok, a primer in how Python indentation works.
number = 1
while number < 10:
print(number)
number += 1
print("this will print everytime because it's inside the while")
Output:
1
this will print everytime because it's inside the while
2
this will print everytime because it's inside the while
3
this will print everytime because it's inside the while
4
this will print everytime because it's inside the while
5
this will print everytime because it's inside the while
6
this will print everytime because it's inside the while
7
this will print everytime because it's inside the while
8
this will print everytime because it's inside the while
9
this will print everytime because it's inside the while
Notice that the second print prints every time because of it's indentation.
Now the second example:
number = 1
while number < 10:
print(number)
number += 1
print("this will print AFTER the loop ends")
Output:
1
2
3
4
5
6
7
8
9
this will print AFTER the loop ends
See how it only printed after the loop ended? That is because of the indentation. You should correct your code and indent it properly...
Ok, I corrected the code and it seems to be working now. Most of it was because of the indentation. Please try to understand how it works...
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result #this was out indented
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a guessing number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess) # this was out indented
print("Correct!\nWell done\n\n") # this all the way to the bottom was out indented
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the awesome number game. Goodbye")
done = True
It looks like adding a little structure would help you out.
Something like this might help you with doing your control flow. Hopefully gives you an outline that makes sense and makes it easier to run the loop multiple times.
""" Guess the number game.
"""
import random
def is_same(targ, num):
""" Check for correct entry. """
if targ == num:
result = "WIN"
elif targ > num:
result = "LOW"
else:
result = "HIGH"
return result
def play_game():
""" Play the game 1 time, returns play_again """
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print("""\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""")
Choose_Level = input("\t\tPlease choose your Level : ")
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
# this could be simplified to: while choose_level not in 'EMF':
Choose_Level = input("Sorry. You must type in one of the letters " +
"'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! " +
"You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1, 10)
elif Choose_Level == "M":
computer_number = random.randint(1, 50)
else:
computer_number = random.randint(1, 100)
counter = 1
higher_or_lower = ""
while higher_or_lower != "WIN":
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter += 1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
print("\nSorry, you are to low. Please try again.\n:")
elif higher_or_lower == "HIGH":
print("Guess attempts", counter)
print("\nSorry, To high. Please try again. \n:")
else:
print("Correct!\nWell done\n\n")
break
print("""
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = input("\t\t Please choose a option 'S' or 'E' ")
while start_again != "S" and start_again != "E":
# can simplify: while start_again not in 'SE':
start_again = input("You must enter a upper case letter" +
"'S' or 'E' to continue")
if start_again == "S":
return True
else:
return False
def main():
""" Main loop for playing the game. """
play_again = True
while play_again:
play_again = play_game()
print("Thanks for playing the number game. Goodbye")
if __name__ == '__main__':
main()

breaking out of python loop without using break

while answer == 'Y':
roll = get_a_roll()
display_die(roll)
if roll == first_roll:
print("You lost!")
amount_won = roll
current_amount = amount_earned_this_roll + amount_won
amount_earned_this_rol = current_amoun
print("You won $",amount_won)
print( "You have $",current_amount)
print("")
answer = input("Do you want to go again? (y/n) ").upper()
if answer == 'N':
print("You left with $",current_amount)
else:
print("You left with $",current_amount)
The purpose here of using this loop is in a game, dice are rolled, and you are rewarded money per the number of your roll, unless you roll a roll matching your first roll. Now, I need the loop to stop if that occurs, and I know this is easily achievable using a break statement, however, I have been instructed no break statements are allowed. How else can I get the loop to terminate if roll == first_roll?
You can:
Use a flag variable; you are already using one, just reuse it here:
running = True
while running:
# ...
if roll == first_roll:
running = False
else:
# ...
if answer.lower() in ('n', 'no'):
running = False
# ...
Return from a function:
def game():
while True:
# ...
if roll == first_roll:
return
# ...
if answer.lower() in ('n', 'no'):
return
# ...
Raise an exception:
class GameExit(Exception):
pass
try:
while True:
# ...
if roll == first_roll:
raise GameExit()
# ...
if answer.lower() in ('n', 'no'):
raise GameExit()
# ...
except GameExit:
# exited the loop
pass
You could use a variable that you will set to false if you want to exit the loop.
cont = True
while cont:
roll = ...
if roll == first_roll:
cont = False
else:
answer = input(...)
cont = (answer == 'Y')
Get some bonus points and attention, use a generator function.
from random import randint
def get_a_roll():
return randint(1, 13)
def roll_generator(previous_roll, current_roll):
if previous_roll == current_roll:
yield False
yield True
previous_roll = None
current_roll = get_a_roll()
while next(roll_generator(previous_roll, current_roll)):
previous_roll = current_roll
current_roll = get_a_roll()
print('Previous roll: ' + str(previous_roll))
print('Current roll: ' + str(current_roll))
print('Finished')
Is continue allowed? It's probably too similar to break (both are a type of controlled goto, where continue returns to the top of the loop instead of exiting it), but here's a way to use it:
while answer == 'Y':
roll = get_a_roll()
display_die(roll)
if roll == first_roll:
print("You lost!")
answer = 'N'
continue
...
If when you lose, answer is hard-coded to "N" so that when you return to the top to re-evaluate the condition, it is false and the loop terminates.
import random
# Select highest score
def highest_score(list_of_scores):
m_score = 0
m_user = 1
for user in list_of_scores:
if m_score <= list_of_scores.get(user):
m_score = list_of_scores.get(user)
m_user = user
return m_score, m_user
# -----------------------------------------------------------------------------------------------------------------------------------------------
# Get the dice value
def dice_value():
d1 = random.randint(1, 6)
return d1
# -------------------------------------------------------------------------------------------------------------------------------------------------
# Prints the game instructions such as opening message and the game rules
print(
"\n**************************************************************************************************************\n")
print(" Welcome To OVER 12!\n")
print(" << GAME RULES >> ")
print(
"______________________________________________________________________________________________________________\n")
print(" <<< Each player rolls a single dice and can choose to roll again (and again) if they choose")
print(" <<< Their total is the sum of all their rolls")
print(" <<< The target is 12, if they go over twelve they score zero")
print(" <<< Once a player decides to stay the next player takes their turn")
print(" <<< DO FOLLOW THE INSRUCTIONS PROPERLY (Use ONLY Yes/No) ")
print(
"______________________________________________________________________________________________________________\n")
# ---------------------------------------------------------------------------------------------------------------------------------------------------
game_over = True
player_score = {}
game_started = False
while game_over:
exit_game = input('Exit The Game (Yes/No)? ')
# The Player Can Either Start The Game Saying Yes or Exit The Game Without Starting By Saying No
if exit_game == 'Yes':
game_over = False
else:
game_started = True
no_of_players = int(input('\n<< How Many Players Are Playing ? '))
for player in range(1, no_of_players + 1):
print(f'\n Now playing player {player}')
continue_same_player = True
# If The Same Player Needs To Play
total_score = 0
while continue_same_player:
d2 = dice_value()
total_score = total_score + d2
if total_score >= 12:
print('\nSorry..!, Your Total Score Is OVER 12, You Get ZERO!!')
total_score = 0
print(f'\n Dice Turned Value Is: {d2}')
print(f' Your Total Score is: {total_score}')
same_player = input('\n<< Continue With The Same Player (Yes/No)? ')
if same_player == 'No':
# If The Player Needs To Be Changed
player_score[player] = total_score
continue_same_player = False
print(f'\nPlayer {player} Total Score Is {total_score}')
break
# --------------------------------------------------------------------------------------------------------------------------------------------------
if game_started:
u1 = highest_score(player_score)
# Display The Highest User Score
print(f'\n << Highest Score User Is: {u1[1]} ')
# The Most Scored Player Is Being Calculated
print(f'\n << Player Highest Score Is: {u1[0]}')
print(
'\n Good Bye....! \n Thank You For Playing OVER 12.. \n See You Again!!') # Prints The Ending Message For the Players
explanation: you define an end_game function that does what you want at the end then ends the code
#do this
def end_game()
if answer == 'N':
print("You left with $",current_amount)
else:
print("You left with $",current_amount)
exit()
while answer == 'Y':
roll = get_a_roll()
display_die(roll)
if roll == first_roll:
print("You lost!")
end_game()
amount_won = roll
current_amount = amount_earned_this_roll + amount_won
amount_earned_this_rol = current_amoun
print("You won $",amount_won)
print( "You have $",current_amount)
print("")
answer = input("Do you want to go again? (y/n) ").upper()

Categories