With a case study of Chess.
Vineesh Narikutty Pacha
Backend Developer @ TechJini.
Codes NodeJs and Python.
Loves Rust, Golang and Elixir.
What is game backend?
Which languages generally we use to build game backend?
What, Why, When ?
REST vs Sockets?
What is websocket?
Why socket.io?
Case study of writing chess backend using NodeJS
gameState = {
players: {
p1 : {
...
},
p2 : {
...
}
},
state : {
board : [],
turn : []
},
winner : null,
turn : null
}
Let's look at some code for socket fundamentals.
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
io.on('connection', (socket) => {
socket.on('chat message', function(msg){
io.emit('chat message', msg);
socket.to({{socketId}}).emit('chat message', msg);
});
});
http.listen(port, () => {
console.log('listening on *:' + port);
});
<script> src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
$(function () {
var socket = io();
/*
* On some event trigger below code
*/
socket.emit('chat message', $('#m').val());
socket.on('chat message', function(msg){
console.log(msg)
});
});
</script>
Let's dive to some more code!
/**
* Front end code
*/
io.on('connection', (socket) => {
/**
* During some action
*/
socket.join('room1');
/**
* Inorder to leave a room
*/
socket.leave('room1');
});
/**
* Backend code
*/
io.to('room1').emit('data', {data : 0});
/**
* Front end, on a subscribed client
*/
io.on('connection', (socket) => {
socket.on('data', (msg) => {
console.log(msg); //{data : 0}
});
});
Let's look at chess library.
npm install --save chess.js
const Chess = require('chess.js').Chess;
const chess = new Chess();
console.log('Printing the current board state');
console.log(chess.ascii());
/** Output */
+------------------------+
8 | r n b q k b n r |
7 | p p p p p p p p |
6 | . . . . . . . . |
5 | . . . . . . . . |
4 | . . . . . . . . |
3 | . . . . . . . . |
2 | P P P P P P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
/**
* moves can be triggered in different ways
*/
chess.move('e4'); // Standard algebraic notation
chess.move({from : 'e7', to : 'e5'}) // or with more readable way.
chess.move('Nh3'); // Moves the night to h3
chess.move({from : 'f8', to : 'a3' }) // Moving the bishop
/**
* Checking the validity of the move
*/
console.log('Valid move output', chess.move('b3'));
{
color: 'w',
from: 'b2',
to: 'b3',
flags: 'n',
piece: 'p',
san: 'b3'
}
console.log('Invalid move output', chess.move('b2'));
null
/**
* Check if the game is in check state
*/
console.log(chess.in_check());
// returns boolean
console.log(chess.in_checkmate());
// returns boolean
Chess have lots of situations like.
* Draw
* Settlement
* Castling, etc
/**
* Check if the game is in check state
*/
console.log(chess..in_draw());
// returns boolean
console.log(chess.in_stalemate());
// returns boolean