Skip to content
Snippets Groups Projects
Select Git revision
  • 593b58a00405509833bd280369d402f50adc17a2
  • master default protected
  • 84-improve-app-metadata
  • 82-fix-colors
  • 23-add-timer
  • 65-update-icons
  • Release_0.10.1_88 protected
  • Release_0.10.0_87 protected
  • Release_0.9.2_86 protected
  • Release_0.9.1_85 protected
  • Release_0.9.0_84 protected
  • Release_0.8.0_83 protected
  • Release_0.7.0_82 protected
  • Release_0.6.0_81 protected
  • Release_0.5.2_80 protected
  • Release_0.5.1_79 protected
  • Release_0.5.0_78 protected
  • Release_0.4.1_77 protected
  • Release_0.4.0_76 protected
  • Release_0.3.1_75 protected
  • Release_0.3.0_74 protected
  • Release_0.2.1_73 protected
  • Release_0.2.0_72 protected
  • Release_0.1.22_71 protected
  • Release_0.1.21_70 protected
  • Release_0.1.20_69 protected
26 results

board_utils.dart

Blame
  • cpu.dart 2.78 KiB
    import 'dart:math';
    
    import 'board.dart';
    import 'coordinate.dart';
    import 'match_page.dart';
    
    abstract class Cpu {
      final Color color;
      final Random _random = Random(DateTime.now().millisecond);
    
      Cpu(this.color);
    
      Color get otherPlayer => color == Color.RED ? Color.YELLOW : Color.RED;
    
      Future<int> chooseCol(Board board);
    }
    
    class DumbCpu extends Cpu {
      DumbCpu(Color player) : super(player);
    
      Color get otherPlayer => color == Color.RED ? Color.YELLOW : Color.RED;
    
      @override
      Future<int> chooseCol(Board board) async {
        await Future.delayed(Duration(seconds: _random.nextInt(2)));
        int col = _random.nextInt(7);
    
        return col;
      }
    
      @override
      String toString() => 'DUMB CPU';
    }
    
    class HarderCpu extends Cpu {
      HarderCpu(Color player) : super(player);
    
      @override
      Future<int> chooseCol(Board board) async {
        final List<double> scores = List.filled(7, 0);
    
        await Future.delayed(Duration(seconds: 1 + _random.nextInt(2)));
        return _compute(board, 0, 1, scores);
      }
    
      int _compute(Board board, int step, int deepness, List<double> scores) {
        for (var i = 0; i < 7; ++i) {
          final boardCopy = board.clone();
    
          final target = boardCopy.getColumnTarget(i);
          if (target == -1) {
            scores[i] = null;
            continue;
          }
    
          final coordinate = Coordinate(i, target);
    
          boardCopy.setBox(coordinate, color);
          if (boardCopy.checkWinner(coordinate, color)) {
            scores[i] += deepness / (step + 1);
            continue;
          }
    
          for (var j = 0; j < 7; ++j) {
            final target = boardCopy.getColumnTarget(j);
            if (target == -1) {
              continue;
            }
    
            final coordinate = Coordinate(j, target);