-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
tic_tac_toe.m
92 lines (77 loc) · 2.08 KB
/
tic_tac_toe.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
% Author: Syed Haseeb Shah (QuantumNovice)
%Simple Tic Tac Toe
% Creates a row vector
space = 1:9;
% Converts it into matrix
space = reshape(space,[3,3]);
space = string(space);
marker = 'O';
reset = 0;
changes = 0;
for r = 1:3
disp( space(r,1) + " | " + space(r,2) + " | " +space(r,3) )
disp(' | |')
disp( '___________________')
end
while reset ~= 1
pos = input( char("Player ("+marker+")<< "));
if and(space(pos) ~= 'O', space(pos) ~= 'X')
space(pos) = marker;
changes = 1;
end
clc
% Win Check
for i = 1:3
% If rows are similaroz
if or(sum(space(i, :) == ["X","X","X"]) == 3, sum(space(i, :) == ["O","O","O"]) == 3)
disp("Player "+marker+" Wins")
reset = 1;
break
end
% If cols are similar
if or(sum(space(:, i) == ["X";"X";"X"]) == 3, sum(space(:, i) == ["O";"O";"O"]) == 3)
disp("Player "+marker+" Wins")
reset = 1;
break
end
% main diagonal
if and(space(1,1) == space(2,2), space(2,2) == space(3,3))
disp("Player "+marker+" Wins")
reset = 1;
break
end
% cross diagonal
if and(space(1,3) == space(2,2), space(2,2) == space(3,1))
disp("Player "+marker+" Wins")
reset = 1;
break
end
end
% Game Draw
count = 0;
for elm = 1:9
if or(space(elm) == "X", space(elm) == "O")
count = count + 1;
end
if count == 9
disp ("Game Draw")
reset = 1;
break
end
end
for r = 1:3
disp( space(r,1) + " | " + space(r,2) + " | " +space(r,3) )
disp(' | |')
disp( '___________________')
end
% Make sure previous positions are loocked
if changes == 1
switch marker
case "X"
marker = "O";
case "O"
marker = "X";
changes = 0;
end
end
end