How to Show scores/ save Game/ load game Python? - python

I am struggling with this code, I have my menu working to make the game run and to collect scores up to 18 for each player. But I think I have gotten lost in my code and I am frustrated beyond belief.
I need to have the Player scores loaded to a list that can be saved (save game), displayed(show scores) and list current winner, and then load (load game)
Player_1 = []
Player_2 = []
def main():
choice = 0
while choice != 6 :
print("1: New Game")
print("2: Play Round")
print("3: Show Scores")
print("4: Save Game")
print("5: Load Game")
print("6: Exit Game")
choice = input ("Option Select: ")
if choice == "1":
print("New Game // Reset Game")
ResetGame()
elif choice == "2":
print("Play Play Round")
PlayRound()
elif choice == "3":
print("Show Scores")
ShowScores()
elif choice == "4":
print("Save Game")
SaveGame()
elif choice == "5":
print("Load Game")
LoadGame()
elif choice == "6":
print("Thanks for playing!")
else:
print("I don't understand your choice.")
def PlayRound():
holes = 0
index = 0
endRound = 0
while holes <= 18 and endRound != 1:
Player_1Score = int(input("Player 1 Stroke: "))
Player_2Score = int(input("Player 2 Stroke: "))
endRound = int(input("Would you like to Continue 0= YES 1= NO"))
if Player_1Score > 5:
Player_1Score = 5
if Player_2Score > 5:
Player_2Score = 5
Player_1.insert (index,Player_1Score)
Player_2.insert (index,Player_2Score)
holes += 1
index += 1
print (Player_1)
print (Player_2)
def ShowScores():
total1 = sum(Player_1)
total2 = sum(Player_2)
if total1 < total2:
print("The Current Winner is Player 1")
elif total1 > total2:
print("The Current Winner is Player 2")
elif total1 == total2:
print("The Players are Tied")
def SaveGame():
with open("score1.txt","w") as P1:
for S1 in Player_1:
P1.writelines(str(S1)+' ')
with open("score2.txt", "w") as P2:
for S2 in Player_2:
P2.writelines(str(S2)+ ' ')
print('Your Scores have been saved.')
def LoadGame():
with open("score1.txt", "r") as P1:
for S1 in Player_1:
P1.split(' ')
print(P1)
with open("score2.txt", "r") as P2:
for S2 in Player_2:
P2.split(' ')
print(P2)
print('Game Loaded')
def ResetGame():
Player_1.clear()
Player_2.clear()
print('Scores():', Player_1, Player_2)
main()

Related

Arrow Simulator Highest score and its holder

