Write a simulation of a funny game with a dice in MATLAB - matlab

I am trying to write a code that simulates the following game:
Roll two dice and let x be the sum of them. If x=7 or x=11 then you win. Otherwise roll both dice again until you get x (in which case you win) or 7 or 11 (in which case you loose).
Imagine you have a two dice, then if in the first roll you get as the sum of both 7 or 11, you win, if not, then the sum could be other number, let's say 9, then you have to continue rollin both dice until you get again 9, if in that process you get 7 or 11 agiain you loose :)
Then I wrote the following code:
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
while x~=7 & x~=11
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
if x==x
disp('You win')
elseif x==7 | x==11
disp('You loose')
end
end
But it displays indefinitely the sentence "you win" and can't stop it, I know that this is because the condition "x==x" always evaluates true, but how can I fix that to have the simulation?
Thanks a lot in advance

Do you want to do re-rolls until you win? In that case you want to do the re-roll in your while-loop. Checking the same number over and over again is not going to be useful.
x=0;
wins=[7 11];
while min(x~=wins)
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2
if max(x==wins)
disp('You win')
else
disp('You loose')
end
end

This should work:
x=0;
while x~=7 | x~=11
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
if x==7 | x==11
disp(x)
disp('You win')
break
else
disp(x)
disp('You loose')
a = input('You want roll again (y/n)? ','s')
if strcmpi(a,'y')
else
break
end
end
end

added more of a game vibe to it, also added comments so you understand what I am doing
win1 = 7; %these values give you a win
win2 = 11;
lose1 = 0; %can't lose on first roll. this will be set later
lose2 = 0;
streak = 0;
%while game is still going on..
while true
newgame = input('Would you like to start a new game? Type YES or NO --> ','s'); %user inputs string
if strcmpi(newgame,'YES') %did user type YES?
game = true; % set games state to true to begin the game loop
firstroll=true; %first roll coming up
elseif strcmpi(newgame,'NO')
break; % end program by exiting outer loop
else %user didn't enter correctly so re-ask
continue;
end
while game
input('Press enter to roll dice'); %roll the dice
d1 = floor(6*rand)+1;
d2 = floor(6*rand)+1;
disp('You rolled:'); %display the dice
disp(d1);
disp(d2);
x=d1+d2;
if x==win1 || x==win2 % check for a win
streak=streak+1; %%add a win to your total
disp('WINNER!')
elseif x==lose1 || x==lose2
disp('YOU LOST!')
disp('streak:') %show how many games you won
disp(streak)
game = false; % end game state because you lost
%reset winning and losing numbers
win1=7;
win2=11;
lose1=0;
lose2=0;
streak = 0; %reset streak
elseif firstroll %ok, didn't win on the FIRST ROLL so lets set the NEW winning value and reroll
win1 = x; % we win if we roll the same value again
win2 = x;
lose1 = 7; % we lose if we roll a 7 or 11
lose2 = 11;
firstroll = false; % set firstroll false so it doesn't keep resetting the winning and losing values
continue;
end
end
end
disp('Thanks for playing!')

Because you change the rule after the first round, you specify the rule of the first round with an if statement and the rest of the game in the else statement. Moreover, you need to specify the value X in your code. Here I use 5 as an example. If there is no result after the first round, you role the dice again with the code d1=floor(6*rand)+1; d2=floor(6*rand)+1; x=d1+d2;, then determine whether you win or lose. If there is still no result, you will use a while loop to keep this going until there is a win or lose situation.
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
first_sum = x % use another variable first_sum to hold the status of first roll
if x==7 || x==11
disp('You win')
else
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
if x== 7 || x==11
disp('You lose')
elseif x == first_sum
disp('You win')
else
while x ~= first_sum && x~=11 && x~=7
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
if x== 7 || x==11
disp('You lose')
elseif x == first_sum
disp('You win')
end
end
end
end
Or you can write this in a more succinct way. Since the else statement contains a structure like a do while loop(meaning do at least once and keep doing it if a certain condition is met), you can also code it like this :
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
first_sum = x
if x==7 || x==11
disp('You win')
else
flag = true
while flag % The while loop will keep going until flag is set to false.
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
if x== 7 || x==11
disp('You lose')
flag = false % If a result is reached, stop the while loop
elseif x == first_sum
disp('You win')
flag = false
end
end
end

