MATLAB Answers

I'm coding a Connect4 game. Firstmove should play bottom middle of an empty board if I am first, secondmove should play to the left or right of the other player if I am second. Why does my code play bottom middle and to the left of my own move?

조회 수: 1(최근 30일)
function state = play_connect_four_MeisSunnarborg(state, player)
if firstmove(state) == true
state(6,4) = player;
end
if secondmove(state) == true
col = find(state(6,:),1);
state(6,col-1) = player;
end
if secondmove(state) == false
col = find(state(6,:),1);
state(6,col+1) = player;
end
end
function firstmove = firstmove(state)
if state == zeros(6,7)
firstmove = true;
else ,firstmove = false;
end
end
function secondmove = secondmove(state)
col = find(state(6,:),1);
if col == 2 || 3 || 4 || 5 || 6 || 7
secondmove = true;
end
if col == 1
secondmove = false;
end
end

  댓글 수: 0

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 27 Apr 2017
편집: James Tursa 27 Apr 2017
Several problems:
Replace this line:
if state == zeros(6,7)
with this to test for matrix equality:
if isequal(state,zeros(6,7))
Or, if you want generic code that is not tied to any particular matrix size, maybe this instead:
if( all(state(:)==0) )
Replace this line:
if col == 2 || 3 || 4 || 5 || 6 || 7
with this to test if a number is one of several possible numbers:
if( ismember(col,[2 3 4 5 6 7]) )
Don't name a return variable the same as a function name. So change this line:
function firstmove = firstmove(state)
to something like this instead (and change all variable references to "result" also):
function result = firstmove(state)
Same comment for the "secondmove" function.
The "firstmove" and "secondmove" functions return a value, but you don't do anything with this value in the calling code. So you need to examine your logic and determine what you want to do with these result variables in your calling code.

  댓글 수: 0

댓글을 달려면 로그인하십시오.

추가 답변(0개)

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by