Skip to content

Commit

Permalink
Merge seperate Score struct into backend
Browse files Browse the repository at this point in the history
  • Loading branch information
z-riley committed Nov 13, 2024
1 parent e0ed75f commit b7bd4a6
Show file tree
Hide file tree
Showing 11 changed files with 57 additions and 85 deletions.
20 changes: 13 additions & 7 deletions backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@ import (

// Game contains all required data for a 2048 game.
type Game struct {
Grid *grid.Grid `json:"grid"`
Score *Score `json:"currentScore"`
Timer *Timer `json:"time"`
Grid *grid.Grid `json:"grid"`
Score int `json:"score"`
HighScore int `json:"highScore"`
Timer *Timer `json:"time"`

store *store.Store
opts *Opts
}

// opts contains configuration for the game.
// Opts contains the configuration for the backend game.
type Opts struct {
SaveToDisk bool
}
Expand All @@ -34,7 +35,7 @@ func NewGame(opts *Opts) *Game {

g := &Game{
Grid: grid.NewGrid(),
Score: NewScore(),
Score: 0,
Timer: NewTimer(),
store: store.NewStore(".save.bruh"),
opts: opts,
Expand All @@ -56,15 +57,20 @@ func NewGame(opts *Opts) *Game {
// Reset resets the game.
func (g *Game) Reset() *Game {
g.Grid.Reset()
g.Score.Reset()
g.Score = 0
g.Timer.Reset().Pause()
return g
}

// ExecuteMove carries out a move in the given direction.
func (g *Game) ExecuteMove(dir grid.Direction) {
pointsGained := g.Grid.Move(dir)
g.Score.AddToCurrent(pointsGained)

// Update score
g.Score += pointsGained
if g.Score > g.HighScore {
g.HighScore = g.Score
}

if g.Grid.Outcome() == grid.Lose {
g.Timer.Pause()
Expand Down
56 changes: 28 additions & 28 deletions backend/grid/grid.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ import (
)

const (
GridLen = 4
gridWidth = GridLen
gridHeight = GridLen
GridSize = 4
gridWidth = GridSize
gridHeight = GridSize
)

// Grid contains the tiles for the game. Position {0,0} is the top left square.
type Grid struct {
mu sync.Mutex
Tiles [gridWidth][gridHeight]Tile `json:"tiles"`

LastMove Direction `json:"lastMove"`
LastMove Direction
}

// NewGrid constructs a new grid.
Expand Down Expand Up @@ -71,15 +71,6 @@ func (g *Grid) Reset() {
g.Tiles[tile2.x][tile2.y].Val = newTileVal()
}

// ClearCmbFlags clears the Cmb flag of every tile.
func (g *Grid) ClearCmbFlags() {
for i := range g.Tiles {
for j := range g.Tiles[i] {
g.Tiles[i][j].Cmb = false
}
}
}

// NumTiles returns the number of non zero tiles on the grid.
func (g *Grid) NumTiles() int {
n := 0
Expand All @@ -93,6 +84,15 @@ func (g *Grid) NumTiles() int {
return n
}

// ClearCmbFlags clears the Cmb flag of every tile.
func (g *Grid) ClearCmbFlags() {
for i := range g.Tiles {
for j := range g.Tiles[i] {
g.Tiles[i][j].Cmb = false
}
}
}

// Outcome represents the outcome of a game.
type Outcome string

Expand Down Expand Up @@ -150,14 +150,14 @@ func (g *Grid) move(dir Direction) (bool, int) {
// The moveStep function only operates on a row, so to move vertically
// we must transpose the grid before and after the move operation.
if dir == DirUp || dir == DirDown {
g.Tiles = Transpose(g.Tiles)
g.Tiles = transpose(g.Tiles)
}
g.Tiles[row], rowMoved, points = moveStep(g.Tiles[row], dir)
if points > 0 {
pointsGained = points
}
if dir == DirUp || dir == DirDown {
g.Tiles = Transpose(g.Tiles)
g.Tiles = transpose(g.Tiles)
}

if rowMoved {
Expand Down Expand Up @@ -247,7 +247,7 @@ func (g *Grid) isLoss() bool {
}
}
}
t := Transpose(g.Tiles)
t := transpose(g.Tiles)
for i := range gridHeight {
for j := range gridWidth - 1 {
if t[i][j].Val == t[i][j+1].Val {
Expand Down Expand Up @@ -284,17 +284,6 @@ func (g *Grid) Debug() string {
return out
}

// Transpose returns a transposed version of the grid.
func Transpose(matrix [gridWidth][gridHeight]Tile) [gridHeight][gridWidth]Tile {
var transposed [gridHeight][gridWidth]Tile
for i := range gridWidth {
for j := range gridHeight {
transposed[j][i] = matrix[i][j]
}
}
return transposed
}

// clone returns a deep copy for debugging purposes.
func (g *Grid) clone() *Grid {
newGrid := &Grid{}
Expand All @@ -306,9 +295,20 @@ func (g *Grid) clone() *Grid {
return newGrid
}

// transpose returns a transposed version of the grid.
func transpose(matrix [gridWidth][gridHeight]Tile) [gridHeight][gridWidth]Tile {
var transposed [gridHeight][gridWidth]Tile
for i := range gridWidth {
for j := range gridHeight {
transposed[j][i] = matrix[i][j]
}
}
return transposed
}

const emptyTile = 0

// Tile represents a single Tile on the grid.
// Tile represents a single tile on the grid.
type Tile struct {
Val int `json:"val"` // the value of the number on the tile
Cmb bool `json:"cmb"` // flag for whether tile was combined in the current turn
Expand Down
2 changes: 1 addition & 1 deletion backend/grid/grid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func TestTranspose(t *testing.T) {
{{Val: 3}, {Val: 0}, {Val: 0}, {Val: 0}},
{{Val: 4}, {Val: 0}, {Val: 0}, {Val: 5}},
}
got := Transpose(input)
got := transpose(input)
if !reflect.DeepEqual(expected, got) {
t.Errorf("\nExpected:\n<%v>\nGot:\n<%v>", expected, got)
}
Expand Down
2 changes: 1 addition & 1 deletion backend/grid/iter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package grid

// iter is a genetic iterator which can iterate forwards or backwards.
// iter is a generic iterator which can iterate forwards or backwards.
type iter struct {
length int
reverse bool
Expand Down
36 changes: 0 additions & 36 deletions backend/score.go

This file was deleted.

2 changes: 1 addition & 1 deletion backend/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"sync"
)

// Store can store bytes to the disk with gob encoding.
// Store can store bytes to the disk.
type Store struct {
mu *sync.Mutex
filename string
Expand Down
2 changes: 1 addition & 1 deletion common/arena.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (
ArenaSizePx = tileSpacingPx*4 + TileSizePx*TileBoundryFactor // the width and height of arena, in pixels
tileSpacingPx = TileSizePx * (1 + TileBoundryFactor)
tileFont = FontPathBold
numTiles = grid.GridLen
numTiles = grid.GridSize
)

// tile is a visual representation of a game tile.
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/brunoga/deep v1.2.4
github.com/google/uuid v1.6.0
github.com/moby/moby v27.3.1+incompatible
github.com/z-riley/turdgl v0.0.0-20241111212625-8502d81bbf4b
github.com/z-riley/turdgl v0.0.0-20241113204523-7589c7e2d94c
github.com/z-riley/turdserve v0.0.0-20241109095301-66eab11d38af
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ github.com/z-riley/turdgl v0.0.0-20241111211940-c3cd8a2a4483 h1:70BLpyLJWGuxgRDW
github.com/z-riley/turdgl v0.0.0-20241111211940-c3cd8a2a4483/go.mod h1:PUy0rnENvtQrZRghi9dYinsUUE7gvC9wOz8C/gcwJ8A=
github.com/z-riley/turdgl v0.0.0-20241111212625-8502d81bbf4b h1:Vf/FWjMHQAcLWjDGTGmhs52EoNHK+ojtG722IWdyduw=
github.com/z-riley/turdgl v0.0.0-20241111212625-8502d81bbf4b/go.mod h1:PUy0rnENvtQrZRghi9dYinsUUE7gvC9wOz8C/gcwJ8A=
github.com/z-riley/turdgl v0.0.0-20241113204523-7589c7e2d94c h1:rY4cuGYihAkPwxwA79jHFhpOfMAyds33epNsxl45zwM=
github.com/z-riley/turdgl v0.0.0-20241113204523-7589c7e2d94c/go.mod h1:PUy0rnENvtQrZRghi9dYinsUUE7gvC9wOz8C/gcwJ8A=
github.com/z-riley/turdserve v0.0.0-20241103172943-200ed8c9c094 h1:9ldkpBMZ5+BV8GOGH+4QhrBgevotAprFgMVCasm+td0=
github.com/z-riley/turdserve v0.0.0-20241103172943-200ed8c9c094/go.mod h1:D5VroZVlQvt0vUtZ2xHL8aQOlCumE/9LFEH1BBLE468=
github.com/z-riley/turdserve v0.0.0-20241109095301-66eab11d38af h1:X0XCfUgoGvZaOZtSRcB6UkuEkP4B6EzwvDUkkZkA7p0=
Expand Down
8 changes: 4 additions & 4 deletions screen/multiplayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,9 @@ func (s *MultiplayerScreen) Update() {
func (s *MultiplayerScreen) updateNormal() {
s.newGame.Update(s.win)
s.menu.Update(s.win)
s.score.SetBody(strconv.Itoa(s.backend.Score.CurrentScore()))
s.score.SetBody(strconv.Itoa(s.backend.Score))
s.timer.SetText(s.backend.Timer.Time.String())
s.opponentScore.SetBody(strconv.Itoa(s.opponentBackend.Score.CurrentScore()))
s.opponentScore.SetBody(strconv.Itoa(s.opponentBackend.HighScore))

for _, d := range []turdgl.Drawable{
s.logo2048,
Expand Down Expand Up @@ -343,10 +343,10 @@ func (s *MultiplayerScreen) updateLose() {

func (s *MultiplayerScreen) updateGameEnd() {
s.menu.Update(s.win)
s.score.SetBody(strconv.Itoa(s.backend.Score.CurrentScore()))
s.score.SetBody(strconv.Itoa(s.backend.Score))
s.timer.SetText(s.backend.Timer.Time.String())
s.backend.Timer.Pause()
s.opponentScore.SetBody(strconv.Itoa(s.opponentBackend.Score.CurrentScore()))
s.opponentScore.SetBody(strconv.Itoa(s.opponentBackend.Score))

for _, d := range []turdgl.Drawable{
s.menu,
Expand Down
10 changes: 5 additions & 5 deletions screen/singleplayer.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (s *SingleplayerScreen) Enter(_ InitData) {
s.debugTime = turdgl.NewText("time", turdgl.Vec{X: 1100, Y: 550}, common.FontPathMedium).
SetText(s.backend.Timer.Time.String())
s.debugScore = turdgl.NewText("score", turdgl.Vec{X: 950, Y: 550}, common.FontPathMedium).
SetText(strconv.Itoa(s.backend.Score.Current))
SetText(strconv.Itoa(s.backend.Score))

// Set keybinds. User inputs are sent to the backend via a buffered channel
// so the backend game cannot execute multiple moves before the frontend has
Expand Down Expand Up @@ -212,7 +212,7 @@ func (s *SingleplayerScreen) Update() {
s.debugGrid.SetText(s.backend.Grid.Debug())
s.debugTime.SetText(s.backend.Timer.Time.String())
s.debugScore.SetText(
fmt.Sprint(s.backend.Score.Current, "|", s.backend.Score.High),
fmt.Sprint(s.backend.Score, "|", s.backend.HighScore),
)

s.win.Draw(s.debugGrid)
Expand All @@ -225,9 +225,9 @@ func (s *SingleplayerScreen) Update() {
func (s *SingleplayerScreen) updateNormal(game backend.Game) {
s.win.SetBackground(common.BackgroundColour)

s.score.SetBody(strconv.Itoa(game.Score.Current))
s.score.SetBody(strconv.Itoa(game.Score))
s.menu.Update(s.win)
s.highScore.SetBody(strconv.Itoa(game.Score.High))
s.highScore.SetBody(strconv.Itoa(game.HighScore))
s.timer.SetText(game.Timer.Time.String())
s.newGame.Update(s.win)

Expand Down Expand Up @@ -263,7 +263,7 @@ func (s *SingleplayerScreen) updateLose(game backend.Game) {

s.heading.SetText("Game over!")
s.loseDialog.SetText(fmt.Sprintf(
"You earned %d points in %v.", game.Score.Current, game.Timer.Duration(),
"You earned %d points in %v.", game.Score, game.Timer.Duration(),
))

s.menu.Update(s.win)
Expand Down

0 comments on commit b7bd4a6

Please sign in to comment.