Check taken location on Tic Tac Toe board
이전 댓글 표시
I'm trying to make a small function that checks whether a spot is taken on a Tic Tac Toe board or not. I have created an array of zeroes called tttArray where when each spot is filled, its location is changed to 1. So I first take the input from the player from the below function.
function [pXInputRow, pXInputCol] = pickXspot(playerInput)
%This function is to take inputs from Player X
pXInputRow = 0;
pXInputCol = 0;
%Set text for Row/Col Prompt
prompt = {'Row (1,2, or 3)', '(Col (1, 2, or 3)'};
name = 'Player X Turn';
%Show prompt to input values
playerInput = inputdlg(prompt, name);
pXInputRow = str2num(playerInput{2});
pXInputCol = str2num(playerInput{1});
tttArray(pXInputRow, pXInputCol) = 1;
end
And then use the below function to see if the spot is taken.
function [spotTaken] = checktaken(tttArray)
%Function used to check if spot is taken
%Setup Error Messages
errorMessage = 'This spot is taken, please choose another spot';
errorMessageTitle = 'Spot Taken';
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1
msgbox(errorMessage, errorMessageTitle)
spotTaken = 1;
end
end
However, I keep getting the following error after I run and put a row/col in the prompt dialog box. Any Suggestions?
Not enough input arguments.
Error in checktaken (line 8)
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1
채택된 답변
추가 답변 (1개)
Walter Roberson
2015년 10월 4일
편집: Walter Roberson
2015년 10월 4일
Your function pickXspot changes tttArray but does not return its value. The change is only going to affect the workspace of that one function, unless tttArray is defined in a function that picXspot is nested inside.
Your function checktaken uses pXInputRow and pXInputCol and pOInputRow and pOInputCol but they are not passed as parameters. This will be an error unless they happen to be defined as functions, or of they are defined as variables in a function that checktaken is nested inside.
The error you display would be consistent with the possibility that you invoked checktaken() without passing any input parameters.
Note: the syntax
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1
is equivalent to
if tttArray(pXInputRow, pXInputCol) ~= 0 || tttArray(pOInputRow, pOInputCol) == 1
if you want to test that both values are 1 then you need to test them individually -- the "== 1" does not "distribute" to both locations.
Also note that if your "if" is not considered true then you do not assign a value to spotTaken which would cause a problem.
Might I also suggest that you should be testing whether the spot is taken before assigning the spot as taken in pickXspot, and if it is taken then force the user to pick a different spot before returning?
댓글 수: 1
Anas Abou Allaban
2015년 10월 4일
카테고리
도움말 센터 및 File Exchange에서 Board games에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!