HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Design Tic tac toe game

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
toedesigntictacgame

Problem

Today I had an interview, where I was asked to solve this question:

Design Tic tac toe game

Game rules:


Design a simple tic tac game with 2 modes for 3*3 matrix. At the
beginning, ask if single player or two player mode has to be played
(more details on the mode below).


The players input position on matrix by inputting 2 integers, like:

0,0    0,1    0,2

1,0    1,1    1,2

2,0    2,1    2,2




If anywhere player gives incorrect input, he has to be prompted to
give the right value again.


Print the updated matrix after every input. Example: after 3 moves,
one game might look like

1    1    _

2    _    _

_     _    _




Single player mode


In this mode, player plays against the computer.
You’ve to first assign 0’s or X’s to the Player. X’s play first. The
computer can randomly place its assigned symbol at any available
position within the matrix.


Two player mode


In this mode, two players play against each other.


The game ends when either player wins, or there are no moves left
(draw). At the end of game, print the final result Ask if the player
wants to play another game, and start a new game/end the game
accordingly.

I got the feedback that complexity could be improved, How to improve it?
and how to make it more readable

Code goes below:

```
def get_input(mat, player):
input_value = map(int, raw_input().split(','))
while(validate_input(mat, input_value) == False):
print "not correct input"
input_value = map(int,raw_input().split(','))
mat[input_value[0]][input_value[1]] = player
return input_value

def validate_input(mat, input_value):
x = input_value[0]
y = input_value[1]
if x not in [0,1,2] or y not in [0,1,2]:
return False
if mat[x][y]:
return False
return True

def switch_play(player):
player = 2 if player==1 else 1
return player

def print_game(mat):
print mat

def get_random(mat):
in

Solution

I think your interviewer meant that you can improve checking the winning situation and do it in \$O(1)\$ time by keeping track of the scores in rows, columns and both diagonals (total 8 variables for 3x3 board):

[row1, row2, row3, column1, column2, column3, diagonal, anti-diagonal]


Then, you can increment these value by 1 in case of "player 1" and decrement by one in case of "player 2". This will lead to only checking these 8 values (or you can also use the fact that you know where the last move took place) for 3 or -3 for a winning situation. You can find out more about this idea here.

Or, you can go over all the possible winning combinations like suggested here or here.

Code Snippets

[row1, row2, row3, column1, column2, column3, diagonal, anti-diagonal]

Context

StackExchange Code Review Q#159801, answer score: 4

Revisions (0)

No revisions yet.