summaryrefslogtreecommitdiff
path: root/pkg/ui/views/game.go
blob: 7331f28995a13eed8f1148e19a7bc5141be84f29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package views

import (
	"fmt"
	"strings"

	"github.com/boozec/rahanna/internal/api/database"
	"github.com/boozec/rahanna/internal/network"
	"github.com/boozec/rahanna/pkg/ui/multiplayer"
	"github.com/charmbracelet/bubbles/list"
	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/notnil/chess"
)

// GameModel represents the state of the game view.
type GameModel struct {
	// UI dimensions
	width  int
	height int

	// UI state
	err  error
	keys gameKeyMap

	// Game state
	peer               string
	currentGameID      int
	game               *database.Game
	network            *multiplayer.GameNetwork
	chessGame          *chess.Game
	incomingMoves      chan string
	turn               int
	availableMovesList list.Model
}

// NewGameModel creates a new GameModel.
func NewGameModel(width, height int, peer string, currentGameID int, network *multiplayer.GameNetwork) GameModel {
	listDelegate := list.NewDefaultDelegate()
	listDelegate.ShowDescription = false
	listDelegate.Styles.SelectedTitle = lipgloss.NewStyle().
		Border(lipgloss.NormalBorder(), false, false, false, true).
		BorderForeground(highlightColor).
		Foreground(highlightColor).
		Padding(0, 0, 0, 1)

	moveList := list.New([]list.Item{}, listDelegate, width/4, height/2)
	moveList.Styles.Title = lipgloss.NewStyle().
		Background(highlightColor).
		Foreground(lipgloss.Color("230")).
		Padding(0, 1)

	return GameModel{
		width:              width,
		height:             height,
		keys:               defaultGameKeyMap,
		peer:               peer,
		currentGameID:      currentGameID,
		network:            network,
		chessGame:          chess.NewGame(chess.UseNotation(chess.UCINotation{})),
		incomingMoves:      make(chan string),
		turn:               0,
		availableMovesList: moveList,
	}
}

// Init initializes the GameModel.
func (m GameModel) Init() tea.Cmd {
	ClearScreen()
	return tea.Batch(textinput.Blink, m.getGame(), m.getMoves(), m.updateMovesListCmd())
}

// Update handles incoming messages and updates the GameModel.
func (m GameModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	if exit := handleExit(msg); exit != nil {
		return m, exit
	}

	var cmds []tea.Cmd
	var cmd tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m, cmd = m.handleWindowSizeMsg(msg)
		cmds = append(cmds, cmd)
	case UpdateMovesListMsg:
		m = m.handleUpdateMovesListMsg()
	case tea.KeyMsg:
		m, cmd = m.handleKeyMsg(msg)
		cmds = append(cmds, cmd)
	case ChessMoveMsg:
		m, cmd = m.handleChessMoveMsg(msg)
		cmds = append(cmds, cmd)
	case database.Game:
		m = m.handleDatabaseGameMsg(msg)
		cmds = append(cmds, m.updateMovesListCmd())
	}

	if m.isMyTurn() {
		m.availableMovesList, cmd = m.availableMovesList.Update(msg)
		switch msg := msg.(type) {
		case tea.KeyMsg:
			if msg.Type == tea.KeyEnter {
				selectedItem := m.availableMovesList.SelectedItem()
				if selectedItem != nil {
					moveStr := strings.Replace(selectedItem.(item).Title(), " → ", "", 1)
					m.network.Server.Send(network.NetworkID(m.peer), []byte(moveStr))
					m.chessGame.MoveStr(moveStr)
					m.turn++
					cmds = append(cmds, m.getMoves(), m.updateMovesListCmd())
				}
			}
		}
		cmds = append(cmds, cmd)
	}

	return m, tea.Batch(cmds...)
}

// View renders the GameModel.
func (m GameModel) View() string {
	formWidth := getFormWidth(m.width)

	if m.game == nil {
		return "Loading game..."
	}

	listWidth := formWidth / 4
	boardWidth := formWidth / 2
	notationWidth := formWidth - listWidth - boardWidth - 2

	listHeight := m.height / 3
	boardHeight := m.height / 3
	notationHeight := m.height - listHeight - boardHeight - 2

	listStyle := lipgloss.NewStyle().Width(listWidth).Height(listHeight).Padding(0, 1)
	boardStyle := lipgloss.NewStyle().Width(boardWidth).Height(boardHeight).Align(lipgloss.Center).Padding(0, 1)
	notationStyle := lipgloss.NewStyle().Width(notationWidth).Height(notationHeight).Padding(0, 1)

	var availableMovesListView string

	if m.isMyTurn() {
		m.availableMovesList.SetSize(listWidth, listHeight-2)
		availableMovesListView = listStyle.Render(m.availableMovesList.View())
	} else {
		availableMovesListView = listStyle.Render(lipgloss.Place(listWidth, listHeight, lipgloss.Center, lipgloss.Center, "Wait your turn"))
	}

	var movesListStr string

	for i, move := range m.chessGame.Moves() {
		if i%2 == 0 {
			movesListStr += altCodeStyle.Render(fmt.Sprintf("[%d]", i/2)) + fmt.Sprintf(" %s → %s", move.S1().String(), move.S2().String())
		} else {
			movesListStr += fmt.Sprintf(", %s → %s\n", move.S1().String(), move.S2().String())
		}
	}

	// TODO: a faster solution withoout strings.Split and strings.Join
	moves := strings.Split(movesListStr, "[")
	if len(moves) > 10 {
		start := len(moves) - 10
		movesListStr = "[" + strings.Join(moves[start:], "[")
	} else {
		movesListStr = strings.Join(moves, "[")
	}

	var errorStr string
	if m.err != nil {
		errorStr = m.err.Error()
	}

	content := lipgloss.JoinVertical(
		lipgloss.Center,
		lipgloss.NewStyle().Foreground(lipgloss.Color("#f1c40f")).Render(fmt.Sprintf("%s vs %s", m.game.Player1.Username, m.game.Player2.Username)),
		lipgloss.JoinHorizontal(
			lipgloss.Top,
			availableMovesListView,
			boardStyle.Render(
				m.chessGame.Position().Board().Draw(),
			),
			notationStyle.Render(
				lipgloss.JoinVertical(
					lipgloss.Left,
					lipgloss.NewStyle().Background(highlightColor).Foreground(lipgloss.Color("230")).Padding(0, 1).MarginBottom(1).Render("Moves"),
					movesListStr,
				),
			),
		),
	)

	windowContent := m.buildWindowContent(content, formWidth)
	buttons := m.renderNavigationButtons()

	centeredContent := lipgloss.JoinVertical(
		lipgloss.Center,
		getLogo(m.width),
		windowContent,
		errorStyle.Width(formWidth/2).Render(errorStr),
		lipgloss.NewStyle().MarginTop(2).Render(buttons),
	)

	return lipgloss.Place(
		m.width,
		m.height,
		lipgloss.Center,
		lipgloss.Center,
		centeredContent,
	)
}