Creating a Tic-Tac-Toe game in Matlab

I'm very new to Matlab and am creating a simple Tic Tac Toe game where a user plays against the computer. I have 3x3 push buttons in a GUI and for each button's callback I have set it up so that an 'X' will appear if the square is empty, and set a '1' value into a 3x3 zeros matrix in the corresponding spot.

I want to put a 'player2' function after this in each callback so that the computer will find any spot in the matrix that is a zero, randomly pick one and give me the coordinates which I will then translate over to its corresponding push button to place an 'O' there.

The matrix is handles.move=zeros(3,3).

I know I'll probably need to use an 'if' statement, and '[i,j] = find(move==0);' but I don't know what random command to use with this to pick from the zeros that will give me back the coordinates. Any suggestions?

Calling find(move==0) will return linear indices of elements in move which are equal to zero. For example:

move =

     1     0     1
     0     0     0
     0     1     0

>>indices = find(move==0)

indices =

 2
 3
 4
 5
 8
 9

You can take this result and scramble the indices randomly using...

>>scrambled = indices(randperm(length(indices)))

scrambled =

 9
 2
 8
 4
 3
 5

Then choose the first element, scrambled(1) , as the computer's next choice. There are probably several ways to go about this. The nice thing about this one is that it can be called until the very end of the game to retrieve the computer's next move.

EDIT:

computerMove = indices(randperm(length(indices),1));

This will return the first element automatically as Dennis pointed out.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章