Giter Site home page Giter Site logo

lichess-org / chessground Goto Github PK

View Code? Open in Web Editor NEW
989.0 37.0 254.0 11.04 MB

Mobile/Web chess UI for lichess.org

Home Page: https://lichess.org

License: GNU General Public License v3.0

TypeScript 92.03% Shell 0.27% CSS 5.24% HTML 2.46%
lichess chess ui typescript board

chessground's Introduction

Chessground

Continuous Integration npm

Chessground in 2D and 3D

Chessground is a free/libre open source chess UI developed for lichess.org. It targets modern browsers, as well as mobile development using Cordova.

License

Chessground is distributed under the GPL-3.0 license (or any later version, at your option). When you use Chessground for your website, your combined work may be distributed only under the GPL. You must release your source code to the users of your website.

Please read more about GPL for JavaScript on greendrake.info.

Demos

Features

Chessground is designed to fulfill all lichess.org web and mobile apps needs, so it is pretty featureful.

  • Well typed with TypeScript
  • Fast. Uses a custom DOM diff algorithm to reduce DOM writes to the absolute minimum.
  • Small footprint: 10K gzipped (31K unzipped). No dependencies.
  • SVG drawing of circles, arrows, and custom user shapes on the board
  • Arrows snap to valid moves. Freehand arrows can be drawn by dragging the mouse off the board and back while drawing an arrow.
  • Entirely configurable and reconfigurable at any time
  • Styling with CSS only: board and pieces can be changed by simply switching a class
  • Fluid layout: board can be resized at any time
  • Support for 3D pieces and boards
  • Full mobile support (touchstart, touchmove, touchend)
  • Move pieces by click
  • Move pieces by drag & drop
    • Minimum distance before drag
    • Centralisation of the piece under the cursor
    • Piece ghost element
    • Drop off revert or trash
  • Premove by click or drag
  • Drag new pieces onto the board (editor, Crazyhouse)
  • Animation of pieces: moving and fading away
  • Display last move, check, move destinations, and premove destinations (hover effects possible)
  • Import and export positions in FEN notation
  • User callbacks
  • No chess logic inside: can be used for chess variants

Installation

npm install --save chessground

Usage

import { Chessground } from 'chessground';

const config = {};
const ground = Chessground(document.body, config);

Wrappers

More? Please make a pull request to include it here.

Documentation

Development

Install build dependencies:

pnpm install

To build the node module:

pnpm run compile --watch

To build the standalone:

pnpm run dist

chessground's People

Contributors

370417 avatar as-f avatar benediktwerner avatar brandone avatar chiller2020 avatar d10n avatar dependabot[bot] avatar fitztrev avatar flugsio avatar geodic avatar gtim avatar gtm-nayan avatar hi-ogawa avatar isaacl avatar leodog896 avatar linrock avatar melgrove avatar niklasf avatar ornicar avatar pnodet avatar qwerty084 avatar romnzs avatar ruhibloodworth avatar schlawg avatar srimethan avatar stilllearnin avatar topce avatar trufa avatar veloce avatar zevaverbach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chessground's Issues

JS builds?

Are there any JS compiled builds of this anywhere? Can someone create one and shove it in the latest release? I don't want to have to have a NodeJS env just to use this library :)

how to reach same as lichess/analysis with chess960?

Hi,
i have no idea for scala / and lila is quiet complex.

Now:
I changed the chess.js code so, it works for chess960, and i follow the example files with "playOtherSide".
But i cant get a castle correctly. If i have a bKd8, bRb8, and i click on the d8 square, i get c8 enlighted, but it will then make Kc8, not 0-0-0. On lichess the b8 square also shown as "capture", and lateron 0-0-0.

How to reach this?
I mean, how do i change which squares are possible, when a user clicks on a square, and then lateron move it?

Compatibility with React

Hi @ornicar, just a quick question: Would chessground be easily usable with React, given that the virtual DOM for chessground is managed independently?

config.items not works

Hello.

I tried to find a way how to add some custom items into the board. As I understand we have config.items for this. But the usage of this option is broken at the moment. Actually I do not see how we handle this option in the latest version of chessground.

BTW Liches successfully uses this option on https://lichess.org/learn. But 'learn' section uses github:ornicar/chessground#v4.4.0. I.e. older version. And v4 has some special code which handles config.items option https://github.com/ornicar/chessground/blob/v4/src/view.js#L170. The latest version of chessground do not have the same kind code.

