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

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!

Related

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()

Why the win_check function is not working properly?

I am new and I have created a tic tac toe game in python I worked out the logic but the code is not behaving as expected I have tried to debug it but can't find the bug.
I am new to python and taking course on udemy in the course I was asked to write a tic tac toe game by myself at first. I have figured out a not so good logic but it will do the job. I just can't figure out why win_check function is not working properly. Is it win_check function or something else? What are some suggestion for improving my code?
Sorry for not giving comments in code I just wanted to complete it first and run it successfully.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 20:11:38 2019
#author: sandeep
"""
from os import name,system
from time import sleep
from random import randint
def game_board(turns):
print(turns[6],"|",turns[7],"|",turns[8])
print("--|---|---")
print(turns[3],"|",turns[4],"|",turns[5])
print("--|---|---")
print(turns[0],"|",turns[1],"|",turns[2])
def check_input(player1,player2):
if (player1 == 'X' or player1 == 'O') and (player2 == 'X' or player2 == 'O'):
return True
else:
print("Please choose between X and O")
global initial_player_value
initial_player_value = take_input()
return False
def take_input():
player1 = input("Do you want 'X' or 'O'?\n")
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
return (player1,player2)
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def player_turn(initial_player_value0,initial_player_value1):
clear()
global turns
game_board(turns)
print(f"Player {initial_player_value0} turn")
print("Enter position")
player1_input =input()
turns.pop(int(player1_input)-1)
turns.insert(int(player1_input)-1,initial_player_value0)
clear()
game_board(turns)
print(f"Player {initial_player_value1} turn")
print("Enter position")
player2_input = input()
turns.pop(int(player2_input)-1)
turns.insert(int(player2_input)-1,initial_player_value1)
clear()
game_board(turns)
def win_check(check,initial_player_value3,initial_player_value4):
# print(check)
global game_status
if initial_player_value3 == 'X':
if ((['X','X','X'] == check[:3]) or (['X','X','X'] == check[3:6]) or (['X','X','X'] == check[6:])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::3]) or (['X','X','X'] == check[1::3]) or (['X','X','X'] == check[2::3])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::4]) or (['X','X','X'] == check[2:7:2])):
game_status = "Player X wins"
else:
game_status = "_"
else:
if ((['O','O','O'] == check[:3]) or (['O','O','O'] == check[3:6]) or (['O','O','O'] == check[6:])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::3]) or (['O','O','O'] == check[1::3]) or (['O','O','O'] == check[2::3])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::4]) or (['O','O','O'] == check[2:7:2])):
game_status = "Player O wins"
else:
game_status = "_"
if initial_player_value4 == 'O':
if ((['O','O','O'] == check[:3]) or (['O','O','O'] == check[3:6]) or (['O','O','O'] == check[6:])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::3]) or (['O','O','O'] == check[1::3]) or (['O','O','O'] == check[2::3])):
game_status = "Player O wins"
elif ((['O','O','O'] == check[::4]) or (['O','O','O'] == check[2:7:2])):
game_status = "Player O wins"
else:
game_status = "_"
else :
if ((['X','X','X'] == check[:3]) or (['X','X','X'] == check[3:6]) or (['X','X','X'] == check[6:])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::3]) or (['X','X','X'] == check[1::3]) or (['X','X','X'] == check[2::3])):
game_status = "Player X wins"
elif ((['X','X','X'] == check[::4]) or (['X','X','X'] == check[2:7:2])):
game_status = "Player X wins"
else:
game_status = "_"
draw_check = ''.join(str(x) for x in check)
print(draw_check)
#sleep(5)
if draw_check.isalpha():
game_status ="Game draws"
else:
game_status= "_"
#def welcome():
print("Welcome to the tic tac toe game\n")
initial_player_value = take_input()
check = check_input(initial_player_value[0],initial_player_value[1])
while check is False:
check = check_input(initial_player_value[0],initial_player_value[1])
print(f"Player 1 is {initial_player_value[0]} and Player 2 is {initial_player_value[1]}\nLet's start the game" )
turns = [1,2,3,4,5,6,7,8,9]
sleep(2)
clear()
game_board(turns)
game_status = '_'
decide_first = randint(1,2)
replay = 'yes'
while replay == "yes":
#global game_status
if decide_first == 1:
player_turn(initial_player_value[0],initial_player_value[1])
game_board(turns)
win_check(turns,initial_player_value[0],initial_player_value[1])
else:
player_turn(initial_player_value[1],initial_player_value[0])
game_board(turns)
win_check(turns,initial_player_value[0],initial_player_value[1])
#win_check(turns,tuple(initial_player_value))
if game_status != '_':
print(game_status)
replay = input("Do you want to play again?\n")
turns = [1,2,3,4,5,6,7,8,9]
No error while running the code.
the problem you're facing is in win_check.
win_check does the following steps:
it checks if the first player wins, and sets the variable game_status to either "Player X wins", or "Player Y wins", or "_"
it checks if the second player wins, and sets the variable game_status to either "Player X wins", or "Player Y wins", or "_"
it checks if the a draw happens and sets the variable game_status to either "game draws" or "_"
after each step it deletes the result of the last step.
It would be more readable and functionally correct if you use a single if en elif chain to manage the control flow.
I would also move the checking whether a player has won to its own function called has_won, this would improve readability and reduce code duplication.
def win_check(board, player_1, player_2):
global game_status
if has_won(board, player_1):
game_status = "Player " + player_1 + " has won"
elif has_won(board, player_2):
game_status = "Player " + player_2 + " has won"
elif is_draw(board):
game_status = "Game draws"
else:
game_status = "_"

Win Count and Loop Help (Python 3)

I found a basic rock-paper-scissors game and wanted to know how to create a score table for it. Also, I'm confused how to make the game last forever until the player wants to end it. Here is the coding for the game:
import random;
wins_history = [0]
ties_history = [0]
losses_history = [0]
def initial_wins():
return wins_history[0]
def cur_wins():
return wins_history[-1]
def affect_wins(delta):
wins_history.append(cur_wins() + delta)
return cur_wins()
def initial_ties():
return ties_history[0]
def cur_ties():
return ties_history[-1]
def affect_ties(delta):
ties_history.append(cur_ties() + delta)
return cur_ties()
def initial_losses():
return losses_history[0]
def cur_losses():
return losses_history[-1]
def affect_losses(delta):
losses_history.append(cur_losses() + delta)
return cur_losses()
while True:
player = input("Enter your choice (rock/paper/scissors): ");
player = player.lower();
while (player != "rock" and player != "paper" and player != "scissors"):
print(player);
player = input("That choice is not valid. Enter your choice (rock/paper/scissors): ");
player = player.lower();
computerInt = random.randint(0,2);
if (computerInt == 0):
computer = "rock";
elif (computerInt == 1):
computer = "paper";
elif (computerInt == 2):
computer = "scissors";
else:
computer = "Huh? Error...";
if (player == computer):
print("Draw!");
affect_ties(+1)
print ("Your new tie score is, cur_ties()")
elif (player == "rock"):
if (computer == "paper"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
elif (player == "paper"):
if (computer == "rock"):
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
else:
print("Computer wins!")
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
elif (player == "scissors"):
if (computer == "rock"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")

Incrementing score in Python CGI

I am having some trouble getting my score's to increment. It works but it keeps resetting to zero after the first "+1" has been done.
user1score = 0
user2score = 0
def main():
if form.has_key('choice'):
myMove = form['choice'].value
cpuM = computerMove()
result = compareMove(myMove, cpuM)
now = datetime.datetime.now()
writeFile(user, result, now)
show(user)
print user
print now.strftime("%Y-%m-%d %H:%M")
print result
else:
show(user)
def computerMove():
cc = ["rock","scissor","paper"]
return random.choice(cc)
def compareMove(myMove, cpuM):
global user1score
global user2score
if myMove == cpuM:
return "Its a tie!"
elif myMove == 'rock':
if cpuM == 'paper':
user2score += 1
return "Paper beats Rock. Computer wins! " + str(user2score)
else:
user1score += 1
return "Rock beats Scissors. You win! " + str(user1score)
elif myMove == 'paper':
if cpuM == 'rock':
user1score += 1
return "Paper beats Rock. You win! " + str(user1score)
else:
user2score += 1
return "Scissors beats paper. Computer wins! " + str(user2score)
elif myMove == 'scissors':
if cpuM == 'rock':
user2score += 1
return "Rock beats scissors. Computer wins " + str(user2score)
else:
user1score += 1
return "Scissors beats paper. You win " + str(user1score)
How can i prevent the score from returning to zero after the score is increased by 1? Everything else is working as intended.
Thank you.
As your script is called every time the user does something, it can't rembember the result of the previous rounds.
Either use some kind of a session(cookie) or add the scores to your form as hidden elements.

Simple Rock Paper Scissors game, problems with returning score?

I'm writing this Rock Paper Scissors program for my Programming class, and having some problems getting the full score to show up at the end of the program. I'm super beginner in Python, so nothing too fancy here. For some reason, as I run the program, the only score that shows up is 1 regardless of how many times the game loops. What am I doing wrong here?
from myro import *
from random import *
def announceGame():
""" Announces the game to the user """
speak("Welcome to Rock, Paper, Scissors. I look forward to playing you.")
def computerMove():
""" Determines a random choice for the computer """
randomNumber = random()
if randomNumber == 1:
compMove = "R"
elif randomNumber == 2:
compMove = "P"
else:
compMove = "S"
return compMove
def userMove():
""" Asks the user to input their choice."""
userChoice = raw_input("Please enter R, P, or S: ")
return userChoice
def playGame(userChoice, compMove):
""" Compares the user's choice to the computer's choice, and decides who wins."""
global userWin
global compWin
global tie
userWin = 0
compWin = 0
tie = 0
if (userChoice == "R" and compMove == "S"):
userWin = userWin + 1
print "You win."
elif (userChoice == "R" and compMove == "P"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "R"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "P"):
userWin = userWin + 1
print "You win"
elif (userChoice == "P" and compMove == "S"):
compWin = compWin + 1
print "I win"
elif (userChoice == "P" and compMove == "R"):
userWin = userWin + 1
print "You win"
else:
tie = tie + 1
print "It's a tie"
return compWin, userWin, tie
def printResults(compWin, userWin, tie):
""" Prints the results at the end of the game. """
print " Rock Paper Scissors Results "
print "------------------------------------"
print "Computer Wins: " + str(compWin)
print "User Wins: " + str(userWin)
print "Ties: " + str(tie)
def main():
announceGame()
for game in range(1,6):
u = userMove()
c = computerMove()
game = playGame(u,c)
printResults(compWin, userWin, tie)
main()
Inside playGame, you set userWin, compWin, and tie to zero. So every time you call that function, they get set to zero before the new values are added. You should initialize these variables outside the function that you are calling in the loop. (For instance, you could initialize them in announceGame.)

Categories

Resources