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.

推荐文章

- 1. The Drudge Report Has Been Linking To A Site That Plagiarizes S..
- 2. Instagram’s AR filters are getting more dynamic
- 3. Tesla cuts prices across EV line up, ends free supercharging fo..
- 4. Rural Cities Overtake NYC in per Capita Covid-19 Cases
- 5. French contact-tracing app StopCovid passes first vote
- 6. Microsoft launches Cortana app for Windows 10 without Amazon’s..

热门文章

- 1. The Drudge Report Has Been Linking To A Site That Plagiarizes Stories Fro..
- 2. Meet Doug Hurley and Bob Behnken, 2 'badass' astronauts, engineers, and d..
- 3. Microsoft launches Cortana app for Windows 10 without Amazon’s Alexa
- 4. Rural Cities Overtake NYC in per Capita Covid-19 Cases
- 5. Trump threatens shut down social media platforms after Twitter put a disi..

## 我来评几句

登录后评论已发表评论数()