Python not detecting when a variable is equal to another variable - python

I am making a program for my family for keeping ping pong scores. When the score limit is reached, it should end the game and say who won. This works for one player but not the other, and I can't figure out why. When P2's score reaches 11, it says that P2 wins and restarts, but when P1's score reaches 11, it just keeps on going. Please keep in mind that I am new to this. Here is the code:
import sys
def defaults():
global p1sc
global p2sc
global p1adv
global p2adv
global p1name
global p2name
global sclimit
p1sc = 0
p2sc = 0
p1adv = 0
p2adv = 0
p1name = "Player 1"
p2name = "Player 2"
sclimit = 11
def checkwin():
global p1sc
global p2sc
global p1name
global p2name
global sclimit
if p2sc < sclimit:
program()
if p1sc < sclimit:
program()
if p2sc <= sclimit:
print(p2name + " wins!")
defaults()
print("New game!")
program()
if p1sc <= sclimit:
print(p1name + " wins!")
defaults()
print("New game!")
program()
elif p1sc == sclimit - 1 and p2sc == sclimit - 1:
print("Sudden Death!")
suddendeath()
else:
print("DEBUG: CHECKWIN FAILED")
def displayscore():
global p1name
global p2name
global p1sc
global p2sc
print(p1name + ": " + str(p1sc))
print(p2name + ": " + str(p2sc))
def program():
global p1sc
global p2sc
global p1name
global p2name
global sclimit
cmdinput = str(raw_input("Command: "))
if cmdinput == "1":
p1sc = p1sc + 1
displayscore()
checkwin()
elif cmdinput == "2":
p2sc = p2sc + 1
displayscore()
checkwin()
elif cmdinput == "q":
p1sc = p1sc - 1
displayscore()
checkwin()
elif cmdinput == "w":
p2sc = p2sc - 1
displayscore()
checkwin()
elif cmdinput == "name":
p1name = str(raw_input("Player 1 name: "))
print("Player 1 name has been set to " + p1name)
p2name = str(raw_input("Player 2 name: "))
print("Player 2 name has been set to " + p2name)
program()
elif cmdinput == "limit":
sclimit = raw_input("Score limit: ")
print("Score limit has been set to " + str(sclimit))
program()
elif cmdinput == "exit":
sys.exit()
else:
print("Command not recognised")
program()
def suddendeath():
global p1name
global p2name
global p1adv
global p2adv
cmdinput = str(raw_input("Command: "))
if cmdinput == "1":
if p2adv == 0:
p1adv = 1
elif p2adv == 1:
p2adv = 0
elif p1adv == 1:
print(p1name + " wins!")
defaults()
print("New game!")
program()
elif cmdinput == "2":
if p1adv == 0:
p2adv = 1
elif p1adv == 1:
p1adv = 0
elif p2adv == 1:
print(p2name + " wins!")
defaults()
print("New game!")
program()
defaults()
program()

Your progam has some problems with the conditions, this should work now:
def checkwin():
...
#call program only if both player's score is less than the limit
if p2sc < sclimit and p1sc < sclimit:
program()
#use if-elif conditions here, and you need `>=` here not `<=`.
if p2sc >= sclimit:
print(p2name + " wins!")
defaults()
print("New game!")
program()
elif p1sc >= sclimit:
print(p1name + " wins!")
defaults()
print("New game!")
program()
...
Demo:(Changed sclimit to 3)
$ python so.py
Command: 1
Player 1: 1
Player 2: 0
Command: 1
Player 1: 2
Player 2: 0
Command: 2
Player 1: 2
Player 2: 1
Command: 1
Player 1: 3
Player 2: 1
Player 1 wins!
New game!
Command: 1
Player 1: 1
Player 2: 0
Command: 2
Player 1: 1
Player 2: 1
Command: 2
Player 1: 1
Player 2: 2
Command: 2
Player 1: 1
Player 2: 3
Player 2 wins!
New game!
Command:

Related

