Coursework 2
Coursework 2
Two players are playing the Tic Tac Toe game. Player 1 and 2 take turns to draw
on the 3 x 3 square board.
Player 1 goes first and draws X (capital letter X) and Player 2 draws O (capital
letter O).
The first player to get 3 of their marks in a row (up, down, across, or diagonally) is
the winner.
The board is numbered like this:
123
456
789
2
The players record their games in a sequence of numbers, for instance, 5237649.
This means that the game goes as follows:
Player 1 puts a X at 5.
Player 2 puts a O at 2.
Player 1 puts a X at 3.
…
Player 1 puts a X at 9.
Write a function prepareBoard(game) .
numbering 1 2 3 4 5 6 7 8 9
numbering 0 O X O X X O 0 X
3
You are asked to print out the board at the end of the game. For the game above,
the board looks like this:
_OX
OXX
O_X
Note that the underscore means that the position is empty without any player’s
drawings.
As another example, 539128647 should print out the following game:
OXO
OXX
XOX
Write a printBoard(game) function, where game is a string of numbers, as in the
previous question.
In the function, first call the prepareBoard(game) function.
If the result claims that it is an Invalid input , then print this message out.
If the input is valid, then use the list of symbols returned
by prepareBoard(game) to print a board in the above form.
After each symbol, there will be a space.
4
The final step of the Tic Tac Toe game is determine who is the winner or the game
draws.
Write a function whoWins(game) which again takes in a string of numbers as in the
previous question. But this time, we assume that it is a valid input and that the
game will stop immediately when a winner is determined.
The whoWins(game) function will print out the board, as in the previous question
and on a separate line, print out one of the following:
Player 1 wins
Player 2 wins
Draw
For instance, whoWins("539128647") will print out
OXO
OXX
XOX
Draw
In a school’s Fun Sports Day, there is a game to fill a big bucket. Each child takes
a cup and fills it with water and hops 10 metres to the bucket and empty the water
in the cup to the bucket.
The bucket’s capacity is 1 litre and each cup can hold at most 300 ml. Each team
has 5 players who relay to fill the bucket.
The game stops if