Why the win_check function is not working properly? - python

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 = "_"

Related

Tic-Tac-Toe with Single and Multiplayer in Python

So basically I am trying to build a Tic-Tac-Toe game with both single and multiplayer difficulty levels but I am stuck on what code should I write for player vs computer and I am stuck in a forever loop in the def play_game() function. I can't keep the previous stats of the game as well. I really need help with this.
# --------- Global Variables -----------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions ---------------
# Play a game of tic tac toe
def play_game():
# Show the initial game board
display_board()
game_on = True
while True:
print("1.Single Player")
print("2.Multiplayer")
print("3.Game Stats")
print("4.Quit")
input_1 = int(input("Please Select An Option"))
if input_1 == "3" :
print('reading database...')
read_log()
elif input_1 == "4" :
exit()
elif input_1 == "2" :
Player_1 = input("Enter First Player Name:")
Player_2 = input("Enter Second Player Name:")
display_board()
while game_on:
position = input("Choose a position from 1-9: ")
check_for_winner()
display_board()
# Loop until the game stops (winner or tie)
while game_still_going:
# Handle a turn
handle_turn(current_player)
# Check if the game is over
check_if_game_over()
# Flip to the other player
flip_player()
# Since the game is over, print the winner or tie
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie.")
# Display the game board to the screen
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
# Handle a turn for an arbitrary player
def handle_turn(player):
# Get position from player
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")
# Whatever the user inputs, make sure it is a valid input, and the spot is open
valid = False
while not valid:
# Make sure the input is valid
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Choose a position from 1-9: ")
# Get correct index in our board list
position = int(position) - 1
# Then also make sure the spot is available on the board
if board[position] == "-":
valid = True
else:
print("You can't go there. Go again.")
# Put the game piece on the board
board[position] = player
# Show the game board
display_board()
# Check if the game is over
def check_if_game_over():
check_for_winner()
check_for_tie()
# Check to see if somebody has won
def check_for_winner():
# Set global variables
global winner
# Check if there was a winner anywhere
row_winner = check_rows()
column_winner = check_columns()
diagonal_winner = check_diagonals()
# Get the winner
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
# Check the rows for a win
def check_rows():
# Set global variables
global game_still_going
# Check if any of the rows have all the same value (and is not empty)
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
# If any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_going = False
# Return the winner
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
# Or return None if there was no winner
else:
return None
# Check the columns for a win
def check_columns():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
column_1 = board[0] == board[3] == board[6] != "-"
column_2 = board[1] == board[4] == board[7] != "-"
column_3 = board[2] == board[5] == board[8] != "-"
# If any row does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_going = False
# Return the winner
if column_1:
return board[0]
elif column_2:
return board[1]
elif column_3:
return board[2]
# Or return None if there was no winner
else:
return None
# Check the diagonals for a win
def check_diagonals():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
# If any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
# Return the winner
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
# Or return None if there was no winner
else:
return None
# Check if there is a tie
def check_for_tie():
# Set global variables
global game_still_going
# If board is full
if "-" not in board:
game_still_going = False
return True
# Else there is no tie
else:
return False
# Flip the current player from X to O, or O to X
def flip_player():
# Global variables we need
global current_player
# If the current player was X, make it O
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"
def read_log():
log = open('log.txt', 'r')
log.seek(0)
print('\n\n')
print(log.read(),'\n\n')
# ------------ Start Execution -------------
# Play a game of tic tac toe
play_game()
If I understood correctly You can do it like this:
Define functions:
handle_player_move()
handle_computer_move()
as names suggests when you call the function either human player or computer will make a move (make sure that it's certain or add some Errorcodes/Exceptions when player do something unexpected and you want to end program)
Define function:
game_is_over() # returns True if it's the end of game False other wise
Then Your game is just:
Human vs Human:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_player_move(player2)
whos_move = (whos_move + 1) % 2
Quite similarly Human vs Bot:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
Instead of this you can also check for end of game with your function, and do:
whos_move = 0 # number of player ( 0 or 1 )
while game_still_going:
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
check_if_game_over()
if statement: # your ending statement here
game_is_still_going = False
Your method with flip_player() is also good I just put if statements to both so that they are familiar in truth if you would are able to distinguish in handle_turn() between bot and human player you can do it for both cases ;)
As implementing computer moves can be hard here are some tips:
Easiest way you can just randomly choose number between 1 and 9 check if it's unoccupied if it's free computer makes move there if it is not you pick again. Maybe it sounds like being potentially endless loop but statisticly computer shouldn't have any problems with making a move.
You can also create list of free squares and then randomly choose an index (probably better way)
You can also try to add some logic f.e. if there are two in a row block third square.
too choose random integer from given interval you can use:
import random
random.randint(1,9) # choose integer x such that: 1 <= x <= 9
Of course you can and even maybe should use your own function names (name them as you wish!)
Hope that helps, good luck!