Doesn't run IF statement even though condition is true, but loops other IF

import random
player_health = 100
boss_health = 80
guard1_health = 10
guard1_status = "alive"
guard2_health = 15
gladiator_health = 20
weapon = 0
level = 0
turn = 0
def choose_weapon():
global weapon
global level
weapon = int(input("Choose your weapon:\n 1: Sword \n 2: Daggers \n 3: Bow \n Type here to choose:"
"\n--------------------------"))
if weapon == 1:
weapon = str("Sword")
print("You have chosen", weapon)
elif weapon == 2:
weapon = str("Daggers")
print("You have chosen", weapon)
else:
weapon = str("Bow")
print("You have chosen", weapon)
level += 1
choose_weapon()
def level_1_enemy():
global guard1_status
global guard1_health
global level
global turn
global weapon
print("Player turn")
if guard1_status == "alive" and guard1_health > 0 and turn == 1:
print("test")
if weapon == 1:
guard1_health -= 8
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 2:
guard1_health -= 5
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 3:
bow_crit = random.randint(1, 10)
if bow_crit == 1:
guard1_health -= 20
print("Guard health:", guard1_health)
else:
guard1_health -= 5
print("Guard health:", guard1_health)
if guard1_health <= 0:
print("You defeated the Guard, next level!")
guard1_status = "dead"
level += 1
return
def level_1_player():
global player_health
global weapon
global level
global turn
if player_health > 0 and turn == 0:
if weapon == 2:
dodge = random.randint(1, 3)
if dodge == 1:
print("You dodged the attack!")
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
print("You have died, Game Over.")
return
while level == 1:
if turn == 0:
level_1_player()
turn += 1
elif turn == 1:
level_1_enemy()
turn -= 1
I want to have the game loop through player and enemy turns until either the player is dead or the enemy. It reaches the first IF in level_1_enemy and prints "test", but does not continue to the next if statement even though the condition "weapon == 1" is true.
The last while loop is meant to repeat the level_1_enemy and level_1_player functions. It does do both but will also not stop looping once the guard or player is dead.

Why does choosemove() allow you to hit endlessly and not run lose() when the total value is greater then 21?

Is the code generating a new card every time choosemove() and then creating a new card again and adding on top if you hit again like its supposed to?
Basically, I need lose() to run when newtotalplayercardvalue > 21 so it shows the player lost, but it just lets you "hit" endlessly for some reason. Thanks in advance!
import random
def win():
print ("")
print("You won!")
menu()
def lose():
print ("")
print("You lost!")
menu()
def numbertocard(card):
if card == 11:
card = "J"
elif card == 12:
card = "Q"
elif card == 13:
card = "K"
elif card == 14:
card = "A"
else:
card = card
return card
def cardtonumber(cardvalue):
if cardvalue == "J":
cardvalue == 10
elif cardvalue == "Q":
cardvalue == 10
elif cardvalue == "K":
cardvalue = 10
elif cardvalue == "A":
cardvalue = 11
else: cardvalue = cardvalue
return (cardvalue)
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
newtotalplayercardvalue = newcard + totalplayercardvalue
if newtotalplayercardvalue > 21:
lose()
else:
choosemove()
def stand():
global totalplayercardvalue
global totaldealercardvalue
global dealercard2
print(f"The dealer's second card is a {dealercard2}")
if totalplayercardvalue > totaldealercardvalue:
win()
elif totaldealercardvalue > totalplayercardvalue:
lose()
def choosemove():
print("")
choice = input("Would you like to hit or stand? \n")
if choice == "hit":
hit()
elif choice == "stand":
stand()
else:
print("""Please only enter "hit" or "stand" """)
choosemove()
def startgame():
global totalplayercardvalue
global totaldealercardvalue
playercard1 = random.randint(1,14)
p_card1_name = numbertocard(playercard1)
print(f"Your first card is {p_card1_name}")
print("")
playercard2 = random.randint(1,14)
p_card2_name = numbertocard(playercard2)
print(f"Your second card is {p_card2_name}")
print("")
dealercard1 = random.randint(1,14)
d_card1_name = numbertocard(dealercard1)
dealercard2 = random.randint(1,14)
totalplayercardvalue = playercard2 + playercard2
totaldealercardvalue = dealercard1 + dealercard2
if totalplayercardvalue == 21 and totaldealercardvalue == 21:
tie()
elif totalplayercardvalue == 21:
win()
elif totaldealercardvalue == 21:
lose()
else:
print(f"The dealer's first card is a {d_card1_name}")
choosemove()
def menu():
play_game = input("Would you like to start a round? y/n: \n")
if play_game == "y":
startgame()
else:
print("""Say "y" """ )
menu()
menu()
First things first, your program isnt well formatted, there is no seperation between the way that global variables and local variables are defined. It's standard practice to define global variables in Uppercase. Will make life easier for you.
As to what the endless hitting is, you aren't updating the totalplayercard variable in hit. You just define newtotalplayercardvalue, check if that is greater than 21 else choosing move, it doesn't update the global variable instead try
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
totalplayercardvalue += newcard
if totalplayercardvalue > 21:
lose()
else:
choosemove()
IDK how black jack works however this is the reason that I can see