d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
x=d1+d2;
kk=1;
while x~=7 && x~=11
d1=floor(6*rand)+1;
d2=floor(6*rand)+1;
if kk ==1
tmp = d1+d2;
end
x=d1+d2;
if x==7 || x==11 && kk == 1
disp('You win')
elseif x==7 || x==11 && kk > 1
disp('You loose')
elseif x==tmp && kk>1
disp('You win')
else
disp('You loose')
end
kk = kk+1;
end
What is happening is that I introduced kk, which can be considered and iteration counter. Add that as an extra condition upon the winning condition. if statements then contain all the conditions you set, note that if kk==1 I save the sum in tmp, against which I check the second win condition.
Test run:
You loose
You loose
You loose
You win

Related

Matlab Code should stop duplicates, but duplicates still occur

I am trying to write a program that will find the outline of a figure by finding if points around an original point is within a boundary of the original point. I have tried to write a section that will prevent points to look at points already included in the outline (using variables a,b,c,d). The current code I have is
while 1
[m M] = size(already_boxed);
x=0;
for n = 1:m
a=0;
b=0;
c=0;
d=0;
for w = 1:m
if already_boxed(w,:) == [(already_boxed(n,1)+1), already_boxed(n,2)]
a=1;
end
if already_boxed(w,:) == [(already_boxed(n,1)-1), already_boxed(n,2)]
b=1;
end
if already_boxed(w,:) == [already_boxed(n,1), (already_boxed(n,2)+1)]
c=1;
end
if already_boxed(w,:) == [already_boxed(n,1), (already_boxed(n,2)-1)]
d=1;
end
end
if a==0
if subimages((already_boxed(n,1)+1), already_boxed(n,2))<subimages(already_boxed(n,1),already_boxed(n,2))*0.9 && subimages((already_boxed(n,1)+1), already_boxed(n,2))>subimages(already_boxed(n,1),already_boxed(n,2))*1.1
already_boxed = [already_boxed; (already_boxed(n,1)+1), already_boxed(n,2)];
x=1;
end
end
if b ==0
if subimages((already_boxed(n,1)-1), already_boxed(n,2))<subimages(already_boxed(n,1),already_boxed(n,2))*0.9 && subimages((already_boxed(n,1)-1), already_boxed(n,2))>subimages(already_boxed(n,1),already_boxed(n,2))*1.1
already_boxed = [already_boxed; (already_boxed(n,1)-1), already_boxed(n,2)];
x=1;
end
end
if c==0
if subimages(already_boxed(n,1), (already_boxed(n,2)+1))<subimages(already_boxed(n,1),already_boxed(n,2))*0.9 && subimages(already_boxed(n,1), (already_boxed(n,2)+1))>subimages(already_boxed(n,1),already_boxed(n,2))*1.1
already_boxed = [already_boxed; already_boxed(n,1), (already_boxed(n,2)+1)];
x=1;
end
end
if d ==0
if subimages(already_boxed(n,1), (already_boxed(n,2)-1))<subimages(already_boxed(n,1),already_boxed(n,2))*0.9 && subimages(already_boxed(n,1), (already_boxed(n,2)-1))>subimages(already_boxed(n,1),already_boxed(n,2))*1.1
already_boxed = [already_boxed; already_boxed(n,1), (already_boxed(n,2)-1)];
x=1;
end
end
end
if x == 0
break
end
end
Right now, the code will go on forever since it keeps on checking points that are in the online. For example, the variable 'already_boxed' will contain the doubles:
119,288
120,288
118,288
119,289
119,287
119,288
I don't know why 119,288 shows up twice, and I only want it to show up once. How can I fix this?

Tic Tac Toe with a win and taken check - Matlab

