ggol

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2022 License: MIT Imports: 2 Imported by: 0

README

Go's Game of Liberty

Go Reference Go Report Card Go

Go's Game of Liberty is a go package that provides a set of API for you to build a game in 2d map, this API was initially for helping you build the Conway's Game of Life, but later we found more possibilities of it, so the Go's Game of Liberty came out.

Looking forward to seeing your masterpiece built with the API :).

For more details, please check API document here.

Features

  • Easy to setup.
  • Concurrently safe.
  • Fully customizable.

Install

go get github.com/dum-dum-genius/ggol

Usage

Build Conway's Game of Life

The example below shows you how to buil a the Conway's Game of Life with the API.

package main

import (
    "fmt"

    "github.com/dum-dum-genius/ggol"
)

// Define your unit type, in Conway's
// Game of Life, the smallest unit refers to a cell,
// and the only information we need to know is "Alive".
type CgolCell struct {
    Alive bool
}

// This is the core part of the game, it tells the game
// how to generate the next status of the given unit.
// This generator here implements 4 basic rules of Conways Game
// of Life, if you want, you can add your custom rules here :).
func cgolNextUnitGenerator(
    // Coordinate of the given unit.
    coord *ggol.Coordinate,
    // Pointer to the current unit status.
    unit *CgolCell,
    // A getter for getting adjacent units, check this type ggol.AdjacentUnitGetter[T] for details.
    getAdjacentUnit ggol.AdjacentUnitGetter[CgolCell],
) (nextCgolCell *CgolCell) {
    nextUnit := *unit

    // Get live adjacent cells count
    // We need to to implement 4 basic rules of
    // Conways Game of Life.
    var liveAdjacentCellsCount int = 0
    for i := -1; i < 2; i += 1 {
        for j := -1; j < 2; j += 1 {
            if !(i == 0 && j == 0) {
                // Pay attention to "isCrossBorder", if the adjacent unit in the relative coordinate
                // is on other side of the map, "isCrossBorder" will be true.
                // So if you want to allow your cells to be able to go beyond border, ignore "isCrossBorder" here.
                adjUnit, isCrossBorder := getAdjacentUnit(coord, &ggol.Coordinate{X: i, Y: j})
                if adjUnit.Alive && !isCrossBorder {
                    liveAdjacentCellsCount += 1
                }
            }
        }
    }
    if nextUnit.Alive {
        if liveAdjacentCellsCount == 2 || liveAdjacentCellsCount == 3 {
            // Cell survives due to rule 2.
            nextUnit.Alive = true
            return &nextUnit
        } else {
            // Cell dies of rule 1 or rule 3.
            nextUnit.Alive = false
            return &nextUnit
        }
    } else {
        // Cell becomes alive due to rule 4.
        if liveAdjacentCellsCount == 3 {
            nextUnit.Alive = true
            return &nextUnit
        }
        return &nextUnit
    }
}

// You have to generate your initial cells.
func generateInitialCgolCells(width int, height int, cell CgolCell) *[][]CgolCell {
	cells := make([][]CgolCell, width)
	for x := 0; x < width; x += 1 {
		cells[x] = make([]CgolCell, height)
		for y := 0; y < height; y += 1 {
			cells[x][y] = cell
		}
	}

	return &cells
}

func main() {
    // Initial status of all units.
    initialCgolCell := CgolCell{Alive: false}
    initialCgolCells := generateInitialCgolCells(3, 3, initialCgolCell)

    // Alrighty, let's create a new game with the given cells
    game, _ := ggol.NewGame(initialCgolCells)
    size := game.GetSize()
    // Set generator of next unit.
    game.SetNextUnitGenerator(cgolNextUnitGenerator)

    // Let's bring 3 cells alive to form a Blinker pattern :).
    // What is Blinker? https://conwaylife.com/wiki/Blinker
    game.SetUnit(&ggol.Coordinate{X: 1, Y: 0}, &CgolCell{Alive: true})
    game.SetUnit(&ggol.Coordinate{X: 1, Y: 1}, &CgolCell{Alive: true})
    game.SetUnit(&ggol.Coordinate{X: 1, Y: 2}, &CgolCell{Alive: true})

    // This will generate next units, the looking of next generation of units is depending on "cgolNextUnitGenerator"
    // you just passed in "SetNextUnitGenerator" above.
    game.GenerateNextUnits()

    // Let's see if we generate the next status of the Blinker correctly.
    // If it's correct, all units below should have "Alive" attribute as true.
    for x := 0; x < size.Width; x += 1 {
        unit, _ := game.GetUnit(&ggol.Coordinate{X: x, Y: 1})
        fmt.Printf("%v ", unit.Alive)
    }
    // true true true
}
Conway's Game of Life

