Você está na página 1de 2

2 Tic-Tac-Toe

You should all know the game of tic-tac-toe (or “noughts and crosses”). In it, a 3 × 3 grid is filled
alternately with noughts and crosses until a line of 3 is made. The first player to do this wins.

2.1 Play against each other

Write a program (in C or Fortran) that allows two people to play tic-tac-toe against each other. The
program should ask each player for the coordinate of their next move, and then display a picture of the
resultant board. The start of a game might look like:

...
...
...

Player X? 3 3

...
...
..x

Player O? 0 3
Error. Please enter a valid cell

Player O? 1 2

.O.
...
..X

The program should not allow invalid moves (out of bounds or in an already occupied cell). It should
also detect any valid three-in-a-row wins and display a suitable message.
Consider the following when writing your program:

1. The board should be stored in a 3 × 3 array of integers, with separate values for blank, X, and O.

2. The main game loop should be a do while loop in Fortran, and a while loop in C.

1
3. There are only 8 possible winning lines, but checking for these individually is error-prone. Note that
there are three types of line: horizontal, vertical, and diagonal, and write, for example, a function
that checks for the nth horizontal line being filled.

You should now attempt one or more of the following separate exercises:

2.2 Play against the computer

There is an optimal strategy for solving 3 × 3 tic-tac-toe, which you can find at http://en.wikipedia.
org/wiki/Tic-tac-toe. Try to implement this in code.
Your program should now allow the user to make the choice of whether s/he or the computer should
go first.

2.3 Have the computer make mistakes

If you have managed to make the computer play perfectly, then allow it to make mistakes. How might
you best do this? For example, you might randomly choose to use the wrong rule from the list given in
the link above.

2.4 Extension to larger grids

Extend your program to allow a general n × n grid. The choice of grid size can be made at either
compile-time (via a #define in C or parameter in Fortran) or at run-time.

2.5 Extension to higher dimensions

Extend your program to 3 (or more) dimensions. You will need to consider how you might display the
board to the user.

Você também pode gostar