-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.c
119 lines (104 loc) · 2.25 KB
/
main.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include<stdio.h>
void fillSrc();
void displaylevel(int level);
void display();
void push(int x);
int pop();
int gameWinCondition();
struct pole
{
int stack[3];
};
struct pole p[3];
int top[3];
void main()
{
top[2] = top [1] = -1;
int win = 0;
int x;
fillSrc();
display();
printf("Tower of Hanoi\n");
printf("Objective: Your goal is to insert the numbers into the third pole such that from top to bottom, they are in ascending order\n");
printf("Rule: You cannot put an greater number above a smaller number at any point in the game\n");
printf("Good luck!\n");
while(win != 1) {
x = pop();
push(x);
win = gameWinCondition();
display();
}
printf("Congratulations, you win!\n");
}
//fill the source pole according to the number of disks
void fillSrc()
{
p[0].stack[0] = 3;
p[0].stack[1] = 2;
p[0].stack[2] = 1;
top[0] = 2;
}
//push to stack
void push(int x)
{
int pl;
chooseWhereToPush:
printf("Choose pole to push to: ");
scanf("%d", &pl);
printf("\n");
if(p[pl].stack[top[pl]] > x || p[pl].stack[top[pl]]==0) {
top[pl]++;
p[pl].stack[top[pl]] = x;
}
else {
printf("Cannot push here. Try again.\n");
goto chooseWhereToPush;
}
}
int pop() {
int pl, x;
chooseWhereToPop:
printf("Choose pole to pop from: ");
scanf("%d", &pl);
printf("\n");
if(p[pl].stack[top[pl]] == -1) {
printf("Pole empty, cannot pop. Try again.\n");
goto chooseWhereToPop;
}
x = p[pl].stack[top[pl]];
p[pl].stack[top[pl]] = 99;
top[pl]--;
return x;
}
//printing a single level (function is called by display())
void displaylevel(int level)
{
int i;
for(i=0; i<3; i++)
{
if(p[i].stack[level] == 99 || p[i].stack[level] == 0) {
printf("[ ]\t");
}
else {
printf("[%d]\t",p[i].stack[level]);
}
}
printf("\n");
}
//printing the stacks by calling displaylevel()
void display()
{
int i;
for(i=2; i>=0; i--)
{
displaylevel(i);
}
}
int gameWinCondition() {
if(p[2].stack[0]==3 && p[2].stack[1]==2 && p[2].stack[2]==1) {
return 1;
}
else {
return 0;
}
}