Likely bug with chessground.set(options)

Unless I'm misunderstanding the docs, I should be able to call chessground.set({turnColor: 'white'}) on black's turn, and black will no longer be able to drag pieces, and white will, correct?

I'm trying to do this in a toy bughouse implementation I'm working on (after I've added a dropped piece programmatically), and black remains the color in control, though it breaks the actual move completion, so either I'm doing it wrong, or that command is setting the board to an inconsistent state where only part of the board understand's which color is next to move. Let me know if you need any more details or have trouble reproducing etc!

square highlighting isn't perfectly aligned

It's more obvious with the grey premove overlay, but visible for green move highlights too. In screenshot below, the green move highlight is not quite even with the bottom of d5.

My board zoom is at about 1/5 of the slider.

image

Problems with "npm" & "mithril"

Hi,
when i try to install the code (following the docu), i get an error concerning mithril

npm ERR! Error: No compatible version found: mithril@'github:ornicar/mithril.js#v0.2.0'
npm ERR! Valid install targets:
npm ERR! ["0.1.2","0.1.3","0.1.4","0.1.12","0.1.13","0.1.0","0.1.16","0.1.17","0.1.18","0.1.19","0.1.20","0.1.21","0.1.22","0.1.23","0.1.24","0.1.25","0.1.26","0.1.27","0.1.28","0.1.29","0.1.30","0.1.31","0.1.32","0.1.33","0.1.34-beta.0","0.1.34","0.2.0"]

btw: i changed package.json from 1.0.0 to 0.2.0 but it doesnt work either way.
Not using npm at all, so please help what to do.
Thanks

Setting the board style and 3d pieces

Hi, sorry this might not be an issue but I'm struggling to find out how to set the board style to anything other than default, is there a class I need to add to change my board to the blue one shown in the chessground banner? Thanks

Highlight target during drag

UI idea: highlight target square during a drag so it’s more obvious where the piece will drop (for example if the drag is just slightly over one square)

Drawing text labels on top of chessground

Hi @ornicar, thanks for the amazing work on chessground! I'm making a chess-teaching app. Is there an easy way to add text labels (e.g. chess hints) next to specific chess pieces in chessground? Some very brief pointers on how this might be done would be greatly appreciated :-)

When I require chessground

when i require it i get

window is not defined
at Object. (/home/codio/workspace/node_modules/chessground/src/util.js:109:27)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/home/codio/workspace/node_modules/chessground/src/board.js:1:74)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)

Mobile bug involving highlight/lastMove options.

The following configuration settings appear to exhibit a bug in Chessground:

Chessground(container, {
  "fen": "8/p5b1/2p1q2k/5N1P/2P1B3/3P2p1/P1Q1pr1P/4R2K b - - 0 1",
  "turnColor": "black",
  "orientation": "black",
  "movable": {
    "free": false,
    "color": "black",
    "dests": {"h6": ["g5", "h5", "h7"], "e6": ["f5"], "f2": ["f5"]},
    "showDests": true,
    "events": {
      "after": function(orig, dest, metadata) {
        alert("move made");
      }
    }
  },
  "premovable": {"enabled": false},
  "lastMove": ["h7", "h6"],
  "highlight": {"lastMove": true},
});

See this url for an example. This code works as expected on Desktop browsers (tested on Firefox and Safari on macOS). However, on mobile browsers (tested on Safari and Firefox on iOS), moving the King on h6 to any of the 3 allowed squares does not work. In particular, the expected alert "move made" does not appear. Making any other allowed move (either capturing the Knight on f5 with the Queen on e6 or the Rook on f2) works fine and produces the expected alert box. The culprits appear to be the "lastMove" and "highlight" settings, which cause the squares h6 and h7 to become highlighted. In short, it seems that any highlighted piece cannot be moved, on mobile browsers.

class names conflict with bootstrap

Bootstrap uses class names like "h1" as per http://getbootstrap.com/css/#type-headings

Unfortunately chessground also uses the class "h1" to refer to that coordinate on the board. This causes the board to be amusingly misrendered on web pages that happen to be using bootstrap as well.

Would it be acceptable for chessground to change its coord classnames to something like "coord-h1" ? If so I'll do that and submit a PR.

How to show destinations and prevent opposite color selection?

Firstable, I want to thank all of developers of this library.

And I want to ask you to show me the way how to implement things:

  1. I am trying to show dests of selected pieces with this options
