I'm learning Python at the moment. While taking the first steps, I implemented a Tic Tac Toe game and wanted to share it here, to get some feedback and continue learning. I'm looking for any improvements within my code: style, common mistakes, etc.
def create_playing_board(side_length):
return [[0 for x in xrange(side_length)] for x in xrange(side_length)]
def print_current_board(board):
print "\n", " Y | ", board[0][2], '|', board[1][2], '|', board[2][2]
print " | --+---+--"
print " | ", board[0][1], '|', board[1][1], '|', board[2][1]
print " | --+---+--"
print " | ", board[0][0], '|', board[1][0], '|', board[2][0]
print " | "
print " ------------ X"
def set_marker(player, board):
print "\nplayer",player, " - x/y input between 0 and 2"
x = y = 3
while(x not in range(0,3)):
x = input("x: ")
while(y not in range(0,3)):
y = input("y: ")
if board[x][y] == 0:
board[x][y] = player
return board
else:
print '\nfield already used - choose again!'
set_marker(player,board)
return board
def check_for_winner(player, board):
if (board[0][0] == board[1][0] == board[2][0] == player):
return 1
elif (board[0][1] == board[1][1] == board[2][1] == player):
return 1
elif (board[0][2] == board[1][2] == board[2][2] == player):
return 1
elif (board[0][0] == board[0][1] == board[0][2] == player):
return 1
elif (board[1][0] == board[1][1] == board[1][2] == player):
return 1
elif (board[2][0] == board[2][1] == board[2][2] == player):
return 1
elif (board[0][0] == board[1][1] == board[2][2] == player):
return 1
elif (board[0][2] == board[1][1] == board[2][0] == player):
return 1
else:
return 0
board = create_playing_board(3)
player = 1
is_win = 0
print "welcome to tic tac toe"
while(is_win == 0):
print_current_board(board)
board = set_marker(player, board)
is_win = check_for_winner(player, board)
if is_win == 1:
print ' \n### player', player,' wins! ###\n'
print_current_board(board)
print "\ndo you guys want to play again?"
is_win = input("0 = yes // 1 = no: ")
if is_win == 0:
board = create_playing_board(3)
player = (player%2)+1