Repository navigation
Expand file tree
/
Copy pathSnakeDriver.java
More file actions
executable file
·514 lines (465 loc) · 15.4 KB
/
Copy pathSnakeDriver.java
File metadata and controls
executable file
·514 lines (465 loc) · 15.4 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.awt.image.*;
import java.util.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
public class SnakeDriver{
public SnakeDriver(){
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setContentPane(new SnakePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("The Snake Game");
frame.setVisible(true);
}
}
class SnakePanel extends JPanel{
private javax.swing.Timer moveTimer;
private Snake snake;
private Thread thread;
private boolean[][] array;
private BufferedImage myImage = new BufferedImage(1218, 850, BufferedImage.TYPE_INT_RGB);
private Graphics2D myBuffer = (Graphics2D)myImage.getGraphics();
private Timer timer;
private int delay = 10;
public void newGame(){
array = new boolean[120][80];
setFocusable(true);
myBuffer.setBackground(Color.RED);
myBuffer.clearRect(0, 0, myImage.getWidth(), myImage.getHeight());
setPreferredSize(new Dimension(1218, 855));
snake.reset(array);
}
public void restart(){
this.newGame();
}
public SnakePanel(){
setPreferredSize(new Dimension(1218, 855));
array = new boolean[120][80];
snake = new Snake(myBuffer, array, delay);
thread = new Thread(snake);
setFocusable(true);
myBuffer.setBackground(Color.RED);
myBuffer.clearRect(0, 0, myImage.getWidth(), myImage.getHeight());
timer = new Timer(delay, new TimerListener());
//moveTimer.start();
timer.start();
thread.start();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
runGenetic();
}
});
t1.start();
}
private class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
synchronized (myBuffer) {
drawBoard();
myBuffer.clearRect(100, 0, 620, 10);
myBuffer.setColor(Color.BLACK);
myBuffer.drawString("Length: " + snake.length(), 100, 10);
repaint();
}
}
}
private void drawBoard(){
int x = 9;
int y = 9;
for(int i = 0; i < array.length; i++, x+=10, y = 9){
for(int j = 0; j < array[0].length; j++, y += 10){
if(array[i][j]){
myBuffer.setColor(new Color(20,240, 1));
myBuffer.fillRect(x, y, 9, 9);
}
else{
myBuffer.setColor(Color.BLUE);
myBuffer.fillRect(x, y, 10, 10);
}
}
}
myBuffer.setColor(Color.RED);
myBuffer.fillRect(9 + (snake.getPx() * 10), 9 + (snake.getPy() * 10), 10, 10);
}
public void paintComponent(Graphics g){
g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
}
private void pressEnter(){
synchronized (myBuffer) {
restart();
}
}
public void runGenetic(){
int generation = 1;
while(true){
double length = 0;
pressEnter();
long startTime = System.currentTimeMillis();
long timeSinceGrowth = startTime;
int oldLength = snake.getLength();
while (snake.getAlive()){
System.out.print("");
if(snake.length() != oldLength){
oldLength = snake.length();
timeSinceGrowth = System.currentTimeMillis();
continue;
}
if(System.currentTimeMillis() - timeSinceGrowth > 20000){
break;
}
}
length += snake.getLength();
double score = length + ((float)(System.currentTimeMillis() - startTime)/(float) (1000*6));
System.out.println("Generation " + generation + ": " + score);
System.out.println("Weights: " + Arrays.toString(snake.getWeights()));
generation += 1;
}
}
}
class Snake implements Runnable{
private boolean[][] array;
private int length = 6;
private int pX , pY;
private int headX, headY;
private Queue<Point> queue = new LinkedList<Point>();
private byte dir = 0; //0 = up, 1 = right, 2 = down, 3 = left
private LinkedList<Byte> moveQueue;
private boolean movedSinceLast = true;
private Timer snakeTimer;
private int boardWidth;
private int boardHeight;
private double rewardToGive;
private boolean alive;
Brain curBrain;
public Double[] getWeights(){
return curBrain.getWeights();
}
public Snake(Graphics2D g, boolean[][] a, int delay){
this.moveQueue = new LinkedList<Byte>();
this.array = a;
this.snakeTimer = new Timer(delay, new SnakeListener());
this.boardWidth = this.array.length;
this.boardHeight = this.array[0].length;
pX = (int)(Math.random() * array.length);
pY = (int)(Math.random() * array[0].length);
this.alive = false;
add(60, 60);
add(60, 59);
add(60, 58);
add(60, 57);
add(60, 56);
add(60, 55);
makePrize();
rewardToGive = -1;
curBrain = new Brain();
}
public void reset(boolean[][] a){
this.dir = 0;
this.moveQueue = new LinkedList<Byte>();
this.queue.clear();
this.array = a;
pX = (int)(Math.random() * array.length);
pY = (int)(Math.random() * array[0].length);
add(60, 60);
add(60, 59);
add(60, 58);
add(60, 57);
add(60, 56);
add(60, 55);
makePrize();
this.length = 6;
this.run();
}
public int length(){
return length;
}
public int getPx(){
return pX;
}
public int getPy(){
return pY;
}
private void makePrize(){
pX = (int)(Math.random() * array.length);
pY = (int)(Math.random() * array[0].length);
}
public byte getDir(){
return dir;
}
private void add(int x, int y){
this.add(new Point(x, y));
}
private void add(Point p){
queue.add(p);
int x = p.x;
int y = p.y;
if(x < 0 || y < 0 || x >= this.boardWidth || y >= this.boardHeight){
snakeTimer.stop();
this.alive = false;
rewardToGive = -1000;
return;
}
headX = x;
headY = y;
if(array[x][y] && !queue.peek().equals(new Point(x, y))){
snakeTimer.stop();
this.alive = false;
rewardToGive = -1000;
return;
}
array[x][y] = true;
rewardToGive = -1;
}
private void remove(Point p){
int x = p.x;
int y = p.y;
array[x][y] = false;
}
public void updateWeights(double rewardToGive, double oldQsa, Double[] oldFeatureVector){
curBrain.updateWeights(this, rewardToGive, oldQsa, oldFeatureVector);
}
private class SnakeListener implements ActionListener{
public void actionPerformed(ActionEvent e){
double oldQsa = 0;
Double[] oldFeatureVector = null;
if(Snake.this.getAlive() && curBrain != null) {
Tuple tup = curBrain.nextMove(Snake.this);
dir = tup.action;
oldQsa = tup.value;
oldFeatureVector = tup.featureVector;
}
else{
return;
}
if(oldFeatureVector == null){
System.out.println("THIS IS A PROBLEM!");
}
if(dir == 0){
headY--;
add(new Point(headX, headY));
}
else if(dir == 1){
headX++;
add(new Point(headX, headY));
}
else if(dir == 2){
headY++;
add(new Point(headX, headY));
}
else{
headX--;
add(new Point(headX, headY));
}
if(headX == pX && headY == pY){
length += 6;
rewardToGive = 50;
makePrize();
}
if(queue.size() > (length)){
remove(queue.poll());
try {
array[headX][headY] = true;
}
catch (ArrayIndexOutOfBoundsException fldsj){
}
}
Snake.this.updateWeights(rewardToGive, oldQsa, oldFeatureVector);
rewardToGive = -1;
}
}
public void run(){
snakeTimer.start();
this.alive = true;
}
public boolean[][] getArray(){
return this.array;
}
public int getHeadX(){
return this.headX;
}
public int getHeadY(){
return this.headY;
}
public int getBoardWidth(){
return this.boardWidth;
}
public int getBoardHeight(){
return this.boardHeight;
}
public boolean getAlive(){
return this.alive;
}
public int getLength(){
return this.length;
}
}
class Tuple{
public byte action;
public double value;
public Double[] featureVector;
public Tuple(byte a, double v, Double[] vec){
this.action = a;
this.value = v;
this.featureVector = vec;
}
}
class Brain{
private Random random;
private long rseed;
private Double[] weights;
private int weightsSize = 3;
private double gamma;
private double alpha;
public Double[] getWeights(){
return weights;
}
public Brain(){
this.rseed = 724917;
this.random = new Random(this.rseed);
weights = new Double[weightsSize];
initializeWeights();
gamma = 0.99;
alpha = 0.1;
}
private void initializeWeights(){
for(int i = 0; i < weightsSize; i++){
weights[i] = (random.nextDouble()*2)-1;
}
}
private Double[] calculateFeatureVector(Snake snake, byte action){
boolean[][] array = snake.getArray();
double dir = (int)snake.getDir();
double northDistance = (double)(findDistance(snake, 0, array) - (action == 0 ? 1 : 0))/snake.getBoardHeight() ;
double eastDistance = (double)(findDistance(snake, 1, array) - (action == 1 ? 1 : 0))/snake.getBoardWidth() ;
double southDistance = (double)(findDistance(snake, 2, array) - (action == 2 ? 1 : 0))/snake.getBoardHeight() ;
double westDistance =(double)(findDistance(snake, 3, array) - (action == 3 ? 1 : 0))/snake.getBoardWidth();
/*double northDistance = (findDistance(snake, 0, array) - (action == 0 ? 1 : 0)) <= 0 ? 1 : 0;
double eastDistance = (findDistance(snake, 1, array) - (action == 1 ? 1 : 0)) <= 0 ? 1 : 0;
double southDistance = (findDistance(snake, 2, array) - (action == 2 ? 1 : 0)) <= 0 ? 1 : 0;
double westDistance = (findDistance(snake, 3, array) - (action == 3 ? 1 : 0)) <= 0 ? 1 : 0;
*/
double dirDistance = (findDistance(snake, action, array) - 1) < 0 ? 1 : 0;
int headX = snake.getHeadX();
int headY = snake.getHeadY();
if(action == 0){
headY--;
}
else if(action == 1){
headX++;
}
else if(action == 2){
headY++;
}
else if(action == 3){
headX--;
}
double horizontalDist = (double)Math.abs(snake.getPx() - headX)/snake.getBoardWidth();
double verticalDist = (double)Math.abs(snake.getPy() - headY)/snake.getBoardHeight();
//Double[] featureVector = {dirDistance, northDistance, eastDistance, southDistance, westDistance, horizontalDist, verticalDist};
Double[] featureVector = {dirDistance, horizontalDist, verticalDist};
return featureVector;
}
public Tuple nextMove(Snake snake){
// return action for which Q(s, a) reaches a maximum
double maxVal = -999999999;
byte maxAction = 0;
Double[] maxFeatureVector = null;
for(int action = 0; action < 4; action++){
Double[] featureVector = calculateFeatureVector(snake, (byte)action);
double qsa = 0;
for(int i = 0; i < weightsSize; i++){
qsa += weights[i]*featureVector[i];
}
double curVal = qsa;
if(curVal > maxVal){
maxAction = (byte)action;
maxVal = curVal;
maxFeatureVector = featureVector;
}
}
if(maxFeatureVector == null){
System.out.println("WHAT THE FUCK");
System.exit(0);
}
return new Tuple(maxAction, maxVal, maxFeatureVector);
}
public void updateWeights(Snake snake, double rewardToGive, double oldQsa, Double[] oldFeatureVector){
Tuple subsequentMove = nextMove(snake);
double qsaprime = subsequentMove.value;
double difference = (rewardToGive + (gamma*qsaprime)) - oldQsa;
for(int i = 0; i < this.weights.length; i++){
if(oldFeatureVector == null){
System.out.println("subsequentMove was null");
}
this.weights[i] += this.alpha * difference * oldFeatureVector[i];
}
//normalizeWeights();
}
private void normalizeWeights(){
double sum = 0;
for(int i = 0; i < this.weights.length; i++){
sum += this.weights[i];
}
for(int i = 0; i < this.weights.length; i++){
this.weights[i] /= sum;
}
}
private int findDistance(Snake snake, int dir, boolean[][] array){
// change array to be of longs rather than bools
try{
if(dir == 0){
int counter = 0;
int curX = snake.getHeadX();
int curY = snake.getHeadY()-1;
while(curY >= 0 && array[curX][curY] == false){
curY -= 1;
counter++;
}
return counter;
}
else if(dir == 1){
int counter = 0;
int curX = snake.getHeadX()+1;
int curY = snake.getHeadY();
while(curX < snake.getBoardWidth() && array[curX][curY] == false){
curX += 1;
counter++;
}
return counter;
}
else if(dir == 2) {
int counter = 0;
int curX = snake.getHeadX();
int curY = snake.getHeadY()+1;
while(curY < snake.getBoardHeight() && array[curX][curY] == false){
curY += 1;
counter++;
}
return counter;
}
else{
int counter = 0;
int curX = snake.getHeadX()-1;
int curY = snake.getHeadY();
while(curX >= 0 && array[curX][curY] == false){
curX -= 1;
counter++;
}
return counter;
}
}
catch(Exception e){
return 0;
}
}
}