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()
Related
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I have a y/n query at the end of the game which will restart the game or exit the game.
y and n work as they should, but if I enter any other letter even if it does print the "please try again message", it restarts the game anyway. I thought it should only do that if I put continue, but I haven't
I also want it to recognize y or n as upper case, is there a command in python that allows a letter to be recognized regardless of if its upper or lowercase?
play_again = input('Would you like to play again?(y/n) ')
if play_again == 'y': #loop restarts
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print ("I don't recognize that character, please select y or n")
I have provided the loop as requested, but the last time I did this I got in trouble:
number_of_stones = int(input('Select between 30-50 stones to start your game: ' )) #player1 chooses stones
if number_of_stones >= 30 and number_of_stones <= 50:
print('Starting the game...')
has_winner = False # Winner = False since there no winners (start of game)
while True:
for player in player_list:
if has_winner: # if there is a winner, exit loop
break
# display whose turn is it
print('\n{}\'s turn:'.format(player))
while True:
# if the player is computer use strategy that is mentioned in assignment 2
if player == 'Mr Computer':
remainder = number_of_stones%3
if remainder == 0:
stones_to_remove = 2
else:
stones_to_remove = 1
# if the player is not the computer
else:
stones_to_remove = int(input('Select between 1-3 stones to remove: '))
# assess the number of stones remaining and print the remainder to the screen
if stones_to_remove >= 1 and stones_to_remove <= 3:
number_of_stones -= stones_to_remove
print('Number of stones remaining:',number_of_stones)
if number_of_stones <= 0:
print('The winner is:',player,"!")
has_winner = True
break
else: # show error and let the user input again
print("I'm sorry, that number is outside the range. Please choose a number between 1 and 3")
if has_winner == True: # if the winner=true then exit loop
break
play_again = input('Would you like to play again?(y/n) ').lower() #only accepts lower case letter
if play_again == 'y': #loop restarts
os.system('cls') # clear the console
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print("I'm sorry, that number is outside the range. Please select between 30 and 50 stones.")
You haven't added necessary information ,i.e. rest of the loop , try add that .
For case insensitivity , just use the following
if play_again == "n" || play_again == "N":
.
All of this code does not get affected by a SIGKILL command and my while loop continues no matter what condition
Code:
if Play == False:
signal.SIGKILL(0)
if gameplayint == "N":
print("What are you doing here then?")
Play == False
if gameplayint == "Y":
Play == True
time.sleep(0.5)
print("We will start now.")
#Start the game.
print("")
#Actual gameplay block of code
#game start
while Play == True:
pcNum = random.randint(1,19)
anotherNum = True
total = 0
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
again = input("Try again? <Y or N>")
if again == "Y":
Play = True
else:
Play = False
print("Goodbye now.")
Output:
What's your name? Y
Very well then Y, do you want to play 13? <Y or N> N
What are you doing here then?
Your number is 3.
You have 3 in total.
The issue here is that despite N being outputted on the gameplayint variable, the while loop still continues instead of stopping the output entirely.
I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.
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):
...