| 47 | } |
| 48 | |
| 49 | export class SnakeGame { |
| 50 | /** |
| 51 | * Constructor of SnakeGame. |
| 52 | * |
| 53 | * @param {object} args Configurations for the game. Fields include: |
| 54 | * - height {number} height of the board (positive integer). |
| 55 | * - width {number} width of the board (positive integer). |
| 56 | * - numFruits {number} number of fruits present on the screen |
| 57 | * at any given step. |
| 58 | * - initLen {number} initial length of the snake. |
| 59 | */ |
| 60 | constructor(args) { |
| 61 | if (args == null) { |
| 62 | args = {}; |
| 63 | } |
| 64 | if (args.height == null) { |
| 65 | args.height = DEFAULT_HEIGHT; |
| 66 | } |
| 67 | if (args.width == null) { |
| 68 | args.width = DEFAULT_WIDTH; |
| 69 | } |
| 70 | if (args.numFruits == null) { |
| 71 | args.numFruits = DEFAULT_NUM_FRUITS; |
| 72 | } |
| 73 | if (args.initLen == null) { |
| 74 | args.initLen = DEFAULT_INIT_LEN; |
| 75 | } |
| 76 | |
| 77 | assertPositiveInteger(args.height, 'height'); |
| 78 | assertPositiveInteger(args.width, 'width'); |
| 79 | assertPositiveInteger(args.numFruits, 'numFruits'); |
| 80 | assertPositiveInteger(args.initLen, 'initLen'); |
| 81 | |
| 82 | this.height_ = args.height; |
| 83 | this.width_ = args.width; |
| 84 | this.numFruits_ = args.numFruits; |
| 85 | this.initLen_ = args.initLen; |
| 86 | |
| 87 | this.reset(); |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Reset the state of the game. |
| 92 | * |
| 93 | * @return {object} Initial state of the game. |
| 94 | * See the documentation of `getState()` for details. |
| 95 | */ |
| 96 | reset() { |
| 97 | this.initializeSnake_(); |
| 98 | this.fruitSquares_ = null; |
| 99 | this.makeFruits_(); |
| 100 | return this.getState(); |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Perform a step of the game. |
| 105 | * |
| 106 | * @param {0 | 1 | 2 | 3} action The action to take in the current step. |
nothing calls this directly
no outgoing calls
no test coverage detected