I'm making a tic tac toe game and I'm bombarded with various errors everytime I try to debug. I'm not sure where the problem is. The main error is either
Index exceeds matrix dimensions
or
Subscript indices must either be real positive integers or logicals
in line 8 of my 'checktaken' function.
Below is my code, where tttGame is the main function, boardplot does the plotting, and checkwintest/check taken see if a position is taken or if there is a win. I have asked many people for help and most haven't a clue whats wrong. Examples/code of your answers will help. Thanks!
Main function:
function tttGame
%%
%This function determines which players turn it is and whether there is a
%win or not
wonX = 0;
wonO = 0;
tttArray = zeros(3);
tttXArray = zeros(3);
tttOArray = zeros(3);
while wonX ~= 1 || wonO ~= 1
%%
%Initialize values
pXInputRow = 0;
pXInputCol = 0;
pOInputRow = 0;
pOInputCol = 0;
%%
%Show prompt to input values
pXInputRow = input('Player X Enter Row: ');
pXInputCol = input('Player X Enter Column: ');
%Plot and prompt Player X
boardplot(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol)
%Check taken location
checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol);
%If place is taken, prompt player to input again
if checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol) == 1
%Show prompt to input values
msgbox('That spot is taken')
pXInputRow = input('Enter Row: ');
pXInputCol = input('Enter Column: ');
%Otherwise, continue and change taken/player position on board
else
tttArray(pXInputRow, pXInputCol) = 1; %Set the position as taken
tttXArray(pXInputRow, pXInputCol) = 1; %Set the position for X
end
%Check if theres a win
checkwintest(tttXArray, tttOArray)
%Reset values
pXInputRow = 0;
pXInputCol = 0;
%%
%Show prompt to input values
pOInputRow = input('Player O Enter Row: ');
pOInputCol = input('Player O Enter Column: ');
%Prompt and plot Player O
boardplot(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol)
%Check taken location
checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol);
%If place is taken, prompt player to input again
if checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol) == 1
%Show prompt to input values
msgbox('That spot is taken')
pOInputRow = input('Enter Row: ');
pOInputCol = input('Enter Column: ');
%Otherwise, continue and change taken/player position on board
else
tttArray(pOInputRow, pOInputCol) = 1;%Set the position as taken
tttOArray(pOInputRow, pOInputCol) = 1;%Set the position for O;
end
%%
%Check win again
checkwintest(tttXArray, tttOArray)
%Reset values
pOInputRow = 0;
pOInputCol = 0;
end
end
Winning function
function [wonX, wonO] = checkwintest(tttXArray, tttOArray, tttGame)
%Test to see whether this format of win testing works
%Find any nonzero value in the tttX/OArray matrix. Returns 1 if true.
%All Columns, rows, diagonals
if any(all(tttXArray)) || any(all(tttXArray, 2)) || any(all(diag(tttXArray)))...
|| any(all(diag(fliplr((tttXArray)))));
wonX = 1;
elseif any(all(tttOArray)) || any(all(tttOArray, 2)) || any(all(diag(tttOArray)))...
|| any(all(fliplr(diag(tttOArray))));
wonO = 1;
else
wonX = 0;
wonO = 0;
end
%Send a message if a player won
if wonX == 1
playerXWonMessage = 'Congratulations Player X, you win!';
msgbox(playerXWonMessage)
exit(tttGame);
elseif wonO == 1
playerOWonMessage = 'Congratulations Player O, you win!';
msgbox(playerOWonMessage)
exit(tttGame);
end
end
Then
function [spotTaken] = checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol)
%Function used to check if spot is taken
%Setup Error Messages
errorMessage = 'This spot is taken, please choose another spot';
errorMessageTitle = 'Spot Taken';
spotTaken = 0;
if (tttArray(pXInputRow, pXInputCol) == 1) || (tttArray(pOInputRow, pOInputCol) == 1)
msgbox(errorMessage, errorMessageTitle)
spotTaken = 1;
end
end
and
function boardplot(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol)
%Setup the window for the game
close all;
clc;
figure('Name','Tic Tac Toe');
plot(-1. -1)
axis([0 3 0 3])
set(gca,'xTick',1:3)
set(gca,'yTick',1:3)
set(gca,'xTickLabel',[1 2 3])
set(gca,'yTickLabel',[1 2 3])
grid on
hold on
shg
%Plot
plot(pXInputRow - 0.5, pXInputCol - 0.5,'x', 'MarkerSize', 50)
hold on
plot(pOInputRow - 0.5, pOInputCol - 0.5,'o', 'MarkerSize', 50)
hold on
end
So I solved the problem and rewrote most of my code.
First I did not pass the proper inputs to the function checktaken (and other functions) which obviously led to some errors.
Then I rewrote my user input statements to use only 2 variables for rows/cols rather than 4, where there are 2 for each player.
checktaken is rewritten as follows:
function [spotTaken] = checktaken(tttArray, x, y)
%This function is used to check if spot is taken
%Function takes users row/col input as indices for the taken locations
%array, 'tttArray'. It then returns whether the spot is taken or not.
%Setup Error Messages
errorMessage = 'This spot is taken, please choose another spot';
errorMessageTitle = 'Spot Taken';
spotTaken = 0; %Initialization
%If the location's value is 1(taken), show error message and return
%spotTaken as 1(true).
if tttArray(x,y) == 1
msgbox(errorMessage, errorMessageTitle)
pause(3)
spotTaken = 1;
end
end
And I take the input via
function [a,b] = pickunospot
%This nested function creates the prompt for the player and takes
%the inputs as indices to be used later on in our arrays
prompt = {'Row (1,2, or 3)', '(Col (1, 2, or 3)'};
name = 'Enter your choice of row or column';
pt=inputdlg(prompt, name);
a = str2num(pt{2});
b = str2num(pt{1});
end
and call it like this
[x,y] = pickunospot;
where x and y are the rows/cols and can be used as matrix indices in checktaken.
This prevented any matrix index errors and limited the issue with 'not enough input arguments'.

