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

채택된 답변

James Tursa
James Tursa 2017년 4월 27일
편집: James Tursa 2017년 4월 27일
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개)

카테고리

Help CenterFile Exchange에서 Board games에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by