All files / js/SnakeLogic JsGameState.ts

93.21% Statements 151/162
82.05% Branches 64/78
100% Functions 21/21
93.08% Lines 148/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                            244x 244x 244x 244x 244x 244x   244x 244x   244x         2115x 2115x 2115x 26133x           1589x 1589x       232x       735x 735x       503x       503x 508x   503x       259x                           107x 107x 1070x 1070x 10700x 10700x 32100x       107x     107x 107x     107x 107x     107x 107x 970x 970x     107x                       125x 125x   125x 125x     125x 58x   67x       125x 108x   17x       125x 4x   121x       125x 55x   70x       125x 125x 125x 125x 125x 125x 125x       125x 125x 125x 125x 125x 125x 125x 125x     125x 125x 125x 125x 125x 125x 125x 125x   125x       1375x 683x 692x         125x 125x         125x   31x 31x   31x 31x   36x 36x   27x 27x     125x       125x 125x     15x 15x     110x                 107x 107x     26x 26x     29x 29x     27x 27x     25x 25x         1732x     423x     443x     421x     445x         265x   66x   57x   76x   66x         250x   62x   54x   72x   62x         500x   124x   108x   144x   124x         244x 244x 244x   244x 244x       244x 244x       232x 232x   232x     232x   232x 15x 15x     232x 215x     232x       232x                          
import JsSnake, {Coordinate, Direction} from "./JsSnake";
 
export interface SnakeMap {
    [propName: number]: JsSnake;
}
 
/// implementation of the same logic as on the server side (but only for a single snake
/// this is useful to let it run at a higher framerate client-side (currently for demoing the autopilot)
class JsGameState {
    public readonly width: number;
    public readonly height: number;
    public food: { x: number; y: number } | null;
    public readonly snakes: SnakeMap;
 
    // properties not needed for this class but present in the server response
    public paused: boolean;
    public gameOver: boolean;
 
    private gameOverCallback?: (score: number) => void;
    private delay_ctr: number;
 
    constructor(width: number, height: number, gameOverCallback?: (score: number) => void) {
        this.width = width;
        this.height = height;
        this.food = {x: -1, y: -1};
        this.snakes = {0: new JsSnake({x: 0, y: 0})};
        this.paused = false;
        this.gameOver = false;
 
        this.gameOverCallback = gameOverCallback;
        this.delay_ctr = 0;
 
        this.reset();
    }
 
    // TODO: do something better, a hashmap or bitmap, or something
    isOccupied(site: Coordinate) {
        const {x, y} = site;
        return Object.values(this.snakes).some(
            snake => snake.tail.some(
                (site: Coordinate) => site.x === x && site.y === y
            )
        );
    }
 
    isWall(site: Coordinate) {
        const {x, y} = site;
        return x < 0 || x >= this.width || y < 0 || y >= this.height;
    }
 
    isEating(snake: JsSnake) {
        return this.food && snake.head.x === this.food.x && snake.head.y === this.food.y;
    }
 
    checkPerfectGame() {
        const occupied_fields = this.snakes[0].length + 1;  // +1 for the head
        return occupied_fields === this.width * this.height - 1; // -1 to place new food
    }
 
    randomSite() {
        Iif(this.checkPerfectGame())
            return null;
 
        let site;
        do {
            site = {x: Math.floor(Math.random() * this.width), y: Math.floor(Math.random() * this.height)};
        } while (this.isOccupied(site));
        return site;
    }
 
    add_food() {
        this.food = this.randomSite();
        // in case of a perfect game
        // if(this.food === null) {
        //     this.food = {x: -1, y: -1};
        // }
    }
 
    /// get the state of the game
    /// here we take bitmap of the field with multiple layers:
    /// first layer: 1: food, else 0
    /// second layer: 1: head of the current snake, else 0
    /// third layer: number of turns the site will be occupied by the tail of a snake
    /// this is inspired by https://towardsdatascience.com/learning-to-play-snake-at-1-million-fps-4aae8d36d2f1
    trainingBitmap() {
        let state = new Array(this.width);
        for (let i = 0; i < this.width; i++) {
            state[i] = new Array(this.height);
            for (let j = 0; j < this.width; j++) {
                state[i][j] = new Array(3);
                for (let k = 0; k < 3; k++) {
                    state[i][j][k] = 0;
                }
            }
        }
        let snake = this.snakes[0];
 
        // after a perfect game, there is no food on the field
        Eif(this.food !== null) {
            state[this.food.x][this.food.y][0] = 1;
        }
        // the head can be outside of the field (after collision with a wall)
        Eif(!this.isWall(snake.head)) {
            state[snake.head.x][snake.head.y][1] = 1;
        }
 
        let ctr = 1;
        for(let site of snake.tail) {
            state[site.x][site.y][2] = ctr;
            ctr += 1;
        }
 
        return state;
    }
 
