-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnake.ts
268 lines (214 loc) · 6.97 KB
/
Snake.ts
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core';
import { HamiltonianCylce } from './hamiltonian';
import { AstarPathFinder } from './AstartPathFinder';
import { FloodFill } from './FloodFill';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
@ViewChild('gameBoard', { static: true }) gameBoardRef!: ElementRef;
private GAME_SIZE: number = 6;
tileEnum = tileType;
public get gameBoard(): HTMLDivElement {
return this.gameBoardRef.nativeElement;
}
board: tileType[][] = [];
snake!: Point[];
food!: Point;
intervalId!: any;
lastPath!: Point[];
public static accessibleArea: [number, number][] | null = [];
public static pathgenerated = false;
private hamil: HamiltonianCylce = new HamiltonianCylce();
constructor(private renderer: Renderer2) { }
async ngOnInit(): Promise<void> {
this.initializeBoard();
this.adjustBoardSize();
this.initSnake();
await this.startGame();
this.placeFood();
}
private initializeBoard() {
this.board = [];
for (let i = 0; i < this.GAME_SIZE; i++) {
this.board[i] = [];
for (let j = 0; j < this.GAME_SIZE; j++) {
this.board[i][j] = tileType.EMPTY;
}
}
}
private adjustBoardSize() {
console.log(`Trying to resize game to fit user screen better`);
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
console.log(screenHeight, screenWidth);
const maxCellSize = Math.min(screenWidth, screenHeight) / this.GAME_SIZE;
const cells = document.querySelectorAll(".cell");
cells.forEach(cell => {
cell = cell as HTMLDivElement;
cell.setAttribute('style', `width: ${maxCellSize}px; height: ${maxCellSize}px;`);
});
}
private initSnake() {
this.snake = [{ x: 0, y: 0 }];
this.setCell(0, 0, tileType.SNAKEHEAD);
}
private placeFood() {
let x = Math.floor(Math.random() * this.GAME_SIZE);
let y = Math.floor(Math.random() * this.GAME_SIZE);
while (this.isSnakeBody(x, y)) {
x = Math.floor(Math.random() * this.GAME_SIZE);
y = Math.floor(Math.random() * this.GAME_SIZE);
}
this.food = { x: x, y: y };
this.setCell(x, y, tileType.APPLE);
}
private async startGame() {
this.intervalId = setInterval(() => {
//console.log(`Moving snake...`, Math.random() * 20);
this.moveSnake();
//const cycle: HamiltonianCylce = new HamiltonianCylce(this.board, this.snake);
//cycle.generateHamiltonianPath();
}, 100);
}
private gameOver() {
clearInterval(this.intervalId);
console.log("Game over!");
this.ngOnInit();
}
private async moveSnake() {
const head = this.snake[0];
const [x, y] = [head.x, head.y];
const [dx, dy] = await this.getDirection();
const newX = x + dx;
const newY = y + dy;
if (this.isOutOfBounds(newX, newY) || this.isSnakeBody(newX, newY)) {
this.gameOver();
return;
}
this.setCell(x, y, tileType.SNAKEBODY);
this.snake.unshift({ x: newX, y: newY });
this.setCell(newX, newY, tileType.SNAKEHEAD);
if (this.isFood(newX, newY)) {
this.eatFood();
}
const tail = this.snake.pop();
this.setCell(tail!.x, tail!.y, tileType.EMPTY);
}
private async isValidMove(x: number, y: number) {
if(x < 0 || x > this.GAME_SIZE) return false;
if(y < 0 || y > this.GAME_SIZE) return false;
if(this.snake.some(val => val.x === x && val.y === y)) return false;
return true;
}
private getRandomPoint(list: number[][]): [number, number] | null {
const validPoints: [number, number][] = [];
for(let i = 0; i < list.length; i++) {
for(let j = 0; j < list[i].length; j++) {
if(list[i][j] === 2) {
validPoints.push([i, j]);
}
}
}
if(validPoints.length === 0) {
return null;
}
return validPoints[Math.floor(Math.random() * validPoints.length)];
}
private getMove(x: number, y: number): [number, number] {
if(!TestComponent.accessibleArea) return [0 ,0];
let index = -1;
for(let e = 0; e < TestComponent.accessibleArea!.length; e++) {
if(TestComponent.accessibleArea![e][0] === x && TestComponent.accessibleArea![e][1] === y) {
index = e;
}
}
let current = [x, y];
let next = TestComponent.accessibleArea![index + 1];
if(!next) next = TestComponent.accessibleArea![0];
// //console.log(this.board);
let movement = [current[0] - next[0], current[1] - next[1]];
// //console.log(current, next, movement);
movement = [ movement[0] * -1, movement[1] * -1];
//console.log(this.accessibleArea);
//return [0, 1]; // => jobbfele
return [movement[0], movement[1]];
}
private async getDirection(): Promise<[number, number]> {
let movement: [number, number] = [0, 0];
const pathFinder: AstarPathFinder = new AstarPathFinder(this.board, this.snake);
const floodFill: FloodFill = new FloodFill(this.snake, this.food, this.GAME_SIZE);
const hamiltonian: HamiltonianCylce = new HamiltonianCylce();
if(TestComponent.pathgenerated) {
// path has been generated we can use it
let move = this.getMove(this.snake[0].x, this.snake[0].y);
movement = move;
console.log(movement);
console.log("Path GO brrrrrrrrr");
} else {
// no ham cycle we use astar for this
let path = pathFinder.findBestPath(this.snake[0], this.food);
let next = path[1];
if(!next) {
// no path no cycle wtf
console.log(`NO PATH NO CYCLE, Guess I'll just die ^.^`);
// dev stop game
clearInterval(this.intervalId);
}
console.log("Snake AI GO brrrrrrrrr");
let [snakex, snakey] = [this.snake[0].x, this.snake[0].y];
let [pathx, pathy] = [next.x, next.y];
if(snakex < pathx) {
movement[0] = 1; //right
} else if(snakex > pathx) {
movement[0] = -1; // left
} else if(snakey < pathy) {
movement[1] = 1; // down
} else if(snakey > pathy) {
movement[1] = -1; // up
}
}
return movement;
}
isOutOfBounds(x: number, y: number) {
return x < 0 || x >= this.GAME_SIZE || y < 0 || y >= this.GAME_SIZE;
}
isSnakeBody(xpos: number, ypos: number): boolean {
return this.snake.some(({ x, y }) => x === xpos && y === ypos);
}
isFood(x: number, y: number): boolean {
return this.food.x === x && this.food.y === y;
}
eatFood() {
//this.snake.push([]);
const tail = this.snake[this.snake.length - 1];
this.snake.push(tail);
//console.log(this.snake);
this.placeFood();
}
setCell(x: number, y: number, tile: tileType) {
if (!this.board[x]) {
this.board[x] = [];
}
this.board[x][y] = tile;
}
}
export enum direction {
UP,
DOWN,
LEFT,
RIGHT
}
export enum tileType {
APPLE = 3,
SNAKEHEAD = 1,
SNAKEBODY = 2,
EMPTY = 0,
}
export interface Point {
x: number,
y: number,
parent?: Point,
}