-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.java
More file actions
99 lines (86 loc) · 2.64 KB
/
Copy pathSnake.java
File metadata and controls
99 lines (86 loc) · 2.64 KB
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
import java.util.*;
public class Snake {
static int width;
static int height;
static boolean gameover=false;
static int foodx;
static int foody;
static Random rand = new Random();
static List<int[]> snake=new ArrayList<>();
static int dx = 1;
static int dy = 0;
static int score=0;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter board width");
width=sc.nextInt();
System.out.println("Enter board height");
height=sc.nextInt();
foodx =rand.nextInt(width);
foody=rand.nextInt(height);
int sy=height/2;
int sx=width/2;
snake.add(new int[]{sy,sx});
while (!gameover) {
drawBoard();
System.out.print("Move (u/d/l/r): ");
String input = sc.nextLine();
if (input.equals("u")) {
dx=0;
dy=-1;}
if (input.equals("d")) {
dx=0;
dy=1;
}
if (input.equals("l")) {
dx=-1;
dy=0;
}
if (input.equals("r")){
dx=1;
dy=0;}
int head[]=snake.get(0);
int newx=head[1]+dx;
int newy=head[0]+dy;
for(int[] part : snake){
if(part[0]==newy && part[1]==newx)
{gameover=true;
}}
snake.add(0,new int[]{newy,newx});
if(newx<0||newx>=width||newy<0||newy>=height)
{ gameover=true;}
if(newx==foodx && newy==foody)
{ score++;
do {foodx =rand.nextInt(width);
foody=rand.nextInt(height);
}while(foodx==sx && foody==sy);
} else
snake.remove(snake.size()-1);}
System.out.print("Game over");
}
static void drawBoard() {
// Clear screen
System.out.print("\033[H\033[2J");
System.out.flush();
System.out.println("Score"+score);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
boolean printed = false;
for (int[] part : snake) {
if (part[0] == i && part[1] == j) {
System.out.print("O ");
printed = true;
break;
}
}
if (!printed) {
if (i == foody && j == foodx) {
System.out.print("X ");
} else {
System.out.print(". ");
}
}
}
System.out.println();
}
}}