showDests : true,
free : false,
dests : {
        "f1" : ["f2", "f3"], //just example to understand
},
color: "white",

After initing the board shows me possible moves
image
I make a move onto f2 square using mouse.
Then I make opposite color move pragmatically:

 var move = game.move({
            from: arr[0],
            to: arr[1],
            promotion: 'q' 
        });
        cg.set({fen: game.fen()});
//cg is Chessground instance

But after moving the piece onto f2 square pieces are not moving: events are not firing and I don't know how to make the next move not pragmatically. It's just shows me possible moves of my rook and king on selection:
image
Can you tell me the algorithm how to interact with the board after moving a piece ?
Seems that color option affects that.

ChessGround doesn't work on Epiphany and Midori Browsers

for our target plattform "RaspberryPi", these Browsers seems to be the standard (esp. Epiphany).
But it doesnt work for picochess...so, i tried it with "lichess.org" ..but there its same.

The start screen (with many diagrams) seems to work (despite the auto-update of moves), but if i click on one game, the board is broken (all pieces are at top left square).

see also this issue:jromang/picochess#241

Since its not working on lichess and picochess, i guess its an internal problem of chessground.

gulp lint error

gulp lint uses an undefined paths.

p.s. Thanks for this project!

Is there a way to paint a square?

I know that I can draw a circle or arrow, but how can I pain or highlight a specific square?
Let's say I want to paint each square based on the number of defenders like a heat map.

Unable to render in horizontal mode

I am trying to show a chessboard horizontally, default view is vertical. I tried rotating 90deg the parent container and chessboard scales accordingly. However, piece selection is completely wrong. As far as I can see the UI rotates but piece selection stays at top and bottom of the container.

Problems with Examples, missing chessground.js

In examples/index.html we got line for
<script src="../chessground.js"></script>
but such file doesn't exist after successful installation.

I edited it to
<script src="../chessground.min.js"></script>
and the examples/index.html now looks like this from the browser

Which I don't believe it's supposed to be look like. I can luckily move those invisible pieces.

chessground examples promotion bug

Apparently when a pawn moves to the other side of the board aka (promotion), the game doesn't show a dialog to choose what the pawn should turn in to and the ai starts to switch it's team to the other side.
So whenever you get your pawn to the other side of the board, all of a sudden you're playing the other side.

This bug exists on version 7.3 since I couldn't get 7.6 to initialize the board at all, I don't know if this bug has been fixed ever since. If it has, can someone explain to me how I can get version 7.6 working? With perhaps an update of the example script? Since I can't seem to initialize the board in any way possible in version 7.6.

I think #96 has the same issue for 7.6, at least, I am experiencing the same thing.

Performance issue with destinations

I saw in chrome timeline showing possible destinations multiplies scripting time by 2 for each 'select-square' action. It has also an impact on 'move-piece' action.

Suggested actions :

  • don't use array lookup
  • do not iterate over each square

Off-by-0.5-pixel offsets for square highlights

This is very minor, but quite annoying, and I'm not sure what the best way to fix it is. Basically, for most zoom levels, there is a good chance that the "selected" and "last move" overlays will be off by one pixel in either direction. As far as I can tell, it's because the piece overlay position is being calculated by CSS transforms, while the checkerboard background is simply a scaled image. So, when the final resolution doesn't evenly divide the scaling factor, it somehow interpolates the image to a resolution below 1 CSS pixel.

You end up with something like this:

(notice the bottom and right edges are off by one)

If I go into the Web Inspector and manually adjust the width and height of the square overlay from 12.5% to calc(12.5% + 1px), I end up with:

