Tic-Tac-Toe (multiplayer) using pthon

 


About The Game:

 Tic-Tac-Toe (also known as noughts and crosses) is a paper and pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. It is a solved game with a forced draw assuming best play from both players. wikipedia


Tic-Tac-Toe in python:

def printBoard(currentPos):
print("{} {} {}".format(currentPos[0], currentPos[1], currentPos[2]))
print("{} {} {}".format(currentPos[3], currentPos[4], currentPos[5]))
print("{} {} {}".format(currentPos[6], currentPos[7], currentPos[8]))

def askPos():
global pos
pos = int(input("row (0 to 2):\n"))
if pos < 0 or pos > 8:
print(f"{pos} is an invalid row number!")
askPos()

def updatePositions(position, playerSymbol):
position[pos] = playerSymbol
s = "continue"
def win(player):
print(f"{player} won!!")
ask = input("Do you want to play again? (Y/N)\n").upper()
if ask == "Y":
main()
elif ask == "N":
global s
s = "break"

def main():

#game variables
positions = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
i = 1

playerX = input("name of player X:\n").upper()
playerO = input("name of player O:\n").upper()

#game loop
gameOver = False
while not gameOver:
printBoard(positions)
if i%2 == 0:
playerSymbol = "O"
i+=1
else:
playerSymbol = "X"
i+=1
if playerSymbol == "X":
currentPlayer = playerX
else:
currentPlayer = playerO
print(f"player : {currentPlayer}")
askPos()
updatePositions(positions, playerSymbol)
#printBoard(positions)

if positions[0] == positions[1]:
if positions[1] == positions[2]:
if positions[0] == "X":
win(playerX)
else:
win(playerO)
elif positions[3] == positions[4]:
if positions[4] == positions[5]:
if positions[3] == "X":
win(playerX)
else:
win(playerO)
elif positions[6] == positions[7]:
if positions[7] == positions[8]:
if positions[7] == "X":
win(playerX)
else:
win(playerO)
elif positions[0] == positions[3]:
if positions[3] == positions[6]:
if positions[0] == "X":
win(playerX)
else:
win(playerO)
elif positions[1] == positions[4]:
if positions[4] == positions[7]:
if positions[1] == "X":
win(playerX)
else:
win(playerO)
elif positions[2] == positions[5]:
if positions[5] == positions[8]:
if positions[2] == "X":
win(playerX)
else:
win(playerO)
elif positions[0] == positions[4]:
if positions[4] == positions[8]:
if positions[0] == "X":
win(playerX)
else:
win(playerO)
elif positions[2] == positions[4]:
if positions[4] == positions[6]:
if positions[0] == "X":
win(playerX)
else:
win(playerO)
if s == "break":
break


if __name__ == '__main__':
main()
 
@projectsofcode on instagram

Comments

Popular posts from this blog

HangMan game in PYTHON

Projects to consider as a bigener in PYTHON