How do i properly call this function in python? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm a beginner in python and having some difficulties on how to call a function for a rock, paper and scissor game. The code is as below:
def game:
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")

You need brackets, like this:
def game():
to define a function. And .lower() only returns the string in lower case, it doesn't override.
your = input("Rock, Paper or Scissor? ").lower()

This is how function calls work in Python:
#Defining the function
def myFunction():
print("Hello world")
#Calling the function. Yes, it is this simple.
myFunction()
For creating functions with parameters
def myFuncWithParams(Word):
print("Hello" + Word)
myFuncWithParams("World")
Output:
Hello World
In your case:
def game():
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")
#Calling the method and staring the game
game()

All you have to do to call a function is type its name and include arguments if required.
In your case, what you have to do is
def game:
your = input("Rock, Paper or Scissor? ")
your.lower()
list = ["rock", "paper", "scissor"]
import random
a = random.randint(0, 2)
weapon = list[a]
if your == weapon:
print("You chose " + your + " and I chose " + weapon + " so it's a draw.")
elif your == "rock" and weapon == "paper":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "paper" and weapon == "scissor":
print("You chose " + your + " and I chose " + weapon + " so I won.")
elif your == "scissor" and weapon == "rock":
print("You chose " + your + " and I chose " + weapon + " so I won.")
else:
print("You chose " + your + " and I chose " + weapon + " so you won.")
choice = input("Would you like to play again?(y/n) ")
if choice == "y":
game()
else:
print("Thank you for playing.")
# this is how you call the function
game()

Related

Game Not Functioning Properly

So i tried making a rock paper scissors game but some if statements are not working. code was written in python.
Is there something preventing the if statements ffrom running? or s there another problem
I tried a bunch of little changes but none of them work
code:
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ")
botInput = random.choice(moves)
if userInput == botInput:
print(userInput + " VS " + botInput)
print("DRAW")
if userInput == "paper" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "scissors" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "rock" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "rock" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
if userInput == "paper" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
if userInput == "scissors" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
print("Wanna Rematch?")
decision = input("Yes or No? ")
if decision == "Yes":
pass
elif decision == "No":
break
Here's my solution to this. I cleaned up the amount of if-else statements in your code as well with a variable outcome_map. I also removed a lot of the typing rarities that come with inputs by introducing your choice to be "(1, 2, or 3)":
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("Rock, paper, scissors. Go! ")
user_input = int(input("Choose your move (1:rock, 2:paper, 3:scissors): "))
if user_input not in [1, 2, 3]:
print("Invalid input. Try again...")
continue
bot_move = random.choice(moves)
user_move = moves[user_input-1]
outcome_map = { # item A vs item B -> Outcome for A
"rock":{
"rock":"Draw",
"paper":"Lose",
"scissors":"Win",
},
"paper":{
"rock":"Win",
"paper":"Draw",
"scissors":"Lose",
},
"scissors":{
"rock":"Lose",
"paper":"Win",
"scissors":"Draw",
}
}
outcome = outcome_map[user_move][bot_move]
print("Player: ", outcome, "!")
decision = input("Wanna Rematch? (y/n) ")
if decision in ["y", "yes", "Y", "YES"]:
pass
else:
print("Exiting... ")
break
Hope this helps!
I think there's nothing wrong with your code... however, it does not handle specific inputs, maybe that is your problem, here is my solution:
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ").lower()
botInput = random.choice(moves)
#check if input is valid
if userInput not in moves:
print("Choose a valid move! Wanna try again?")
decision = input("Yes or No? ").lower()
if decision == "yes" or decision == 'y': continue
# skips the remaining body of the loop
else: break
elif userInput == botInput:
print(userInput + " VS " + botInput)
print("DRAW")
elif userInput == "paper" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "scissors" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "rock" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "rock" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif userInput == "paper" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif userInput == "scissors" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
print("Wanna Rematch?")
decision = input("Yes or No? ").lower()
if decision == "yes" or decision == 'y': continue
else: break
I hope you understand what I did here:
moves = ('rock', 'paper', 'scissors')
decision = "Nothing"
while decision != "No":
decision = "Nothing"
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ")
botInput = random.choice(moves)
if userInput == "paper":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("DRAW")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
else:
print("Invalid choice.")
if userInput == "scissors":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("DRAW")
if userInput == "rock":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("DRAW")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
while decision != "Yes" and decision != "No":
print("Wanna Rematch?")
decision = input("Yes or No? ")
if decision == "Yes":
pass
elif decision == "No":
break
else:
print("Invalid answer.")