Sample Code

Normal

Game of Wave

Build multiple wave that keep going up forever.

Sample Code

Wave

Game of Black and White

You can switch black and white in every iteration.

Sample Code

Black White

Game of King

When cells collide, they get more power, cells with greatest power will show in gold color.

Sample Code

Who Is King

Game of Matrix

The rain of code in the movie Matrix.

Sample Code

Who Is King

Development

We use Makefile to setup develop environments.

Run Unit Tests
make test
Setup Pre-commit Hook
make setup-pre-commit
Build Sample GIFs As Demo

You can refer to sample code in here to build GIFs of your custom games.

make demo

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdjacentUnitGetter

type AdjacentUnitGetter[T any] func(originCoord *Coordinate, relativeCoord *Coordinate) (unit *T, isCrossBorder bool)

This function will be passed into NextUnitGenerator, this is how you can adajcent units in NextUnitGenerator. Also, 2nd argument "isCrossBorder" tells you if the adjacent unit is on ohter side of the map.

type Area

type Area struct {
	From Coordinate
	To   Coordinate
}

Area indicates an area within two coordinates.

type Coordinate

type Coordinate struct {
	X int
	Y int
}

Coordniate tells you the position of an unit in the game.

type ErrAreaIsInvalid

type ErrAreaIsInvalid struct {
	Area *Area
}

This error will be thrown when the X or Y of "from coordinate" is less than X or Y of "to coordinate" in the area.

func (*ErrAreaIsInvalid) Error

func (e *ErrAreaIsInvalid) Error() string

type ErrCoordinateIsInvalid

type ErrCoordinateIsInvalid struct {
	Coordinate *Coordinate
}

This error will be thrown when you're trying to set or get an unit with invalid coordinate.

func (*ErrCoordinateIsInvalid) Error

func (e *ErrCoordinateIsInvalid) Error() string

Tell you that the coordinate is invalid.

type ErrUnitsIsInvalid

type ErrUnitsIsInvalid struct {
}

This error will be thrown when you try to create a new game with invalid size.

func (*ErrUnitsIsInvalid) Error

func (e *ErrUnitsIsInvalid) Error() string

Tell you that the size is invalid.

type Game

type Game[T any] interface {
	// Generate next units, the way you generate next units will be depending on the NextUnitGenerator function
	// you passed in SetNextUnitGenerator.
	GenerateNextUnits() (units *[][]T)
	// Set NextUnitGenerator, which tells the game how you want to generate next unit of the given unit.
	SetNextUnitGenerator(nextUnitGenerator NextUnitGenerator[T])
	// Set the status of the unit at the given coordinate.
	SetUnit(coord *Coordinate, unit *T) (err error)
	// Get the size of the game.
	GetSize() (size *Size)
	// Get the status of the unit at the given coordinate.
	GetUnit(coord *Coordinate) (unit *T, err error)
	// Get all units in the area.
	GetUnitsInArea(area *Area) (units *[][]T, err error)
	// Get all units in the game.
	GetUnits() (units *[][]T)
	// Iterate through units in the given area.
	IterateUnitsInArea(area *Area, callback UnitsIteratorCallback[T]) (err error)
	// Iterate through all units in the game
	IterateUnits(callback UnitsIteratorCallback[T])
}

"T" in the Game interface represents the type of unit, it's defined by you.

func NewGame

func NewGame[T any](
	units *[][]T,
) (Game[T], error)

Return a new Game with the given size and initalUnit.

type NextUnitGenerator

type NextUnitGenerator[T any] func(coord *Coordinate, unit *T, getAdjacentUnit AdjacentUnitGetter[T]) (nextUnit *T)

NextUnitGenerator tells the game how you're gonna generate next status of the given unit.

type Size

type Size struct {
	Width  int
	Height int
}

The size of the game.

type UnitsIteratorCallback

type UnitsIteratorCallback[T any] func(coord *Coordinate, unit *T)

UnitsIteratorCallback will be called when iterating through units.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL