How to Build a Web3 Chess Server
Repository: https://github.com/gnolang/gnochess
Slides: https://hackmd.io/@tyge/gnochess (soon on the repo!)
Morgan Bazalgette
Core Team Developer @ Gno.Land
Note:
Show this as first slides. Do introductions.
Present how the workshop's going to work.
Baby don't hurt me.
crypto/rand
, system clock, filesystem, unsafe
.Early phase, still not in "production" ("mainnet", in blockchain lingo).
Completely FOSS, contributors welcome!
gno.mod
for versioning// Package ufmt provides utility functions for
// formatting strings [...]
package ufmt
import "strconv"
// Sprintf offers similar functionality to Go's fmt.Sprintf
// or the sprintf equivalent available in many languages,
// [...]
func Sprintf(format string, args ...interface{}) string {
end := len(format)
argNum := 0
argLen := len(args)
buf := ""
for i := 0; i < end; {
isLast := i == end-1
c := format[i]
if isLast || c != '%' {
buf += string(c)
i++
continue
}
// ...
package counter
import "strconv"
var counter int
func Increment() {
counter++
}
func Render(string) string {
return "Times incremented: " + strconv.Itoa(counter)
}
gno
go
command line: gno doc
, gno run
, gno test
, gno repl
gnokey
Note:
Talk about how we are working in parellel on an IDE for streamlining development even further; it will work completely in the browser, and it'll be able to run code through WASM
gno
and gnokey
, and publish our first realm. (Next up!)Gno is alpha quality software. There are a large number of caveats when developing programs, and not every feature is there yet. If a panic shows up that you have no idea how to fix or what it means, call up on one of us.
Note:
This slide is an intro on chess programming and how the first step is to go from the 3D real-life board into the programming representation.
[64]Piece
):
Note:
In this slide, I'll switch to a few predetermined Lichess positions, to show all the moves (even the weirder and less known ones).
The point is to say that to implement a good move validator, the ruleset to implement is a bit trickier than one might expect.
Chess Programming Wiki
Great resource to dig deep & learn what others have done in the past
https://chessprogramming.org
uint64
), we'll be dumber ([64]Piece
)r1bqkbnr/pp1p1Qpp/2n5/2p1p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4
Note:
Position evaluation: engines like stockfish, in order to determine how "good" a move is, eventually need to be able to evaluate a position without recursively searching deeper. So proper engines implement an evaluation function.
This slide serves to explain some concepts about chess programming, and make some of the decisions of the data structures that the users will be re-using look a little less arbitrary
I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
– Linus Torvalds
type Board [64]Piece
type Position struct {
B Board
Moves []Move
Flags PositionFlags // E.p. column, castling rights
}
type Piece byte
const (
PieceEmpty Piece = iota
PiecePawn
PieceRook
// [...]
PieceBlack Piece = 8 // bit-flag
)
type Move struct {
From, To Square
Promotion Piece
}
// range [0,64). 44 (decimal):
// 44 = 0b00 101 100 = d5
// ^row ^col
type Square byte
Note:
Slide talking about: of course, playing chess alone is boring and not that interesting, and referencing this video by tom7 if anyone is interested in more chess playing
func newGame(caller, opponent std.Address, seconds, increment int) *Game {
games := getUserGames(caller)
// Ensure player has no ongoing games.
assertGamesFinished(games)
assertGamesFinished(getUserGames(opponent))
if caller == opponent {
panic("can't create a game with yourself")
}
isBlack := determineColor(games, caller, opponent)
// Set up Game struct. Save in gameStore and user2games.
gameIDCounter++
// id is zero-padded to work well with avl's alphabetic order.
id := zeroPad9(strconv.FormatUint(gameIDCounter, 10))
g := &Game{
ID: id,
White: caller,
Black: opponent,
Position: NewPosition(),
State: GameStateOpen,
Creator: caller,
CreatedAt: time.Now(),
}
if isBlack {
g.White, g.Black = g.Black, g.White
}
gameStore.Set(g.ID, g)
addToUser2Games(caller, g)
addToUser2Games(opponent, g)
return g
}
func MakeMove(gameID, from, to string, promote Piece) string {
std.AssertOriginCall()
g := getGame(gameID, true)
// determine if this is a black move
isBlack := len(g.Position.Moves)%2 == 1
caller := std.GetOrigCaller()
if (isBlack && g.Black != caller) ||
(!isBlack && g.White != caller) {
// either not a player involved; or not the caller's turn.
panic("you are not allowed to make a move at this time")
}
// validate move
m := Move{
From: SquareFromString(from),
To: SquareFromString(to),
}
if m.From == SquareInvalid || m.To == SquareInvalid {
panic("invalid from/to square")
}
if promote > 0 && promote <= PieceKing {
m.Promotion = promote
}
newp, ok := g.Position.ValidateMove(m)
if !ok {
panic("illegal move")
}
// add move and record new board
g.Position = newp
o := newp.IsFinished()
if o == NotFinished {
// opponent of draw offerer has made a move. take as implicit rejection of draw.
if g.DrawOfferer != nil && *g.DrawOfferer != caller {
g.DrawOfferer = nil
}
return g.json()
}
switch {
case o == Checkmate && isBlack:
g.State = GameStateCheckmated
g.Winner = WinnerBlack
case o == Checkmate && !isBlack:
g.State = GameStateCheckmated
g.Winner = WinnerWhite
case o == Stalemate:
g.State = GameStateStalemate
g.Winner = WinnerDraw
case o == Drawn75Move:
g.State = GameStateDrawn75Move
g.Winner = WinnerDraw
case o == Drawn5Fold:
g.State = GameStateDrawn5Fold
g.Winner = WinnerDraw
}
g.DrawOfferer = nil
g.saveResult()
return g.json()
}
Draw
, DrawOffer
and Resign
♟Commerce on the Internet has come to rely almost exclusively on financial institutions serving as trusted third parties to process electronic payments. While the system works well enough for most transactions, it still suffers from the inherent weaknesses of the trust based model. Completely non-reversible transactions are not really possible, since financial institutions cannot avoid mediating disputes. The cost of mediation increases transaction costs, limiting the minimum practical transaction size and cutting off the possibility for small casual transactions, and there is a broader cost in the loss of ability to make non-reversible payments for non-reversible services. With the possibility of reversal, the need for trust spreads. Merchants must be wary of their customers, hassling them for more information than they would otherwise need.
A certain percentage of fraud is accepted as unavoidable. These costs and payment uncertainties can be avoided in person by using physical currency, but no mechanism exists to make payments over a communications channel without a trusted party.
What Web3 enables is what Web2 never could:
Achieve trust in a trustless environment.
Additionally, it enables perpetual, self-funded applications.
See GOPHERCON_COMPETITION.md
in Chess repository.