User/Player Health is not saved during attack simulation using a coin and random

I am a novice to python. My longterm project is to design a choose your own adventure text-based game.
A major component of this game is attack scenarios. With that in mind, I have been constructing a python program for simulating an attack scenario. In this case, by flipping a coin to first determine whether the player or the enemy attacks first. Afterwards, a random integer between 1 and 10 is used as the attack damage. A function (HealthCheck), checks the health of the player/enemy to determine whether the player/enemy is dead.
My main problem is that the enemy's and player's health restarts after an attack. How can my program save the user's health after an attack, instead of resetting to 10 HP?
Below is my python code. Thank you for your help.
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack(enemyHealth):
attack_damage = random.randint(1, 10)
print("The player does " + str(attack_damage) + " damage points to
the enemy.")
enemyHealth -= attack_damage
print("The enemy has " + str(enemyHealth) + " HP left!")
enemyHealthCheck(enemyHealth)
pass
def enemyAttack(playerHealth):
attack_damage = random.randint(1, 10)
print("The enemy does " + str(attack_damage) + " damage points to
the player.")
playerHealth -= attack_damage
print("The player has " + str(playerHealth) + " HP left!")
playerHealthCheck(playerHealth)
pass
def turnChoice():
h = 1
t = 2
coin = ""
while coin != "h" and coin != "t":
coin = input("Player, flip a coin to decide who attack first.\n"
"Heads or tails? H for heads. T for tails.\n")
if coin == "h":
print("You chose heads.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
else:
print("You chose tails.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
choice = random.randint(1, 2)
if choice == coin:
print("Great choice. You go first.")
playerAttack(enemyHealth)
else:
print("Enemy goes first.")
enemyAttack(playerHealth)
def replay():
playAgain = ""
while playAgain != "y" and playAgain != "n":
playAgain = input("Do you want to play again? yes or no")
if playAgain == "y":
print("You chose to play again.")
print(".")
print(".")
print(".")
time.sleep(2)
turnChoice()
else:
print("Game over. See you soon.")
sys.exit()
def playerHealthCheck(playerHealth):
if playerHealth <=0:
print("Player is dead. Game over.")
replay()
else:
print("The player has " + str(playerHealth) + " HP points!")
print("It is your turn to attack.")
playerAttack(enemyHealth)
def enemyHealthCheck(enemyHealth):
if enemyHealth <=0:
print("Enemy is dead. You win.")
replay()
else:
print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.")
print("It is their turn to attack.")
enemyAttack(playerHealth)
turnChoice()
To make the code edit the variables you need to use globals. When you call the variable with the parentheses in the function they are only edited in the scope of that variable, but when you use globals they get edited for the whole program. Here is an example. Below is the code that is using globals:
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack():
global enemyHealth
attack_damage = random.randint(1, 10)
print("The player does " + str(attack_damage) + " damage points to the enemy.")
enemyHealth -= attack_damage
print("The enemy has " + str(enemyHealth) + " HP left!")
enemyHealthCheck()
pass
def enemyAttack():
global playerHealth
attack_damage = random.randint(1, 10)
print("The enemy does " + str(attack_damage) + " damage points to the player.")
playerHealth -= attack_damage
print("The player has " + str(playerHealth) + " HP left!")
playerHealthCheck()
pass
def turnChoice():
h = 1
t = 2
coin = ""
while coin != "h" and coin != "t":
coin = input("Player, flip a coin to decide who attack first.\n"
"Heads or tails? H for heads. T for tails.\n")
if coin == "h":
print("You chose heads.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
else:
print("You chose tails.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
choice = random.randint(1, 2)
if choice == coin:
print("Great choice. You go first.")
playerAttack()
else:
print("Enemy goes first.")
enemyAttack()
def replay():
playAgain = ""
while playAgain != "y" and playAgain != "n":
playAgain = input("Do you want to play again? yes or no")
if playAgain == "y":
print("You chose to play again.")
print(".")
print(".")
print(".")
time.sleep(2)
turnChoice()
else:
print("Game over. See you soon.")
sys.exit()
def playerHealthCheck():
global playerHealth
if playerHealth <= 0:
print("Player is dead. Game over.")
replay()
else:
print("The player has " + str(playerHealth) + " HP points!")
print("It is your turn to attack.")
playerAttack()
def enemyHealthCheck():
global enemyHealth
if enemyHealth <= 0:
print("Enemy is dead. You win.")
replay()
else:
print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.")
print("It is their turn to attack.")
enemyAttack()
turnChoice()

Making a leaderboard which resorts itself everytime someone plays

I am learning python coming from C++ and HTML, after studying I decided a good way to exercise was making a simple game then slowly developing. I made it this far, but got stuck on a few things: 1. storing the "player" class and its atributes in a txt file 2. adding the new players everytime someone else with a different name plays 3. sorting the list everytime someone new is added 4. displaying the list when a keyword is input from the keyboard ( split it in small steps as i always do when coding. )
Please help and explain the steps, here is the base code:
input('Welcome to rock, paper, scissors version 1.3!(contact me for updates) Press any key to continue.')
w = 0
l = 0
t = 0
class player:
def __init__(self, name, wins, losses, ties):
self.name = name
self.wins = wins
self.losses = losses
self.ties = ties
def func1():
global w, l, t
x=input('Choose: rock, paper or scissors?')
from numpy import random
y = (random.randint(1, 3))
if (x == "scissors") or (x == "rock") or (x == "paper"):
if y == 1:
y = "scissors"
if y == 2:
y = "rock"
if y == 3:
y = "paper"
else: print("Error: you did not type your answer correctly: check so it is lowercase and spells the word correctly(as described in the question) and try again.")
if x == "rock" :
if y == "paper" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y == "rock" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
if x == "paper" :
if y == "scissors" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y=="paper" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
if x == "scissors" :
if y == "rock" :
print("computer chose " + y + " so you lost!")
l = l + 1
else:
if y == "scissors" :
print("computer chose " + y + " so it is a tie!")
t = t + 1
else:
print("computer chose " + y + " so you win!")
w = w + 1
n=input('Play again?(y/n)')
if n == "y":
n = 0
func1()
if n == "n":
print("You won " + str(w) + " times, lost " + str(l) + " times and it was a tie " + str(t) + " times.")
p1 = player(input("Please type your name:"),w,l,t)
input('Thanks for playing! Press any key to exit.')
func1()

Python SyntaxError: invalid syntax [elif my_move == 'rock']

I'm developing a rock paper scissors on python and I'm getting this syntax error
any help is appreciated
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
self.my_move = my_move
self.their_move = their_movee here
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = input("Pick something!\n")
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
my_score = 0
computer_score = 0
if beats(move1, move2):
my_score = my_score + 1
print ("You win")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
elif beats(move2,move1):
computer_score = computer_score + 1
print ("Computer wins")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
else:
print ("Draw")
print ("Human score = " + str(my_score) + " " + "Computer score = " + str(computer_score) )
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print("Game over!")
class cycleplayer(Player):
def move(self):
if round == 0 :
return 'rock'
elif self.my_move == 'rock'
return "paper"
elif self.my_move == 'paper'
return "scissors"
else self.my_move == 'scissors'
return "rock"
on the cycleplayer subclass I want the program to take the previous move and use it in the current round
I get an error on the first elif in the subclass cycleplayer
the error points on "rock"
invalid syntax ()
In addition to the missing colons after your elif's and the disallowed condition following else, this might have an issue because of the white space. Be sure to indent the member functions within your classes!

Way to keep track of rounds during a while loop

So I'm trying to keep track of what is played in a round by each player and who wins each round in my R/P/S program. Is there a way to do that in a, possibly, infinitely repeating loop? Here's the code
import random
Round = 0
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 and Computer_Score < 5:
Player_object = input("Would you like to choose R, P, or S?")
Computer_object = random.sample("RPS", 1)[0]
if Player_object == "R" or Player_object == "r":
if Computer_object == "R":
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
elif Computer_object == "P":
Computer_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
else:
Player_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")
if Player_object == "P" or Player_object == "p":
if str(Computer_object) == "R":
Player_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")
elif str(Computer_object) == "P":
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have tied with the Computer and neither of you have scored a point.")
else:
Computer_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")
if Player_object == "S" or Player_object == "s":
if str(Computer_object) == "R":
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")
elif str(Computer_object) == "P":
Computer_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have beaten the Computer and you have scored a point.")
else:
Player_Score += 1
print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
if Computer_Score == 5 and Player_Score != 5:
print("The Computer has won!")
if Player_Score == 5 and Computer_Score != 5:
print("You have won and beaten the computer")
R = "Rock"
r = "Rock"
P = "Paper"
p = "Paper"
S = "Scissors"
s = "Scissors"
The simplest way to handle something like this is to use a list where you would store the information you want in each round.
Before your loop, create an empty list
Rounds = []
and at the end of your loop, append the relevant information.
You can use a tuple to add multiple pieces of information as a single entry in the list. For example, to add what is played by each player, you could write
Rounds.append((Player_object, Computer_object))
If you want to keep track of who won the round, add this information in a variable in your if/else and add it to the tuple.
Once your loop is over, you can access the information of each round by accessing this list. List indexes start at 0, so to access the information of the first round, you would write Rounds[0]. Each element in a tuple can also be accessed by index, so the Player_object of round 1 can be accessed using Rounds[0][0].
If you need more information, try to search for lists and tuples in Python.
For each round, you want to store two things, right? The players and their moves, and their winner. In a round, a player moves only once, so we would want a tuple of (player, move) in our data structure. There could be many players participating in one round, so using a list would be most suitable. Therefore in each round, you can have a list of tuples of (player, move).
Since with each round, you want to keep track of the winner also, you can make a tuple to represent a round: ([list of players and moves], winner).
Finally, you want a list of these! Define this list outside the game loop, but append the data of a round at the end of each loop to this list. H
Hope this helps :)
infinity loop......here you go
import random
Round = {}
while True:
cnt = 1
ans = raw_input("Wanna Play RPS (y/n) ? ")
if ans == 'y' or ans == 'Y':
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 and Computer_Score < 5:
Player_object = raw_input("Would you like to choose R, P, or S? ")
Computer_object = random.sample("RPS", 1)[0]
if Player_object == "R" or Player_object == "r":
if Computer_object == "R":
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have tied with the Computer and neither of you have scored a point.")
elif Computer_object == "P":
Computer_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ". You have been beaten by the Computer and it has scored a point.")
else:
Player_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have beaten the Computer and you have scored a point.")
if Player_object == "P" or Player_object == "p":
if str(Computer_object) == "R":
Player_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have beaten the Computer and you have scored a point.")
elif str(Computer_object) == "P":
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ". You have tied with the Computer and neither of you have scored a point.")
else:
Computer_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have been beaten by the Computer and it has scored a point.")
if Player_object == "S" or Player_object == "s":
if str(Computer_object) == "R":
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have been beaten by the Computer and it has scored a point.")
elif str(Computer_object) == "P":
Computer_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ". You have beaten the Computer and you have scored a point.")
else:
Player_Score += 1
print("You have chosen " + Player_object + " and the Computer chose " + str(
Computer_object) + ".You have tied with the Computer and neither of you have scored a point.")
if Computer_Score == 5 and Player_Score != 5:
Round[cnt] = "Computer"
print("The Computer has won!")
elif Player_Score == 5 and Computer_Score != 5:
Round[cnt] = "Player"
print("You have won and beaten the computer")
else:
break
cnt += 1
R = "Rock"
r = "Rock"
P = "Paper"
p = "Paper"
S = "Scissors"
s = "Scissors"
for i in Round:
print "Round ", i, "won by ", Round[i], "\n"

Categories

Resources