    /// get the state of the game
    /// here we just take up to third nearest neighbor fields of the snake's head
    /// 1: snake/wall
    /// 0: free
    /// and in which direction the food is
    /// 0/1: its in front
    /// 0/1: its left
    /// 0/1: its right
    trainingState() {
        const snake = this.snakes[0];
        let state = [];
 
        const rad = this.food === null ? 0 : this.angle(snake.head, snake.headDirection, this.food);
        const eps = 1e-6;
 
        // is food in front?
        if (Math.abs(rad) < Math.PI / 2 - eps) {
            state.push(1);
        } else {
            state.push(0);
        }
 
        // is food left?
        if (rad > eps && rad < Math.PI - eps) {
            state.push(1);
        } else {
            state.push(0);
        }
 
        // is food right?
        if (rad < -eps && rad > -Math.PI + eps) {
            state.push(1);
        } else {
            state.push(0);
        }
 
        // is food behind?
        if (Math.abs(rad) > Math.PI/2. + eps) {
            state.push(1);
        } else {
            state.push(0);
        }
 
        // first neighbors
        const straight = this.next_site(snake.head, snake.headDirection);
        const left = this.next_site(snake.head, this.rLeft(snake.headDirection));
        const right = this.next_site(snake.head, this.rRight(snake.headDirection));
        const back = this.next_site(snake.head, this.back(snake.headDirection));
        state.push(this.danger(left));
        state.push(this.danger(straight));
        state.push(this.danger(right));
        // omit back, its always occupied
 
        // second neighbors
        const lb = this.next_site(left, this.back(snake.headDirection));
        const ls = this.next_site(left, snake.headDirection);
        const rs = this.next_site(right, snake.headDirection);
        const rb = this.next_site(right, this.back(snake.headDirection));
        state.push(this.danger(lb));
        state.push(this.danger(ls));
        state.push(this.danger(rs));
        state.push(this.danger(rb));
 
        // third neighbors
        const ll = this.next_site(left, this.rLeft(snake.headDirection));
        const ss = this.next_site(straight, snake.headDirection);
        const rr = this.next_site(right, this.rRight(snake.headDirection));
        const bb = this.next_site(back, this.back(snake.headDirection));
        state.push(this.danger(ll));
        state.push(this.danger(ss));
        state.push(this.danger(rr));
        state.push(this.danger(bb));
 
        return state;
    }
 
    danger(site: Coordinate) {
        if(this.isOccupied(site) || this.isWall(site))
            return 1;
        return 0;
    }
 
    angle(subject: Coordinate, direction: Direction, object: Coordinate) {
        let rad;
        const dx = object.x - subject.x;
        const dy = object.y - subject.y;
 
        // apply coordinate rotation, such that the snake always looks to the right
        // from the point of view of the atan
        // also note that our coordinate system grows down, so up points to lower values of y
        switch (direction) {
            case "right":
                rad = -Math.atan2(dy, dx);
                break;
            case "up":
                rad = Math.atan2(-dx, -dy);
                break;
            case "left":
                rad = -Math.atan2(-dy, -dx);
                break;
            case "down":
                rad = Math.atan2(dx, dy);
                break;
        }
 
        return rad;
    }
 
    relativeAction2Move(action: number) {
        const snake = this.snakes[0];
        switch(action) {
            case 0:
                // left
                snake.headDirection = this.rLeft(snake.headDirection);
                break;
            case 1:
                // straight
                break;
            case 2:
                // right
                snake.headDirection = this.rRight(snake.headDirection);
                break;
        }
    }
 
    absoluteAction2Move(action: number) {
        const snake = this.snakes[0];
        switch (action) {
            case 0:
                // north
                snake.headDirection = "up";
                break;
            case 1:
                // east
                snake.headDirection = "right";
                break;
            case 2:
                // south
                snake.headDirection = "down";
                break;
            case 3:
                // west
                snake.headDirection = "left";
                break;
        }
    }
 
    next_site(site: Coordinate, direction: Direction) {
        switch (direction) {
            case "up":
                // north
                return {x: site.x, y: site.y - 1};
            case "right":
                // east
                return {x: site.x + 1, y: site.y};
            case "down":
                // south
                return {x: site.x, y: site.y + 1};
            case "left":
                // west
                return {x: site.x - 1, y: site.y};
        }
    }
 
    rLeft(direction: Direction) {
        switch(direction) {
            case "up":
                return "left";
            case "down":
                return "right";
            case "left":
                return "down";
            case "right":
                return "up";
        }
    }
 
    rRight(direction: Direction) {
        switch(direction) {
            case "up":
                return "right";
            case "down":
                return "left";
            case "left":
                return "up";
            case "right":
                return "down";
        }
    }
 
    back(direction: Direction) {
        switch(direction) {
            case "up":
                return "down";
            case "down":
                return "up";
            case "left":
                return "right";
            case "right":
                return "left";
        }
    }
 
    reset() {
        this.snakes[0].length = 2;
        this.snakes[0].dead = false;
        this.snakes[0].tail = [];
 
        const newHead = this.randomSite();
        Iif(newHead === null) {
            throw "perfect game during reset is impossible"
        }
 
        this.snakes[0].head =  newHead;
        this.add_food();
    }
 
    update() {
        const snake = this.snakes[0];
        if(!snake.dead && !this.checkPerfectGame()) {
 
            let next = this.next_site(snake.head, snake.headDirection);
 
            // copy
            snake.tail.push({x: snake.head.x, y: snake.head.y});
 
            if (this.isEating(snake)) {
                snake.length += 1;
                this.add_food();
            }
 
            while (snake.tail.length >= snake.length + 1) {
                snake.tail.shift();
            }
 
            Iif (this.isWall(next) || this.isOccupied(next)) {
                snake.dead = true;
            }
 
            snake.head = next;
        } else E{
            this.delay_ctr += 1;
            if(this.delay_ctr >= 30) {
                const score = this.checkPerfectGame() ? this.width*this.height : snake.tail.length;
                this.gameOverCallback && this.gameOverCallback(score);
                this.reset();
                this.delay_ctr = 0;
            }
        }
    }
}
 
export default JsGameState