Python -- 3 dices game question by using while loop - python

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

Related

How to get function to loop properly?

I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.
import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
money = money + 250000
else:
print("you lose")
money = money - 250000
print ("your balance is",money)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
game()
if replay == "n":
sys.exit("goodbye")
This is the output:
do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
you need to call game() at the end of the code once more.
import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
fact=1
else:
print("you lose")
fact=-1
print ("your balance is",money+fact*step)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
print("welcome again")
game()
if replay == "n":
sys.exit("goodbye")
game()
Add this up in your game function:
global money, flip

Boolean does not control while loop for me

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.

Returning Value from Function to Variable

So I'm currently having some trouble with working out how to basically create a "count" function work within my Rock, Paper, Scissors game. I'm new to Python and this is my first foray into the use of multiple functions to execute game logic. Here's my code...
import random
from random import choice
cpu_score = 0
player_score = 0
# dictionary from which gestures are pulled
gestures = ["rock","paper","scissors"]
n_rounds = int(input("How many rounds would you like to play? "))
while n_rounds % 2 == 0 or n_rounds <= -1:
print("Number of rounds must be an odd number! Select an odd number!")
n_rounds = input("How many rounds?")
break
print("Lets play",n_rounds,"rounds!")
rounds_to_win = ((n_rounds + 1)//2)
rounds_to_win = round(rounds_to_win)
print("You must win",rounds_to_win,"rounds to beat the game!")
def computer_choice():
"""Movement made by the computer"""
comp = random.choice(gestures)
return comp
def player_gesture():
"""Movement by player"""
player = input("Please select, rock, paper or scissors")
if player not in gestures:
print("That's not an option! Please try again.")
player = input("Please select, rock, paper or scissors")
return player
def who_won_round(comp, player):
'''Who is the winner of the round.'''
winner = 0
if ((player == "rock") and (comp == "paper")) or \
((player == "paper") and (comp == "scissors")) or \
((player == "scissors") and (comp == "rock")):
winner = 1
elif ((comp == "rock") and (player == "paper")) or \
((comp == "paper") and (player == "scissors")) or \
((comp == "scissors") and (player == "rock")):
winner = 2
else:
winner = 0
return winner
def win_counter(winner, cpu_score,player_score):
rounds = 1
if winner == 1:
player_score += 1
print("This is round",rounds)
rounds += 1
return player_score
if winner == 2:
cpu_score += 1
print("This is round",rounds)
rounds += 1
return cpu_score
def count_round(winner, player, comp, cpu_score, player_score):
if winner == 0:
print("It's a tie!")
elif winner == 1:
print("The player chose",player)
print("The computer chose",comp)
print("The computer won the round!")
print("The computer has won",cpu_score,"rounds!")
elif winner == 2:
print("The player chose",player)
print("The computer chose",comp)
print("The player won the round!")
print("The player has won",player_score,"rounds!")
def game_structure():
while rounds_to_win < n_rounds:
comp = computer_choice()
player = player_gesture()
winner = who_won_round(comp,player)
win_count = win_counter(winner, cpu_score,player_score)
count = count_round(winner, player, comp, cpu_score, player_score)
game_structure()
Basically I'm having issues returning the variables in order to keep count of the scores of the "number of rounds" and "cpu_score" and "player_score". I prefer to not declare global variables as I realise they can be messy to use, but I'm not quite sure how to avoid this.
If you must avoid the use of global variables, you should take an object oriented approach. That way you can store the variables in the object.
So basically you do something like this:
newgame = mytictactoe()
while True #infinite loop
input("wanna play?")
if input == yes:
newgame.start
else:
break
From what I see, the cpu_score and player_score are never updated. You only have the newest result in win_count, that is not assigned to cpu_score or player_score at anytime. It could be something like:
win_count = win_counter(winner, cpu_score,player_score)
if winner == 1:
cpu_score = win_count
if winner == 2:
player_score = win_count
rounds_to_win = max(player_score, cpu_score)
count_round(winner, player, comp, cpu_score, player_score)
I did not run it, but this modifications should do the trick. There are better ways of doing it; maybe using a list to keep the scores and use winner as the index, or an object approach as someone else said, but I do not want to change too much the code.
Also, bear in mind that the round variable in win_counter does nothing.

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"

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

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):
...

Categories