Tic Tac Toe Game, I want to offer the user the option to save game during gameplay(after first move). Here's a portion of my current code

I am attempting to prompt the user the option to save the game, after the first move, during gameplay?
After the game is completed I want to prompt the user to reset the game(Y or N) then call the play game function(with a loop)?
However, I am unsure how to organize the code to accomplish these tasks. I am a beginner to python.
def play_game():
game = True
while game == True:
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
#After the game is completed I want to reset the game and call the play game function(with a loop).
# reset_game()
# play_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
elif winner == None:
print("Tie.")
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
For saving code, your Game has things that you should save:
The state of the board, variable player
Whose turn it is, variable
board
This means you would have to write a function that takes these 2 variables as input argument and writes the content to a file.
#Remy this is what I have for the save function,
which I believe works properly as I've saved the data I need.
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
import random
# functions
# board
# display board
# ask if you want to be x or O
# menu
# play game
# take input & alternate turns
# check win
# check rows
# check columns
# check diagonals
# check tie
# is board full
# ---- Global Variables -----
# Game Board
board = [''] * 9
# If game is still going
game_still_playing = True
# Who won? Or Tie?
winner = None
# Prompt user to choose X's or O's
letter = input("Choose a letter X or O: ").upper()
current_player = letter
# Input validation
while current_player not in ('x', 'o', 'X', 'O'):
letter = input("Try again. Choose a letter X or O:").upper()
current_player = letter
if letter.upper() not in ('X', 'O'):
print("Not an appropriate choice.")
else:
break
print("Player 1 will be ", current_player + "'s.\n")
def display_board():
print(board[6], "\t|", board[7] + " | " + board[8])
print("--------------")
print(board[3], "\t|", board[4] + " | " + board[5])
print("--------------")
print(board[0], "\t|", board[1] + " | " + board[2])
# ("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Load Game\n0) Save & Exit")
# play tic tac toe
def play_game():
begin = "Y"
while begin == "Y":
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
clear_board = reset_game()
play_game()
elif winner == None:
print("Tie.")
reset_game()
play_game()
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
def check_if_game_over():
# 3 in a row
check_for_winner()
# full board
check_if_tie()
def check_for_winner():
# Set up global variables
global winner
# check rows
row_winner = check_rows()
# check columns
column_winner = check_columns()
# check diagonals
diagonal_winner = check_diagonals()
if row_winner:
winner = row_winner
print("There was a ROW win!")
elif column_winner:
winner = column_winner
print("There was a COLUMN win!")
elif diagonal_winner:
winner = diagonal_winner
print("There was a DIAGONAL win!")
else:
winner = None
def check_rows():
# Set up global variables
global game_still_playing
# check rows for all the same values & is not an empty ''
row_1 = board[6] == board[7] == board[8] != ''
row_2 = board[3] == board[4] == board[5] != ''
row_3 = board[0] == board[1] == board[2] != ''
# if any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_playing = False
# Return the winner (X or O)
if row_1:
return board[6]
elif row_2:
return board[3]
elif row_3:
return board[0]
# return X or O if winner
# then flag game still playing to false to end loop
def check_columns():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
column_1 = board[6] == board[3] == board[0] != ''
column_2 = board[7] == board[4] == board[1] != ''
column_3 = board[8] == board[5] == board[2] != ''
# if any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_playing = False
# Return the winner (X or O)
if column_1:
return board[6]
elif column_2:
return board[7]
elif column_3:
return board[8]
# return X or O if winner
# then flag game still playing to false to end loop
def check_diagonals():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
diagonal_1 = board[0] == board[4] == board[8] != ''
diagonal_2 = board[6] == board[4] == board[2] != ''
# if any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_playing = False
# Return the winner (X or O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[6]
# return X or O if winner
# then flag game still playing to false to end loop
def check_if_tie():
# declare global variable
global game_still_playing
# check if board full
if '' not in board:
game_still_playing = False
return
def alternate_player():
global current_player
# if current player is == to X then change it to O
if current_player == "X":
current_player = 'O'
# if current player is == to O then change it to X
elif current_player == "O":
current_player = 'X'
def player1VSai():
#random number
return
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
def menu():
print("Welcome to Tic Tac Toe")
print("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Save & Exit\n4) Load Game")
game_choice = int(input("Choose an option, 0-4: "))
#
return game_choice
def load_game():
#setup global
global current_player
file = open("HW3game.txt", "r")
for i in range(0,8):
board[i]=file.read(1)
current_player=file.read(1)
#current choice of game.
game_choice=int(file.read(1))
file.close()
print("You have called the load function.")
return
def reset_game():
global board
#erase contents in current board
#replay game
clear_board = board.clear()
return clear_board
play_game()

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!