Conditional switching between vector

I have two same dimensioned vectors sig1 and sig2, both have more than 1 million data. With the condition that whenever the value of a vector falls below a threshold, a pointer will point to alternate vector (switching). This way I want to form a new vector sws from the pointer's values. Below code works fine, the only issue is, it takes long time. Is there any other way to speed up the code? :
thresh = -70;
i=1;
flag1 = 1; % 1 means sig1, 0 means sig2
flag2 = 0; % 1 means switch happened in this loop, 0 means no switch happened in this loop
while(i <= numel(sws))
if(flag1 == 1)
sws(i)=sig1(i);
else
sws(i)=sig2(i);
end
if(sws(i) < thresh)
if(flag2==1)
i=i+1;
else
flag1 = ~flag1;
end
flag2= ~flag2;
else
flag2 = 0;
i=i+1;
end
end

How can i end an if statement and break out of all others?

I am making a black jack program for a class, and i have a series of "if loops"my issue is thatwhen i say yes, hit me with another card, it proceeds to the next step as i would like, but when i say "no, i am holding", it still asks me if i would like to hit again. How can i make it so that when i say no, I then end the function completly? program is below.
players=input('Welcome to Matjack! Aces count as 11, and face cards count as 10. Please enter the number of players:')
if players==1;
card_1=randi(11,1);
card_2=randi(11,1);
fprintf ('Face up card is %d! Face down is unknown!',card_1)
hit=input(' Hit? Y/N:','s')
if hit=='Y';
card_3=randi(11,1);
cards=card_1+card_3;
player_1=card_1+card_2+card_3;
if player_1<21;
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_4=randi(11,1);
cards=card_1+card_3+card_4;
player_1=card_1+card_2+card_3+card_4;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_5=randi(11,1);
cards=card_1+card_3+card_4+card_5;
player_1=card_1+card_2+card_3+card_4+card_5;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_6=randi(11,1);
cards=card_1+card_3+card_4+card_5+card_6;
player_1=card_1+card_2+card_3+card_4+card_5+card_6;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4+card_5;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
if player_1<21
fprintf('Value of face up cards is %d. Face down is still unknown!',cards);
hit=input(' Hit again? Y/N:','s')
if hit=='Y';
card_7=randi(11,1);
cards=card_1+card_3+card_4+card_5+card_6+card_7;
player_1=card_1+card_2+card_3+card_4+card_5+card_6+card_7;
end
if player_1>21 ;
fprintf ('Player one broke! Total card value was %d',player_1)
end
if hit=='N';
player_1=card_1+card_2+card_3+card_4+card_5+card_6;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
end
if hit=='N';
player_1=card_1+card_2;
fprintf ('Player one holds! Total card value was %d',player_1)
end
end
I worked on it a bit. Some functions you might want to add are the split, put in suits, and add in persistent player names. I tried to put in descriptive variable and function names.
function Matjack
global AllCards decks
AllCards = [];
clc
DealerHitOnSoft17 = 1;
disp('Welcome to Matjack! Aces count as 11, and face cards count as 10.')
if DealerHitOnSoft17
disp('Dealer hits on soft 17')
else
disp('Dealer holds on soft 17')
end
NumberPlayers = input('Please enter the number of players:');
decks = input('How many decks of cards do you want to play with? ');
playerName = cellfun(#(n) strjoin({'Player ', num2str(n)}, ' '), num2cell((1:NumberPlayers)'), 'uni', 0);
dealerCards = DealCards(2, []);
if Blackjack('Dealer', dealerCards)
printHand('Dealer''s', dealerCards)
disp('You lose')
return
end
printHand('Dealer''s', dealerCards(1))
playerHands = cellfun(#(n) DealCards(n, []), num2cell(2 * ones( NumberPlayers, 1)), 'uni', 0);
isPlaying = ones(size(playerHands));
for i = 1:NumberPlayers
isPlaying(i) = ~Blackjack(['Player ', num2str(i)], playerHands{i});
end
while any(isPlaying)
for i = 1:NumberPlayers
if isPlaying(i)
printHand(playerName{i}, playerHands{i})
if strcmpi(input([playerName{i}, ' has ', num2str(sumHand(playerHands{i}, 0)),'. Hit? Y/N:'],'s'), 'y')
playerHands{i} = DealCards(1, playerHands{i});
printHand(playerName{i}, playerHands{i})
disp([playerName{i}, ' has ', num2str(sumHand(playerHands{i}, 0)),'.'])
if sumHand(playerHands{i}, 0) > 21
disp([playerName{i}, ' busts!'])
isPlaying(i) = 0;
end
else
disp([playerName{i}, ' holds at ', num2str(sumHand(playerHands{i}, 0)),'.'])
isPlaying(i) = 0;
end
end
end
end
printHand('Dealer''s', dealerCards)
while sumHand(dealerCards, DealerHitOnSoft17) < 17
dealerCards = DealCards(1, dealerCards);
printHand('Dealer', dealerCards)
if sumHand(dealerCards, DealerHitOnSoft17) > 21
disp('Dealer busts!')
elseif sumHand(dealerCards, DealerHitOnSoft17) > 17
disp(['Dealer holds at ', num2str(sumHand(dealerCards, DealerHitOnSoft17)),'.'])
else
disp(['Dealer has ', num2str(sumHand(dealerCards, DealerHitOnSoft17)),'.'])
end
end
cellfun(#(name, h) WinDrawLose(name, sumHand(h, 0), sumHand(dealerCards, DealerHitOnSoft17)), playerName, playerHands);
end
function hand = DealCards(N, hand)
global AllCards decks
possibleCards = randi(52 * decks, N, 1);
[C, ia, ~] = unique([AllCards; possibleCards], 'stable');
ia = ia - length(AllCards);
ia(ia < 1) = [];
n = length(AllCards) + N - length(C);
AllCards = C;
hand = [hand; possibleCards(ia)];
if n > 0
hand = DealCards(n, hand);
end
end
function printHand(player, hand)
ord = horzcat('Ace', cellfun(#num2str, num2cell(2:10), 'uni', 0), 'Jack', 'Queen', 'King');
hand = mod(hand - 1, 13) + 1;
if length(hand) == 1
disp([player, ' face up card is ', strjoin(ord(hand), ', '), '. Face down is unknown!'])
elseif length(hand) > 1
disp([player, ' cards are ', strjoin(ord(hand), ', '), '.'])
end
end
function S = sumHand(hand, dealerSoft)
hand = mod(hand - 1, 13) + 1;
hand(hand >= 10) = 10;
hand(hand == 1 ) = 11;
S = sum(hand);
while ((S > 21) && any(hand == 11))
if ~(dealerSoft && ((17 <= S) && (S <= 21)))
n = find(hand == 11, 1, 'first');
hand(n) = 1;
S = sum(hand);
end
end
end
function bj = Blackjack(player, hand)
if (length(hand) == 2) && (sumHand(hand, 0) == 21)
bj = 1;
disp([player, ' hit blackjack!'])
else
bj = 0;
end
end
function WinDrawLose(name, player, dealer)
if ((player < dealer) && (dealer <= 21)) || (player > 21)
disp([name, ' loses.'])
elseif (player == dealer)
disp([name, ' draws.'])
else
disp([name, ' wins.'])
end
end

Matlab Reversi 'valid move' check

Having issues with my move checker currently, it seems that the failsafe I put in my code to make it not look outside the bounds of the matrix isn't working, any suggestions?
There is also the issue that it doesn't seem to be working (i.e. I am still able to place pieces wherever I want!). The code I use earlier up is listed below as well
code:
function legal = legalMove()
d_l = [0, -1];
d_r = [0, 1];
d_u = [-1, 0];
d_d = [1, 0];
d_ul = [-1, -1];
d_ur = [-1, 1];
d_dl = [1, -1];
d_dr = [1, 1];
directions = {'d_l' 'd_ul' 'd_u' 'd_ur' 'd_r' 'd_dr' 'd_d' 'd_dl'};
valid_moves = zeros(8,8);
for ci = 1:8
for cj = 1:8
if game_state(ci,cj) == 0 %check element = 0
for count = 1:8
d = eval( directions{count} );
ti = ci+d(1);
tj = cj+d(2);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
% Number of enemy pieces you went over
cnt = 0;
selected = game_state(ti, tj);
% Move while going over enemy pieces
while selected == player_number * -1
ti = ti + d(1);
tj = tj + d(2);
selected = game_state(ti, tj);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
end
% Count pieces you went over
cnt = cnt + 1;
end
end
% Check if you moved over enemy pieces & whether you landed on your piece
if selected == player_number
valid_moves(ti,tj) = 1;
else
end
end
else
end
end
end
if ~isempty(valid_moves)
legal = 1;
else
legal = 0;
end
end
Error returned when done # boundries:
Attempted to access game_state(0,7); index must be a positive integer or
logical.
Error in umpire/legalMove (line 217)
selected = game_state(ti, tj);
Error in umpire/buttonPress (line 85)
legal = legalMove();
other piece:
function buttonPress(hObject, eventdata)
ended = game_is_over();
if ended == 1;
setAllInactive();
winner = calc_winner();
if winner == -1;
set(stat_text,'string','Winner is White! Restart?')
elseif winner == 1;
set(stat_text,'string','Winner is Black! Restart?')
else
set(stat_text,'string','Game is a tie! Restart?')
end
else
end
legal = legalMove();
if legal ~= 1;
set(stat_text,'Illegal move! Try again')
return
else
end
game_state(get(hObject,'userdata')) = player_number;
drawScreen();
player_number = player_number * -1;
end
In the second place where you assign variable selected (near the end of the function legalMove), you have out-of-board check in the wrong place.
Here's a fixed version
% ...
% Number of enemy pieces you went over
cnt = 0;
selected = game_state(ti, tj);
% Move while going over enemy pieces
while selected == player_number * -1
ti = ti + d(1);
tj = tj + d(2);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
end
selected = game_state(ti, tj);
% Count pieces you went over
cnt = cnt + 1;
end
end
% Check if you moved over enemy pieces & whether you landed on your piece
if selected == player_number
valid_moves(ti,tj) = 1;
else
end
end