Playground
connect4.gno
package connect4
import (
"chain"
"errors"
"strconv"
"strings"
"gno.land/p/nym-moultest123/kit/store/v0"
"gno.land/p/nym-moultest123/kit/ui/v0"
"gno.land/p/nym-moultest123/md/v0"
)
// selfPath is this realm's own page. A root-relative link resolves against
// the domain, not the realm, so every link back into it names it in full.
const selfPath = "/r/nym-moultest123/x/daily/connect4/v1"
const (
cols = 7
rows = 6
)
// cell values
const (
empty = 0
red = 1 // 🔴 game creator (caller of NewGame)
yel = 2 // 🟡 opponent
)
// Game holds the full state of one Connect Four match.
// board is indexed board[row][col]; row 0 is the BOTTOM row.
// It carries no ID field: the id belongs to the store, which hands it back on
// lookup and iteration.
type Game struct {
Red address // 🔴 creator, moves first
Yellow address // 🟡 opponent
Board [rows][cols]int
Turn int // whose turn: red or yel
Winner int // empty until decided; red/yel = winner
Draw bool // true when board full with no winner
Finished bool
}
// games assigns the game ids. v1 kept its own nextID plus an idKey() that
// zero-padded to width 12, which stopped ordering the Render list past 10^12.
var games = store.Named("game")
// NewGame creates a match between the caller (🔴) and opponent (🟡).
// Returns the new game id.
func NewGame(cur realm, opponent address) int64 {
if !cur.IsCurrent() {
panic("connect4: spoofed realm")
}
caller := cur.Previous().Address()
if opponent == caller {
panic("opponent must differ from caller")
}
if opponent.String() == "" {
panic("opponent address is empty")
}
id := games.Add(&Game{
Red: caller,
Yellow: opponent,
Turn: red,
})
chain.Emit("GameCreated",
"id", id.String(),
"red", caller.String(),
"yellow", opponent.String(),
)
return int64(id)
}
func getGame(id int64) (*Game, error) {
v, ok := games.Get(store.ID(id))
if !ok {
return nil, errors.New("game not found: " + strconv.FormatInt(id, 10))
}
return v.(*Game), nil
}
// Drop places the caller's disc into the given column (0-6).
// Enforces turn order by caller, rejects full columns, and detects
// a 4-in-a-row win or a draw.
func Drop(cur realm, gameID int64, column int) {
if !cur.IsCurrent() {
panic("connect4: spoofed realm")
}
if column < 0 || column >= cols {
panic("column out of range (0-6)")
}
g, err := getGame(gameID)
if err != nil {
panic(err.Error())
}
if g.Finished {
panic("game already finished")
}
caller := cur.Previous().Address()
var mover int
switch caller {
case g.Red:
mover = red
case g.Yellow:
mover = yel
default:
panic("caller is not a player in this game")
}
if mover != g.Turn {
panic("not your turn")
}
// find lowest empty row in the column
placed := -1
for r := 0; r < rows; r++ {
if g.Board[r][column] == empty {
g.Board[r][column] = mover
placed = r
break
}
}
if placed == -1 {
panic("column is full")
}
if wins(&g.Board, placed, column, mover) {
g.Winner = mover
g.Finished = true
chain.Emit("GameWon",
"id", strconv.FormatInt(gameID, 10),
"winner", caller.String(),
)
} else if full(&g.Board) {
g.Draw = true
g.Finished = true
chain.Emit("GameDraw", "id", strconv.FormatInt(gameID, 10))
} else {
if g.Turn == red {
g.Turn = yel
} else {
g.Turn = red
}
chain.Emit("DiscDropped",
"id", strconv.FormatInt(gameID, 10),
"col", strconv.Itoa(column),
"player", caller.String(),
)
}
}
func full(b *[rows][cols]int) bool {
for c := 0; c < cols; c++ {
if b[rows-1][c] == empty {
return false
}
}
return true
}
// wins checks whether the disc just placed at (r,c) for player p completes
// a run of 4 in any of the four directions.
func wins(b *[rows][cols]int, r, c, p int) bool {
// direction pairs: horizontal, vertical, diag /, diag \
dirs := [4][2]int{{0, 1}, {1, 0}, {1, 1}, {1, -1}}
for _, d := range dirs {
count := 1
count += run(b, r, c, d[0], d[1], p)
count += run(b, r, c, -d[0], -d[1], p)
if count >= 4 {
return true
}
}
return false
}
func run(b *[rows][cols]int, r, c, dr, dc, p int) int {
n := 0
for i := 1; i < 4; i++ {
rr := r + dr*i
cc := c + dc*i
if rr < 0 || rr >= rows || cc < 0 || cc >= cols {
break
}
if b[rr][cc] != p {
break
}
n++
}
return n
}
func glyph(v int) string {
switch v {
case red:
return "🔴"
case yel:
return "🟡"
default:
return "·"
}
}
// Render draws the board with 🔴🟡· and shows whose turn / the winner.
// path "" lists all games; path "<id>" shows a single board.
func Render(path string) string {
path = strings.TrimSpace(strings.Trim(path, "/"))
if path == "" {
return renderList()
}
id, ok := store.ParseID(path)
if !ok {
return "# Connect Four\n\nInvalid game id: " + md.InlineCode(path) + "\n"
}
g, err := getGame(int64(id))
if err != nil {
return "# Connect Four\n\n" + err.Error() + "\n"
}
return renderGame(id, g)
}
func renderList() string {
var sb strings.Builder
sb.WriteString("# Connect Four\n\n")
sb.WriteString("Two-player Connect Four on a 7×6 board. 🔴 is the game creator, 🟡 the opponent.\n\n")
if games.Len() == 0 {
sb.WriteString("_No games yet. Call `NewGame(opponent)` to start one._\n")
return sb.String()
}
sb.WriteString("## Games\n\n")
sb.WriteString("| ID | 🔴 Red | 🟡 Yellow | Status |\n")
sb.WriteString("|----|--------|-----------|--------|\n")
games.Each(func(id store.ID, v any) {
g := v.(*Game)
status := ""
switch {
case g.Winner == red:
status = "🔴 won"
case g.Winner == yel:
status = "🟡 won"
case g.Draw:
status = "draw"
case g.Turn == red:
status = "🔴 to move"
default:
status = "🟡 to move"
}
sb.WriteString("| [" + id.String() + "](" + selfPath + ":" + id.String() + ") | " +
ui.Addr(g.Red) + " | " + ui.Addr(g.Yellow) + " | " + status + " |\n")
})
sb.WriteString("\nOpen a game by its id (e.g. path `1`).\n")
return sb.String()
}
func renderGame(id store.ID, g *Game) string {
var sb strings.Builder
sb.WriteString("# Connect Four — Game " + id.String() + "\n\n")
sb.WriteString("- 🔴 Red: `" + g.Red.String() + "`\n")
sb.WriteString("- 🟡 Yellow: `" + g.Yellow.String() + "`\n\n")
// status line
switch {
case g.Winner == red:
sb.WriteString("**🔴 Red wins!**\n\n")
case g.Winner == yel:
sb.WriteString("**🟡 Yellow wins!**\n\n")
case g.Draw:
sb.WriteString("**Draw — board full.**\n\n")
case g.Turn == red:
sb.WriteString("**Turn: 🔴 Red**\n\n")
default:
sb.WriteString("**Turn: 🟡 Yellow**\n\n")
}
// board top-down (row rows-1 at top, row 0 at bottom)
sb.WriteString("```\n")
for r := rows - 1; r >= 0; r-- {
for c := 0; c < cols; c++ {
sb.WriteString(glyph(g.Board[r][c]))
}
sb.WriteString("\n")
}
// column indices
for c := 0; c < cols; c++ {
sb.WriteString(strconv.Itoa(c))
}
sb.WriteString("\n```\n\n")
if !g.Finished {
sb.WriteString("Drop a disc: `Drop(" + id.String() + ", <col 0-6>)`\n")
}
return sb.String()
}
connect4_test.gno
package connect4
import (
"strings"
"testing"
"gno.land/p/nym-moultest123/kit/store/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
var (
alice = testutils.TestAddress("alice") // 🔴
bob = testutils.TestAddress("bob") // 🟡
carol = testutils.TestAddress("carol")
)
func resetState() {
games = store.Named("game")
}
// TestVerticalWin plays 🔴 stacking column 0 four high while 🟡 plays column 1.
func TestVerticalWin(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := NewGame(cross(cur), bob)
uassert.Equal(t, int64(1), id)
for i := 0; i < 3; i++ {
testing.SetRealm(testing.NewUserRealm(alice))
Drop(cross(cur), id,0)
testing.SetRealm(testing.NewUserRealm(bob))
Drop(cross(cur), id,1)
}
// alice's 4th disc in column 0 -> vertical win
testing.SetRealm(testing.NewUserRealm(alice))
Drop(cross(cur), id,0)
g, err := getGame(id)
uassert.NoError(t, err)
uassert.True(t, g.Finished)
uassert.Equal(t, red, g.Winner)
out := Render("1")
uassert.True(t, strings.Contains(out, "🔴 Red wins!"))
}
// TestTurnOrderAndErrors covers turn enforcement, non-player, full-column and range checks.
func TestTurnOrderAndErrors(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := NewGame(cross(cur), bob)
// bob cannot move first (red starts)
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsWithMessage(t, cur,"not your turn", func() {
Drop(cross(cur), id,0)
})
// stranger cannot play
testing.SetRealm(testing.NewUserRealm(carol))
uassert.AbortsWithMessage(t, cur,"caller is not a player in this game", func() {
Drop(cross(cur), id,0)
})
// out-of-range column
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsWithMessage(t, cur,"column out of range (0-6)", func() {
Drop(cross(cur), id,7)
})
// fill column 3: alice & bob alternate, 6 discs total
col := 3
for i := 0; i < 3; i++ {
testing.SetRealm(testing.NewUserRealm(alice))
Drop(cross(cur), id,col)
testing.SetRealm(testing.NewUserRealm(bob))
Drop(cross(cur), id,col)
}
// column now full; whoever is on turn overflows it
g, _ := getGame(id)
var mover address
if g.Turn == red {
mover = alice
} else {
mover = bob
}
testing.SetRealm(testing.NewUserRealm(mover))
uassert.AbortsWithMessage(t, cur,"column is full", func() {
Drop(cross(cur), id,col)
})
}
// TestHorizontalWin: 🔴 across columns 0-3 on the bottom row.
func TestHorizontalWin(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
id := NewGame(cross(cur), bob)
// alice drops cols 0,1,2 ; bob answers on row above (col 0,1,2)
for c := 0; c < 3; c++ {
testing.SetRealm(testing.NewUserRealm(alice))
Drop(cross(cur), id,c)
testing.SetRealm(testing.NewUserRealm(bob))
Drop(cross(cur), id,c)
}
// alice completes col 3 on bottom row -> 0,1,2,3 horizontal
testing.SetRealm(testing.NewUserRealm(alice))
Drop(cross(cur), id,3)
g, err := getGame(id)
uassert.NoError(t, err)
uassert.True(t, g.Finished)
uassert.Equal(t, red, g.Winner)
}
// TestRenderList checks the listing view renders created games.
func TestRenderList(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
NewGame(cross(cur), bob)
out := Render("")
uassert.True(t, strings.Contains(out, "Connect Four"))
uassert.True(t, strings.Contains(out, "to move"))
}
gnomod.toml
module = "gno.land/r/nym-moultest123/x/daily/connect4/v1" gno = "0.9" private = true [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186413 max_deposit = "7000000ugnot"
zz_escape_test.gno
package connect4
import (
"strings"
"testing"
"gno.land/p/nym-moultest123/md/v0"
"gno.land/p/nt/uassert/v0"
)
// A path that is not a valid input is echoed back. It is the visitor's text,
// so a backtick in it must not close a code span and let a link through.
func TestInvalidPathIsEscaped(t *testing.T) {
out := Render("x` [claim](https://evil.example) `")
// Still there, but inside a span md.InlineCode widened past its backticks.
uassert.True(t, strings.Contains(out, md.InlineCode("x` [claim](https://evil.example) `")), out)
}
zz_links_test.gno
package connect4
import (
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
)
// The game list links each game to this realm's own page. It once linked
// to the malformed gno.land/r:<id>.
func TestListLinksNameThisRealm(cur realm, t *testing.T) {
testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("red")))
id := NewGame(cross(cur), testutils.TestAddress("yellow"))
out := Render("")
s := ""
for n := id; n > 0; n /= 10 {
s = string(rune(byte(n%10)+byte(48))) + s
}
uassert.True(t, strings.Contains(out, "](/r/nym-moultest123/x/daily/connect4/v1:"+s+")"), out)
}