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
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
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.
[64]Piece
):
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
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
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
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
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
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
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.