How to Show scores/ save Game/ load game 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()

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"

Rock, paper, scissors game. Writing a print statement that works

Here is my code:
from random import*
from myro import*
from math import*
def computerChoice():
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
return choice
def userGuess():
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
userNameWins = 0
computerWins = 0
draws = 0
if(userChoice == "R" and choice == "paper"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
speak( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
speak("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
speak("you win")
userNameWins = userNameWins + 1
else:
speak("Draw")
draws = draws + 1
return userNameWins, computerWins, draws
def printResults(userNameWins, computerWins, draws)
# insert code for print statement
def main():
for x in range (5):
speak("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults (userNameWins, computerWins, draws)
I get an error when I try to define some variables and I don't know why.
I need a function that properly prints the results returned by calculate()
The part you're asking for is trivial. Since you didn't give us the desired output format, I'll guess at it, and hopefully you can fix it to match the way you want it to look:
def printResults(userNameWins, computerWins, draws)
print('user won {} times, computer won {} times, and players drew {} times'
.format(userNameWins, computerWins, draws))
However, your code isn't going to work, for at least two reasons.
First, you call this:
calculate(userChoice,choice)
… which returns the 3 values you want, but you never store them anywhere. In particular, you don't store them, or anything else, in variables named userNameWins, computerWins, and draws. So, this like will get a NameError:
printResults (userNameWins, computerWins, draws)
Second, you're looping 5 times over a function that, each time, returns a full set of values, but you're only calling printResults once, not 5 times. I'm not sure what you're intending here, but most likely, either you need to move printResults into the loop, or you need to add code that sums up the results across all the loops.
sorry about the wait but hopefully this solution is of help to you.
from random import randint
#from myro import *
choice = None
userChoice = None
userNameWins = 0
computerWins = 0
draws = 0
def computerChoice():
global choice
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
print "Scribbler selected " + choice
return choice
def userGuess():
global userChoice
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
global userNameWins
global computerWins
global draws
if(userChoice == "R" and choice == "paper"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
print( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
print("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
print("you win")
userNameWins = userNameWins + 1
else:
print("Draw")
draws = draws + 1
def printResults():
print "You won " + str(userNameWins) + " times"
print "Scribbler won " + str(computerWins) + " times"
print "There were " + str(draws) + " draws"
if (userNameWins > computerWins):
print "You win overall"
elif (userNameWins < computerWins):
print "Scribbler wins overall"
else:
print "It was a dead heat"
def main():
global userChoice
global choice
for x in range (5):
print ("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults ()
main()
I didn't have myro installed so I used print instead to display the results. Before you weren't saving the variables for the results anywhere so I made a global variable so that it can store the variables. Also I completed the printResults function.

Categories