Tic Tac Toe nested-list issues

My Tic tac toe code works fine except for a few issues. When marking a spot on the board the user can override and place their own mark in the same spot. Even though I have code that is supposed to fix this. Here is my code. Please fix any other errors as you see fit. I am almost failing a class on this.
board = [['-','-','-']
,['-','-','-']
,['-','-','-']]
player1 = 'X'
player2 = 'O'
win = False
turns = 0
player1= str(input("Whats ur name+"))
player2= str(input("Whats ur name"))
def checkwin(player):
for c in range(0,3):
if board[c][0] == player and board[c][1] == player and board[c][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win
elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win (right to left)
elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
else:
playerwin = False
return playerwin
def playerturn(player):
print "%s's turn" % player
turn = 1
while(turn):
print "Select column [1-3]: ",
col = int(raw_input()) - 1
print "Select row [1-3]: ",
row = int(raw_input()) - 1
if board[row][col] == "X" or board[row][col] == "O":
print "Already taken!"
else:
board[row][col] = player
turn = 0
def printboard():
print board[0]
print board[1]
print board[2]
printboard()
while(win == False):
playerturn(player1)
turns += 1
printboard()
if checkwin(player1) == True: break
if turns == 9:
print "This game is a draw!"
break
playerturn(player2)
turns += 1
printboard()
checkwin(player2)
if checkwin(player2) == True: break
Your problem is that you've put the player name in the array and checked whether there is an "X" or an "O" in the array. A simple solution would be changing the if condition to ... == player1 instead of "X".
If you do so, you also have to adjust the draw function.
board = [['-','-','-']
,['-','-','-']
, ['-','-','-']]
#player1 = 'X'
#player2 = 'O'
win = False
turns = 0
player1= raw_input("Whats ur name+")
player2= raw_input("Whats ur name")
def checkwin(player):
for c in range(0,3):
if board[c][0] == player and board[c][1] == player and board[c][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win
elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for diagonal win (right to left)
elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
else:
playerwin = False
return playerwin
def playerturn(player):
print "%s's turn" % player
turn = 1
while(turn):
print "Select column [1-3]: ",
col = int(raw_input()) - 1
print "Select row [1-3]: ",
row = int(raw_input()) - 1
if board[row][col] == player1 or board[row][col] == player2:
print "Already taken!"
else:
board[row][col] = player
turn = 0
def printboard():
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[0]]
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[1]]
print ["X" if x == player1 else "O" if x == player2 else "-" for x in board[2]]
printboard()
while(win == False):
playerturn(player1)
turns += 1
printboard()
if checkwin(player1) == True: break
if turns == 9:
print "This game is a draw!"
break
playerturn(player2)
turns += 1
printboard()
checkwin(player2)
if checkwin(player2) == True: break
I also replaced the str(input()) to raw_input() to allow a string as name.

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