snake

mail@pastecode.io avatar
unknown
dart
2 years ago
1.2 kB
1
Indexable
Never
import 'dart:math';
import 'package:flutter/foundation.dart';

import 'game.dart';

class Snake extends GameState {
  Snake() : super() {
    // init the place where body and food at the beginning of game.
    // feel free to modify it , but don't keep it uninitialized
    // or you will get an runtime error for uninitializing. :)
    initGame();
  }

  @override
  void initGame() {
    body = [
      [0, 0]
    ];
    direction = [0, 1];
    generateFood();
  }

  void generateFood() {
    var rnd = Random();
    food = [rnd.nextInt(squarePerRows), rnd.nextInt(squarePerCols)];
  }

  void move() {
    List<int> newHead = [body[0][0] + direction[0], body[0][1] + direction[1]];
    if (listEquals(newHead, food)) {
      body.add([0, 0]);
      generateFood();
    }
    for (int i = body.length - 1; i > 0; i--) {
      body[i] = body[i - 1];
    }
    body[0] = newHead;
  }

  @override
  void updateGame() {
    move();
  }

  @override
  bool isGameOver() {
    for (var pixel in body) {
      if (pixel[0] < 0 || pixel[0] >= squarePerRows) return true;
      if (pixel[1] < 0 || pixel[1] >= squarePerCols) return true;
    }
    return false;
  }
}