Skip to content

Commit a44620d

Browse files
authored
Merge pull request #263 from git-aryan/master
An Automated 4-Player Snakes and Ladders game
2 parents 5a68362 + c5e559d commit a44620d

File tree

1 file changed

+115
-0
lines changed

1 file changed

+115
-0
lines changed

snek.java

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/* This is an automated game of Snakes and Ladders */
2+
3+
/* 4 Players compete on a 2-D array board
4+
5+
with 0 representing absense of snakes or Ladders
6+
7+
1 --> Snake!
8+
9+
2 --> Ladder!
10+
11+
No. of positions to be forward of backward are stored
12+
in another 2-D array which works in the background */
13+
14+
15+
16+
17+
import java.util.*;
18+
class snek
19+
{
20+
int A[][], B[][], n;
21+
snek(int n)
22+
{
23+
this.n = n;
24+
A = new int[n][n];
25+
B = new int[n][n];
26+
27+
}
28+
public static void main(String args[])
29+
{
30+
31+
Scanner sc = new Scanner(System.in);
32+
System.out.println("Enter size of board");
33+
int x = sc.nextInt();
34+
35+
snek obj = new snek(x);
36+
37+
obj.getdata();
38+
obj.winna();
39+
40+
}
41+
42+
void winna()
43+
{
44+
int winner = 0;
45+
int pos[] = {0,0,0,0};
46+
int turn[] = {0,0,0,0};
47+
int i,j;
48+
while(true)
49+
{
50+
for(i=0; i<4; i++)
51+
{
52+
if(turn[i]<0) turn[i]=0;
53+
turn[i]+= random();
54+
55+
if(turn[i]>=n*n) break;
56+
57+
pos[i] = A[turn[i]%n][turn[i]/n];
58+
59+
while(pos[i]!=0)
60+
{
61+
if(pos[i]==2)
62+
{
63+
turn[i]+=B[turn[i]%n][turn[i]/n];
64+
if(turn[i]<0||turn[i]>=n*n) break;
65+
pos[i] = A[turn[i]%n][turn[i]/n];
66+
}
67+
if(pos[i]==1)
68+
{
69+
turn[i]-=B[turn[i]%n][turn[i]/n];
70+
if(turn[i]<0||turn[i]>=n*n) break;
71+
pos[i] = A[turn[i]%n][turn[i]/n];
72+
}
73+
if(pos[i]==0) break;
74+
}
75+
}
76+
for(j=0; j<4; j++)
77+
if(turn[j]>=n*n)
78+
{
79+
winner = j;
80+
break;
81+
}
82+
if(winner!=0)
83+
break;
84+
}
85+
86+
System.out.println("Winner is Player "+winner);
87+
}
88+
89+
void getdata()
90+
{
91+
Scanner sc = new Scanner(System.in);
92+
System.out.println("Enter 0,1 and 2");
93+
for(int i=0; i<n; i++)
94+
for(int j=0; j<n; j++)
95+
A[i][j] = sc.nextInt();
96+
System.out.println("\n");
97+
System.out.println("Enter steps forw or back");
98+
for(int k=0; k<n; k++)
99+
for(int l=0; l<n; l++)
100+
B[k][l] = sc.nextInt();
101+
}
102+
int random()
103+
{
104+
Random random = new Random();
105+
int a = 0;
106+
while (true)
107+
{
108+
a = random.nextInt(7);
109+
if(a !=0)
110+
break;
111+
}
112+
return a;
113+
}
114+
115+
}

0 commit comments

Comments
 (0)