(now it's a bit too large, although personally I find this error a bit less annoying)

I'm not sure how to fix this other than by replacing the board background image with all CSS-generated squares. Anyone have any clever ideas about this?

Error on example/index.html

got this errors on console when opening example/index.html

view.js:175 Uncaught ReferenceError: m is not defined
2drag.js:25 Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null
8view.js:175 Uncaught ReferenceError: m is not defined

Thanks a lot for open source this.

Cancel a move?

I am using chess.js with this amazing chessboard. However, I can use the move event to validate the moves, but I do not know how to cancel an illegal move. How would I achieve that? (This isn't an issue, but I don't know where else to ask this, sorry)

cancelMove in the move event doesn't cancel the move, I've tried that. Or am I doing something wrong?

Tapping a square using Apple "Magic" Trackpad and potentially other tap based input device does not select the square

Greetings and, first of all, thanks for the amazing site and software. It is very much appreciated.

The Problem

As reported at the forums (admittedly the wrong place, just figured it out) there is a small but deadly regression on the handling of mouse events for some class of tap based input devices like Apple's Magic trackpad and others where tap to click is allowed.

The great majority of the players are not affected as it can't happen with a mouse but for the minority that players bullet in a touchpad having to drag or click instead of tap would be very limiting.

After opening a game against the computer in order to live debug the (minified) javascript in an attempt to figure out why it doesn't work I managed to isolate the problem and to find the cause.

The Probable Cause

The tap behaviour is implemented on Safari in a very similar way a normal mouse click. The former, like the later, consists (among other things) in one mousedown event followed by one mouseup event.

But in the tap, as opposed to the click, there is no interval between the mouseup and the mousedown events, the mouseup fires up immediately after the mousedown leaving no time for anything in between.

As far as I could figure out the problem is that:

  • the start function called by the onstart event handler that handles the mousedown sets the value for draggable.current among other information about the current selected piece

and then

  • passes the control to ProcessDrag that will, asynchronously (with the requestAnimationFrame call) try to determine over which square the selected piece is being held over

and, at the same time asynchronously

  • the renderSquare function uses the information obtained by the above mentioned processes to determine how to draw the square, which squares are currently legal moves

until a mouseup, when

  • the end function called by the onend event handler that handles the mouseup that performs whatever action the player intended (or prevent it if it is not legal) and cleans up draggable.current along with the selection.

But in the case of the tap, as the mouseup happens right after the mousedown without any time for the requestAnimationFrame to execute once, draggable.current is cleaned up before ProcessDrag or renderSquare have the chance to use it and then processDrag stop calling itself recursively because cur.orig is now undefined.

A Potential Fix

I can't test it so I won't risk sending a PR but if I were to fix this my theory is that we need to ensure that that ProcessDrag is called at least once before mouseup so it can set the properties needed by the later to work properly, like this:

function processDragFrame(data) {
    var cur = data.draggable.current;
    if (cur.orig) {
      // cancel animations while dragging
      if (data.animation.current.start && data.animation.current.anims[cur.orig])
        data.animation.current = {};
      // if moving piece is gone, cancel
      if (hashPiece(data.pieces[cur.orig]) !== cur.piece) cancel(data);
      else {
        if (!cur.started && util.distance(cur.epos, cur.rel) >= data.draggable.distance)
          cur.started = true;
        if (cur.started) {
          cur.pos = [
            cur.epos[0] - cur.rel[0],
            cur.epos[1] - cur.rel[1]
          ];
          cur.over = board.getKeyAtDomPos(data, cur.epos, cur.bounds);
        }
      }
    }
    data.render();
    return cur.orig;
}

function processDrag(data) {
    if (processDragFrame(data)) {
        util.requestAnimationFrame(function() {
            processDrag(data);
        });
    }
}

This should be functionally equivalent to the original code except the main body of the function is executed at least once synchronously.

Testing the Fix

Assuming there is an test environment I can help testing the fix, the steps are relatively simple:

  1. To enter the test environment
  2. Create a computer game
  3. 1.e3

Let me know here or at lichess if I can be of any help.

Best regards

FF

Not able to make moves on mobile

Hi,

I am using chessground in my project here: https://github.com/ArneVogel/listudy , with this config https://github.com/ArneVogel/listudy/blob/master/app/src/utils/consts.js#L7

I myself and users have reported that its not possible to make moves on mobile. You cannot drag the pieces and click (touch one time) to make moves also doesnt work. After you click the legal moves show up for a split second but disappear before you can make the second click.

I am experiencing the same behavior with the example repo.

Edit (browsers):
Samsung S8 using Chrome (tried Desktop Site) Android 9.0
Samsung J5 using Firefox
Using a desktop with Firefox mobile simulator

Pieces do not resize with the board

Even with the resizable option set, the pieces do not scale or move in response to the board resizing. Can an example of fluid layout be added to the examples.

How to get shapes data?

Hi, for add shapes used board.setShapes([...]) method, but how do I get the shapes already added?

en passant capture isn't handled correctly

When capturing an enemy pawn that has passed your pawn by moving two places, clicking your pawn shows that you can either move straight ahead or capture the enemy pawn.

image

After capturing the enemy pawn, the enemy pawn remains on the board but can't be moved.

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.