jhlywa / chess.js

A TypeScript chess library for chess move generation/validation, piece placement/movement, and check/checkmate/draw detection
BSD 2-Clause "Simplified" License
3.73k stars 892 forks source link

Chess Puzzle function, white move is always null? #173

Closed MitchellWeg closed 6 years ago

MitchellWeg commented 6 years ago

I have a section on my Laravel website where the user can make some chess puzzle.

The function I wrote works for the black pieces, however when the user is white, every move made is always null and ChessJS just resets the position.....

My code:

@extends('layouts.app')

@section('content')

<div class='container'>
    <div class='row'>
        <h3>{{$puzzle->Players}}</h3>
    </div>  

    <div class='row'>

        <div id='board' style='width: 600px;'></div>
    </div>
</div>  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="{{ asset('../chess_engine/js/chessboard-0.3.0.min.js')}}"></script>
<script src="{{ asset('../chess_engine/js/chessboard-0.3.0.js')}}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js"></script>
<link rel="stylesheet" href="/chess_engine/css/chessboard-0.3.0.css">

<script>
  var count = 0; // Int so we can track on which move we are.
</script>

<script>
    var fen_position = "{{$puzzle->Position}}";  
    var solution_raw = "{{$puzzle->Solution}}";

    var solutionArr = solution_raw.split(" ");
    var solution = [];

    function isLetter(str) {
      return str.length === 1 && str.match(/[a-z]/i);
    }

    for(var i = 0; i < solutionArr.length; i++)
    {
        if(isLetter(solutionArr[i][0]))
        {
          solution += solutionArr[i] + " ";
        }
    }

    solution = solution.split(" ");
    console.log(solution);
</script>

<script>

  function pieceTheme(piece) {
  // wikipedia theme for white pieces
  if (piece.search(/w/) !== -1) {
    return '/chess_engine/img/chesspieces/wikipedia/' + piece + '.png';
    }

      return '/chess_engine/img/chesspieces/wikipedia/' + piece + '.png';
  }

var board,
  game = new Chess(),
  statusEl = $('#status'),
  fenEl = $('#fen'),
  pgnEl = $('#pgn');

  game.load(fen_position);
  console.log(game.turn());

// do not pick up pieces if the game is over
// only pick up pieces for the side to move
var onDragStart = function(source, piece, position, orientation) {
  if (game.game_over() === true ||
      (game.turn() === 'w' && piece.search(/^b/) !== -1) ||
      (game.turn() === 'b' && piece.search(/^w/) !== -1)) {
    return false;
  }
};

//
// This function triggers when the player
// releases a piece.
//
var onDrop = function(source, target) {

  var move = game.move({
    from: source,
    to: target
  });

  console.log(move);

  // The moves in the solution are written in "Standard Algebraic Notation",
  // Luckily, ChessJS provides a function that converts the moves played to SAN.

  // Check if the move played is the same as the solution.
  if(move.san === solution[count])
  {
    // The move played is correct.

    count++; // Increase the count by 1.
    game.move(solution[count]); // Play the next move in the solution array.
    count++; // Increase the count again, so we get the move after the opponents move.

    fen_position = game.fen(); // Store the current position.
  }
  else    
  {
    // The move played is incorrect.

    // Reset by loading the previous position.
    // Snapback for some reason doesn't work properly here...
    game.load(fen_position);
    return 'snapback';
  }
};

// update the board position after the piece snap 
// for castling, en passant, pawn promotion
var onSnapEnd = function() {
  board.position(game.fen());
};

var updateStatus = function() {
  var status = '';

  var moveColor = 'White';
  if (game.turn() === 'b') {
    moveColor = 'Black';
  }

  // checkmate?
  if (game.in_checkmate() === true) {
    status = 'Game over, ' + moveColor + ' is in checkmate.';
  }

  // draw?
  else if (game.in_draw() === true) {
    status = 'Game over, drawn position';
  }

  // game still on
  else {
    status = moveColor + ' to move';

    // check?
    if (game.in_check() === true) {
      status += ', ' + moveColor + ' is in check';
    }
  }

  statusEl.html(status);
  fenEl.html(game.fen());
  pgnEl.html(game.pgn());
};

var cfg = {
  pieceTheme: pieceTheme,
  draggable: true,
  position: fen_position, 
  onDragStart: onDragStart,
  onDrop: onDrop,
  onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

updateStatus();

</script>

@endsection
jhlywa commented 6 years ago

What's the value of fen_position?

MitchellWeg commented 6 years ago

r3k2r/ppp2Npp/1b5n/4p2b/2B1P2q/BQP2P2/P5PP/RN5K w kq - 1 0

I'm retrieving all my puzzle Fen-strings from a database.

  1. Bb5+ c6 2. Qe6+ Qe7 3. Qxe7#

This is the solution array.

jhlywa commented 6 years ago

Your FEN is invalid, it should be: r3k2r/ppp2Npp/1b5n/4p2b/2B1P2q/BQP2P2/P5PP/RN5K w kq - 0 1