-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
229 lines (213 loc) · 6.14 KB
/
sketch.js
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
let snakes = [];
let old_gen = [];
var foods = [];
const NUMBER_OF_SNAKES = 1000;
const LEARNING_RATE = 0.1;
const MUTATE_RATE= 0.3;
const GRID_SIZE = 5;
const CANVAS_SIZE = 600;
const FOOD_HEALTH = 40;
const speed = 15; // Should be divide 60
const NUMBER_OF_FOODS = CANVAS_SIZE / 20;
let INITIAL_HEALTH = (CANVAS_SIZE*10)/(NUMBER_OF_FOODS*GRID_SIZE);
var bestSnake;
var showSnakes = true;
var showPipes = true;
var score;
var highScore;
var generation = 0;
var gameSpeed = 1;
var isTraining = false;
function setup() {
score = 0;
highScore = 0;
createCanvas(CANVAS_SIZE, CANVAS_SIZE);
for (let i =0; i< NUMBER_OF_SNAKES; i++){
snakes.push(new Snake());
}
for (let i = 0; i < NUMBER_OF_FOODS; i++) {
foods.push(new Food());
}
// foods.push(new food());
playBestButton = createButton('Play the best snake so far');
playBestButton.position(5, CANVAS_SIZE+5);
playBestButton.mousePressed(()=> {playSnake(bestSnake)});
showSnakesButton = createButton("Show Snakes");
showPipesButton = createButton("Show foods");
showSnakesButton.position(5, CANVAS_SIZE+30);
showPipesButton.position(5, CANVAS_SIZE+50);
showSnakesButton.mousePressed(()=> {showSnakes = !showSnakes});
showPipesButton.mousePressed(()=> {showPipes = !showPipes});
speedSlider = createSlider(1, 100, 1);
speedSlider.position(100, CANVAS_SIZE+80);
trainButton = createButton("Train");
trainButton.position(5, CANVAS_SIZE+80);
trainButton.mousePressed(()=> {isTraining = !isTraining; gameSpeed = speedSlider.value(); train()});
saveCurrentSnakeButton = createButton("Save the current snake");
saveCurrentSnakeButton.position(5, CANVAS_SIZE+120);
saveCurrentSnakeButton.mousePressed(() => {
saveSnake(snakes[0]);
});
saveBestSnakeButton = createButton("Save the best snake");
saveBestSnakeButton.position(140, CANVAS_SIZE+120);
saveBestSnakeButton.mousePressed(() => {
saveSnake(bestSnake);
});
input = createFileInput(handleFile);
input.position(300, CANVAS_SIZE + 120);
}
function gameLoop(){
score+=1;
if (score > highScore) {
bestSnake = snakes[0]; // ?
}
for (snake of snakes) {
snake.health -= 1;
snake.isOffScreen();
if (snake.health < 1) {
old_gen.push(snakes.splice(snakes.indexOf(snake), 1)[0]);
}
}
if (snakes.length == 0) {
restart();
return;
}
for (food of foods) {
for (snake of snakes) {
if (food.hits(snake)) {
snake.size += 1;
snake.health += FOOD_HEALTH;
foods.splice(foods.indexOf(food), 1);
foods.push(new Food());
}
}
}
for (snake of snakes) {
snake.score+=1;
snake.think(foods);
snake.update();
// }
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function train(){
while(isTraining){
for(let i =0 ; i<gameSpeed; i++){
gameLoop();
}
await sleep(1);
}
}
function draw() {
if(frameCount%(60/speed) == 0) {
background(0);
if(!isTraining){
//gameSpeed = speedSlider.value();
score += 1;
if (score > highScore) {
bestSnake = snakes[0]; // ?
}
for (snake of snakes) {
snake.health -= 1;
snake.isOffScreen();
if (snake.health < 1) {
old_gen.push(snakes.splice(snakes.indexOf(snake), 1)[0]);
}
}
if (snakes.length == 0) {
restart();
return;
}
for (food of foods) {
if (showPipes) {
food.show();
}
for (snake of snakes) {
if (food.hits(snake)) {
snake.size += 1;
snake.health += FOOD_HEALTH;
foods.splice(foods.indexOf(food), 1);
foods.push(new Food());
}
}
}
for (snake of snakes) {
snake.score+=1;
snake.think(foods);
snake.update();
if(showSnakes){
snake.show();
}
// }
}
}
let s = `Score : ${score}\nHighScore : ${highScore}\nGeneration : ${generation}`;
fill(255);
text(s, 10, 10, 100, 80);
let speedText = `Speed : x${gameSpeed}`;
text(speedText, CANVAS_SIZE-80, CANVAS_SIZE-30, 100, 80);
}
}
function keyPressed() {
console.log("keyPressed",snakes[0].x,snakes[0].y);
if (keyCode === LEFT_ARROW) {
// console.log("Space pressed;")
snakes[0].changeDirection("n");
}
else if(keyCode === RIGHT_ARROW){
snakes[0].changeDirection("c");
}
}
function restart() {
snakes = [];
foods = [];
nextGeneration();
generation+=1;
if(score> highScore) {
highScore = score;
}
INITIAL_HEALTH -= generation/50
let limit = (CANVAS_SIZE)/(NUMBER_OF_FOODS*GRID_SIZE);
if(INITIAL_HEALTH < limit) {
INITIAL_HEALTH = limit;
}
score = 0;
}
function playSnake(snake){
for(snake of snakes) {
old_gen.push(snake);
}
snakes = [snake];
}
function handleFile(file){
//console.log(file);
var snake = JSON.parse(atob(file.data.split(",")[1]));
var newSnake = new Snake();
newSnake.replaceBrain(snake.brain);
snakes = [newSnake];
}
function saveSnake(snake){
// var data = JSON.stringify(snake);
// var filename="snake.json";
// var type = "json";
// var file = new Blob([data], { type: type });
// if (window.navigator.msSaveOrOpenBlob)
// // IE10+
// window.navigator.msSaveOrOpenBlob(file, filename);
// else {
// // Others
// var a = document.createElement("a"),
// url = URL.createObjectURL(file);
// a.href = url;
// a.download = filename;
// document.body.appendChild(a);
// a.click();
// setTimeout(function() {
// document.body.removeChild(a);
// window.URL.revokeObjectURL(url);
// }, 0);
// }
saveJSON(snake,"snake.json");
}