from multiprocessing.resource_sharer import stop
import random
import math
play_again = 'y'
while play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('please input your name:')
name = input(str())
if name == 'Quit':
break
print('Your current score:',current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer = str(input())
if answer == 'Quit':
break
while remaining_attempts > 0:
if answer == 'y':
target_location_x = random.uniform(30, 150)
target_location_y = random.uniform(0,15)
print('The target is at location:', target_location_x, ',', target_location_y)
print('Input the arrows initial velocity:')
initial_velocity = float(input())
if initial_velocity == 'Quit':
stop
while initial_velocity <= 0:
print('Error: Only values greater than 0')
initial_velocity = float(input())
if initial_velocity == 'Quit':
break
print('Input the angle the arrow is fired:')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
while arrow_angle >= 90:
print('Error: Only values >=0 and <90')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
X0 = 0
Y0 = 1
g = 9.8
t = 0.5
#to calculate where x and y ends up for the arrow
angle_x = math.cos(arrow_angle)
arrow_x = X0 + ((t*initial_velocity)*angle_x)
angle_y = math.sin(arrow_angle)
arrow_y = Y0 + ((t*initial_velocity)*angle_y)-(((1/2)*g)*(t**2))
#to get the distance from the bullseye
def distance_bullseye (arrow_x, arrow_y):
distance_bullseye = ((arrow_x-target_location_x)**2)+((arrow_y-target_location_y)**2)
distance_centre = math.sqrt(distance_bullseye)
return distance_centre
distance_centre = distance_bullseye(arrow_x, arrow_y)
print('Arrow ends up at:',arrow_x,',',arrow_y)
if distance_centre > 10:
print('You missed! Distance from centre', distance_centre)
current_score = current_score
remaining_attempts = remaining_attempts - 1
print('Your current score:', current_score)
if remaining_attempts == 0:
current_score
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('Please input your name:')
name = str(input())
elif play_again == 'Quit' or 'n':
stop
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 10 >= distance_centre > 5:
print('You hit the outer ring!')
current_score = current_score+50
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 5 >= distance_centre > 1:
print('You hit the inner ring!')
current_score = current_score+200
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 1 >= distance_centre >= 0:
print('You hit the bullseye!')
current_score = current_score +500
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
#don't know how to get highest score holder or highest score
elif answer == 'n':
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'Quit' or 'n':
stop
else:
print('Input y or n')
answer = str(input())
if answer == 'Quit':
break
Tried making a list but couldn't get the one variable to stay the same through the code loops it keeps resetting to the new name and new score. is there any way I could keep the highest score and its holder throughout the loops?
it should keep the name from the start if that name has the highest score and the program runs again and that player has a lower score should print the first name and first score, if it's higher it should print the second name with the second score.

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

New to python and having problems with whiles and ifs

My Problem(s):
The problem now is that whenever I enter a number of times to play, it just ignores it and plays forever. It is also not updating the score even though I have global variables and I am adding to them every time there is a win or loss.
Also, I do not want to ask the player(s) for their names every time they play (only when using the "out of a certain number of points function of the game). Any suggestions/help would be greatly appreciated!
My code is below for reference:
from random import randint
import sys
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
bestOutOf = int(input("Best out of: (Enter a number 1-10) "))
player1score = 0
player2score = 0
computerscore = 0
class PlayWithFriend:
def __init__(self, player1, player2, name1, name2, player1score, player2score):
self.player1 = player1
self.player2 = player2
self.name1 = name1
self.name2 = name2
self.player1score = player1score
self.player2score = player2score
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You Win", name2,"!")
print(player2, "covers", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "smashes", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Paper":
if player2 == "Scissors":
print("You Win", name2,"!")
print(player2, "cut", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "covers", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Scissors":
if player2 == "Rock":
print("You Win", name2,"!")
print(player2, "smashes", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "cut", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("That's not a valid play. Check your spelling!")
class PlayWithComputer:
def __init__(self, player, name, player1score, computerscore):
self.player = player
self.player1score = player1score
self.computerscore = computerscore
self.name = name
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0,2)]
if player == computer:
print("Tie!")
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "smashes", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "covers", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "cut", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("That's not a valid play. Check your spelling!")
if dotheywantotplay == "y":
PlayWith = input("Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ")
while PlayWith in ('computer', 'friend', 'exit'):
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
while player1score + player2score < bestOutOf:
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
elif PlayWith == "computer":
player = input('Enter first players name: ')
while player1score + computerscore < bestOutOf:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
elif PlayWith == "exit":
sys.exit()
else:
print("That's not a valid play. Check your spelling!")
else:
print("I am sad now :-(")
sys.exit()
I went over your code and cleaned it up. I made the formatting, variable names, and processes much more pythonic. You will find it is much easier to use python when you use these best practices, so I recommend you at least look over the code and see what I did. For me, I know this would've been helpful when I started learning python.
from random import choice
def get_result(choice1, choice2):
return {
('paper', 'rock'): dict(win='player 1', action='covers'),
('rock', 'paper'): dict(win='player 2', action='covers'),
('rock', 'scissors'): dict(win='player 1', action='smashes'),
('scissors', 'rock'): dict(win='player 2', action='smashes'),
('scissors', 'paper'): dict(win='player 1', action='cuts'),
('paper', 'scissors'): dict(win='player 2', action='cuts'),
}[(choice1, choice2)] # index this dictionary
def main():
print('Lets play a game!')
if input('Do you want to play Rock-Paper-Scissors? (y or n) ') != 'y':
quit()
num_games = int(input('Best out of: (Enter a number 1-10) '))
num_games = max(min(num_games, 10), 1) # clamp num_games between 1-10
while True: # infinite loop, we can break out or quit when we need
inp = input('Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ')
if inp == 'exit':
quit()
play_with_computer = inp == 'computer'
name1 = input('Enter first players name: ')
name2 = 'computer' if play_with_computer else input('Enter second players name: ')
score = {name1: 0, name2: 0}
for game_number in range(num_games):
choice1 = input(f'{name1}... rock, paper or scissors? ')
choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ')
if choice1 == choice2:
print('Tie!')
continue
result = get_result(choice1, choice2)
win_name = name1 if result['win'] == 'player 1' else name2
lose_name = name2 if result['win'] == 'player 1' else name1
score[win_name] += 1
print(f'{win_name} {result["action"]} {lose_name}')
print(f'Game {game_number+1}, the score is {score[name1]} {name1}, {score[name2]} {name2}')
print(name1 if score[name1] > score[name2] else name2, 'wins!')
if __name__ == '__main__': # this just means if the file is run
main()
The main thing I did was get rid of your rock paper scissors logic, (which you repeated twice which is never best practice in programming), and replaced it with a get_result function which returns the winner and action of the moves. I also replaced your if statements that test if the game is against the computer, with a bool play_with_computer. This can be used when getting player 2 name and the second choice, which is all that is really different when playing with a computer. The last thing is your game loop while. Since you never really need to execute any code after this (only reason to exit is to quit), I find it to be cleaner to have an infinite loop while True, and just call quit() if the input is 'exit'.
Okay so the mistake is:
while PlayWith != "computer" or "friend" or "exit":
try this thing:
while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":
And sorry if this does not work
which while loops and if statements are you having trouble with?
Upon first glance, the while statement below will never break the moment a player enters a value besides "computer", "friend" or "exit".
Instead, what you can do is put the process of the game within a function, that is continuously called back when the player enters a value besides the ones aforementioned.
while PlayWith != "computer" or "friend" or "exit":
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
i = 0
while i in range(0, bestOutOf):
if i >= bestOutOf:
sys.exit()
if bestOutOf >= 1 and bestOutOf <= 10:
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i += 1
else:
print("Setting default game to: \"best out of three\"")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i = bestOutOf - 3
if PlayWith == "computer":
i = 0
while i in range(0, bestOutOf - 1):
if i >= bestOutOf:
sys.exit()
else:
player = input('Enter first players name: ')
if bestOutOf >= 1 and bestOutOf <= 10:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
else:
personchoice = input("Rock, Paper, Scissors? ")
print("Setting default game to: \"best out of three\"")
PlayWithComputer(personchoice, player, player1score, computerscore)
if PlayWith == "exit":
sys.exit()
elif PlayWith != "exit" or "computer" or "friend":
print("That's not a valid play. Check your spelling!")

Checking If a File Exists and Loading its Contents

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

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