~tslocum/netris

ref: 133d9560ae1317eba90765352979e492e856c0fb netris/cmd/netris/gui.go -rw-r--r-- 12.2 KiB View raw
                                                                                
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"sort"
	"strconv"
	"sync"
	"time"

	"git.sr.ht/~tslocum/netris/pkg/event"
	"git.sr.ht/~tslocum/netris/pkg/game"
	"git.sr.ht/~tslocum/netris/pkg/mino"
	"github.com/gdamore/tcell"
	"github.com/tslocum/tview"
)

var (
	closedGUI bool

	inputActive      bool
	capturingKeybind bool
	showDetails      bool

	app       *tview.Application
	inputView *tview.InputField
	mtx       *tview.TextView
	side      *tview.TextView
	buffer    *tview.TextView
	recent    *tview.TextView

	joinedGame bool

	draw     = make(chan event.DrawObject, game.CommandQueueSize)
	joinGame = make(chan int, game.CommandQueueSize)

	renderLock   = new(sync.Mutex)
	renderBuffer bytes.Buffer

	multiplayerMatrixSize int
	screenPadding         int

	screenW, screenH       int
	newScreenW, newScreenH int

	nickname      = "Anonymous"
	nicknameDraft string

	inputHeight, mainHeight, previewWidth, newLogLines int

	profileCPU *os.File

	buttonKeybindRotateCCW *tview.Button
	buttonKeybindRotateCW  *tview.Button
	buttonKeybindMoveLeft  *tview.Button
	buttonKeybindMoveRight *tview.Button
	buttonKeybindSoftDrop  *tview.Button
	buttonKeybindHardDrop  *tview.Button
	buttonKeybindCancel    *tview.Button
	buttonKeybindSave      *tview.Button

	buttonCancel *tview.Button
	buttonStart  *tview.Button
)

const DefaultStatusText = "Press Enter to chat, Z/X to rotate, arrow keys or HJKL to move/drop"

var (
	renderHLine    = []byte(string(tcell.RuneHLine))
	renderVLine    = []byte(string(tcell.RuneVLine))
	renderLTee     = []byte(string(tcell.RuneLTee))
	renderRTee     = []byte(string(tcell.RuneRTee))
	renderULCorner = []byte(string(tcell.RuneULCorner))
	renderURCorner = []byte(string(tcell.RuneURCorner))
	renderLLCorner = []byte(string(tcell.RuneLLCorner))
	renderLRCorner = []byte(string(tcell.RuneLRCorner))
)

func resetPlayerSettingsForm() {
	playerSettingsForm.Clear(true).AddInputField("Name", nickname, 0, nil, func(text string) {
		nicknameDraft = text
	}).AddButton("Cancel", func() {
		titleScreen = 1
		titleSelectedButton = 0

		app.SetRoot(titleContainerGrid, true)
		updateTitle()
	}).AddButton("Save", func() {
		if nicknameDraft != "" && game.Nickname(nicknameDraft) != nickname {
			nickname = game.Nickname(nicknameDraft)

			if activeGame != nil {
				activeGame.Event <- &event.NicknameEvent{Nickname: nickname}
			}
		}

		titleScreen = 1
		titleSelectedButton = 0

		app.SetRoot(titleContainerGrid, true)
		updateTitle()
	})
}

// BS 1: 10x10
// BS 2: 20x20
// BS 3: 40x40
func handleResize(screen tcell.Screen) {
	newScreenW, newScreenH = screen.Size()
	if newScreenW == screenW && newScreenH == screenH {
		return
	}

	screenW, screenH = newScreenW, newScreenH

	if !fixedBlockSize {
		if screenW >= 106 && screenH >= 46 {
			blockSize = 3
		} else if screenW >= 56 && screenH >= 24 {
			blockSize = 2
		} else {
			blockSize = 1
		}
	}

	xMultiplier := 1
	if blockSize == 2 {
		xMultiplier = 2
	} else if blockSize == 3 {
		xMultiplier = 4
	}

	if blockSize == 1 {
		mainHeight = 10 + 3
	} else if blockSize == 2 {
		mainHeight = 20 + 3
	} else {
		mainHeight = 40 + 3
	}

	if screenH > mainHeight+9 {
		screenPadding = 2
		mainHeight++
		inputHeight = 2
	} else if screenH > mainHeight+7 {
		screenPadding = 2
		mainHeight++
		inputHeight = 1
	} else if screenH > mainHeight+5 {
		screenPadding = 1
		mainHeight++
		inputHeight = 1
	} else if screenH > mainHeight+3 {
		screenPadding = 1
		inputHeight = 1
	} else {
		screenPadding = 0
		inputHeight = 0
	}

	if blockSize == 1 {
		previewWidth = 9
	} else if blockSize == 2 {
		previewWidth = 10
	} else {
		previewWidth = 18
	}

	multiplayerMatrixSize = ((screenW - screenPadding) - ((10 * xMultiplier) + previewWidth + 6)) / ((10 * xMultiplier) + 4)

	newLogLines = ((screenH - mainHeight) - inputHeight) - screenPadding
	if newLogLines > 0 {
		showLogLines = newLogLines
	} else {
		showLogLines = 1
	}

	gameGrid.SetRows(screenPadding, mainHeight, inputHeight, -1).SetColumns(screenPadding+1, 3+(10*xMultiplier), previewWidth, -1)

	draw <- event.DrawAll
}

func drawAll() {
	if activeGame == nil {
		return
	}

	renderPlayerGUI()
	renderMultiplayerGUI()
}

func drawMessages() {
	recent.ScrollToEnd()
}

func drawPlayerMatrix() {
	renderPlayerGUI()
}

func drawMultiplayerMatrixes() {
	renderMultiplayerGUI()
}

func handleDraw() {
	var o event.DrawObject
	for o = range draw {
		switch o {
		case event.DrawMessages:
			app.QueueUpdateDraw(drawMessages)
		case event.DrawPlayerMatrix:
			app.QueueUpdateDraw(drawPlayerMatrix)
		case event.DrawMultiplayerMatrixes:
			app.QueueUpdateDraw(drawMultiplayerMatrixes)
		default:
			app.QueueUpdateDraw(drawAll)
		}
	}
}

func closeGUI() {
	if closedGUI {
		return
	}
	closedGUI = true

	app.Stop()
}

func setInputStatus(active bool) {
	if inputActive == active {
		return
	}

	inputActive = active

	app.QueueUpdateDraw(func() {
		inputView.SetText("")
		if inputActive {
			app.SetFocus(inputView)
		} else {
			app.SetFocus(nil)
		}
	})
}

func setShowDetails(active bool) {
	if showDetails == active {
		return
	}

	showDetails = active
	draw <- event.DrawAll
}

func renderPlayerGUI() {
	g := activeGame
	if g == nil || len(g.Players) == 0 {
		return
	}

	renderLock.Lock()
	renderMatrixes([]*mino.Matrix{g.Players[g.LocalPlayer].Matrix})
	mtx.Clear()
	mtx.Write(renderBuffer.Bytes())
	renderLock.Unlock()

	player := g.Players[g.LocalPlayer]
	m := g.Players[g.LocalPlayer].Matrix

	p := mino.NewPiece(m.Bag.Next(), mino.Point{0, 0})

	player.Preview.Clear()

	if !player.Matrix.GameOver {
		err := player.Preview.Add(p, p.Solid, mino.Point{0, 0}, false)
		if err != nil {
			log.Fatalf("failed to render preview matrix: failed to add ghost piece: %+v", err)
		}
	}

	m.Lock()
	var (
		comboTime float64
		combo     int
	)
	if m.Combo > 0 && time.Until(m.ComboEnd) > 0 {
		comboTime = 1.0 + (float64(time.Until(m.ComboEnd)) / 1000000000)
		combo = m.Combo
	}

	var speed = strconv.Itoa(m.Speed)
	if m.Speed < 100 {
		speed = " " + speed
	}

	renderLock.Lock()
	renderMatrixes([]*mino.Matrix{g.Players[g.LocalPlayer].Preview})

	if blockSize == 1 {
		renderBuffer.WriteString(fmt.Sprintf(" Combo\n   %d\n\n Timer\n   %.0f\n\nPending\n   %d\n\n Speed\n  %s", combo, comboTime, m.PendingGarbage, speed))
	} else if blockSize == 2 {
		renderBuffer.WriteString(fmt.Sprintf("\n Combo\n\n   %d\n\n\n Timer\n\n   %.0f\n\n\nPending\n\n   %d\n\n\n Speed\n\n  %s", combo, comboTime, m.PendingGarbage, speed))
	} else if blockSize == 3 {
		renderBuffer.WriteString(fmt.Sprintf("\n\n\n\n\n    Combo\n\n      %d\n\n\n\n\n\n    Timer\n\n      %.0f\n\n\n\n\n\n   Pending\n\n      %d\n\n\n\n\n\n    Speed\n\n     %s", combo, comboTime, m.PendingGarbage, speed))
	}

	side.Clear()
	side.Write(renderBuffer.Bytes())

	renderLock.Unlock()
	m.Unlock()
}

func renderMultiplayerGUI() {
	g := activeGame
	if g == nil {
		return
	}

	g.Lock()

	if g.LocalPlayer == game.PlayerUnknown || len(g.Players) <= 1 {
		buffer.Clear()
		g.Unlock()
		return
	}

	var (
		playerIDs = make([]int, len(g.Players)-1)
		i         int
	)
	for playerID := range g.Players {
		if playerID == g.LocalPlayer {
			continue
		}

		playerIDs[i] = playerID
		i++
	}
	sort.Ints(playerIDs)

	i = 0
	var matrixes []*mino.Matrix
	for _, playerID := range playerIDs {
		if g.Players[playerID] == nil {
			continue
		}

		i++
		matrixes = append(matrixes, g.Players[playerID].Matrix)

		if i == multiplayerMatrixSize {
			break
		}
	}

	g.Unlock()

	renderLock.Lock()
	renderMatrixes(matrixes)
	buffer.Clear()
	buffer.Write(renderBuffer.Bytes())
	renderLock.Unlock()
}

func renderPlayerDetails(m *mino.Matrix, bs int) {
	xMultiplier := 1
	if bs == 2 {
		xMultiplier = 2
	} else if bs == 3 {
		xMultiplier = 4
	}

	var buf string
	if !showDetails {
		buf = m.PlayerName
	} else {
		if blockSize == 1 {
			buf = fmt.Sprintf("%d/%d @ %d", m.GarbageSent, m.GarbageReceived, m.Speed)
		} else {
			buf = fmt.Sprintf("%d / %d  @  %d", m.GarbageSent, m.GarbageReceived, m.Speed)
		}
	}
	if len(buf) > m.W*xMultiplier {
		buf = buf[:m.W*xMultiplier]
	}

	padBuf := ((m.W*xMultiplier - len(buf)) / 2) + 1
	for i := 0; i < padBuf; i++ {
		renderBuffer.WriteRune(' ')
	}
	renderBuffer.WriteString(buf)
	padBuf = m.W*xMultiplier + 2 - len(buf) - padBuf
	for i := 0; i < padBuf; i++ {
		renderBuffer.WriteRune(' ')
	}
}

func renderMatrixes(mx []*mino.Matrix) {
	renderBuffer.Reset()
	if len(mx) == 0 {
		return
	}

	bs := blockSize
	mt := mx[0].Type
	mh := mx[0].H
	div := "  "

	var nextPieceWidth = 0
	if mt == mino.MatrixPreview {
		renderBuffer.WriteRune('\n')
		if mx[0].Bag != nil {
			p := mx[0].Bag.Next()
			if p != nil {
				nextPieceWidth, _ = p.Size()
			}
		}

		if bs == 3 {
			renderBuffer.WriteRune('\n')
		}
	} else if mt == mino.MatrixCustom {
		bs = 1
	}

	xMultiplier := 1
	if bs == 2 {
		xMultiplier = 2
	} else if bs == 3 {
		xMultiplier = 4
	}

	for i := range mx {
		mx[i].Lock()
		mx[i].DrawPiecesL()
	}

	if mt == mino.MatrixStandard {
		for i := range mx {
			if i > 0 {
				renderBuffer.WriteString(div)
			}

			renderBuffer.Write(renderULCorner)
			for x := 0; x < mx[i].W*xMultiplier; x++ {
				renderBuffer.Write(renderHLine)
			}
			renderBuffer.Write(renderURCorner)
		}
		renderBuffer.WriteRune('\n')
	}

	if bs == 1 {
		for y := mh - 1; y >= 0; y -= 2 {
			for i, m := range mx {
				if i > 0 {
					renderBuffer.WriteString(div)
				}

				if m.Type == mino.MatrixStandard {
					renderBuffer.Write(renderVLine)
				} else if m.Type == mino.MatrixPreview {
					renderBuffer.WriteRune(' ')
				}

				for x := 0; x < m.W; x++ {
					renderBuffer.WriteRune('[')
					renderBuffer.Write(mino.Colors[m.Block(x, y-1)])
					renderBuffer.WriteRune(':')
					renderBuffer.Write(mino.Colors[m.Block(x, y)])
					renderBuffer.WriteRune(']')
					renderBuffer.WriteRune('▄')
					renderBuffer.Write([]byte("[#FFFFFF:#000000]"))
				}

				if m.Type == mino.MatrixStandard {
					renderBuffer.Write(renderVLine)
				}
			}

			if y > 1 || mt != mino.MatrixCustom {
				renderBuffer.WriteRune('\n')
			}
		}
	} else if bs == 2 {
		for y := mh - 1; y >= 0; y-- {
			for i, m := range mx {
				if i > 0 {
					renderBuffer.WriteString(div)
				}

				if m.Type == mino.MatrixStandard {
					renderBuffer.Write(renderVLine)
				} else if m.Type == mino.MatrixPreview {
					if nextPieceWidth < 4 {
						renderBuffer.WriteRune(' ')
					}
				}

				for x := 0; x < m.W; x++ {
					renderBuffer.WriteRune('[')
					renderBuffer.Write(mino.Colors[m.Block(x, y)])
					renderBuffer.WriteRune(']')
					renderBuffer.WriteRune('█')
					renderBuffer.WriteRune('█')
					renderBuffer.Write([]byte("[#FFFFFF]"))
				}

				if m.Type == mino.MatrixStandard {
					renderBuffer.Write(renderVLine)
				}
			}

			if y != 0 || mt != mino.MatrixCustom {
				renderBuffer.WriteRune('\n')
			}
		}
	} else {
		for y := mh - 1; y >= 0; y-- {
			for repeat := 0; repeat < 2; repeat++ {
				for i, m := range mx {
					if i > 0 {
						renderBuffer.WriteString(div)
					}

					if m.Type == mino.MatrixStandard {
						renderBuffer.Write(renderVLine)
					} else if m.Type == mino.MatrixPreview {
						if nextPieceWidth < 4 {
							renderBuffer.WriteRune(' ')
						}
					}

					for x := 0; x < m.W; x++ {
						renderBuffer.WriteRune('[')
						renderBuffer.Write(mino.Colors[m.Block(x, y)])
						renderBuffer.WriteRune(']')
						renderBuffer.WriteRune('█')
						renderBuffer.WriteRune('█')
						renderBuffer.WriteRune('█')
						renderBuffer.WriteRune('█')
						renderBuffer.Write([]byte("[#FFFFFF]"))
					}

					if m.Type == mino.MatrixStandard {
						renderBuffer.Write(renderVLine)
					}
				}

				if y != 0 || mt != mino.MatrixCustom {
					renderBuffer.WriteRune('\n')
				}
			}
		}
	}

	if mt == mino.MatrixStandard {
		for i := range mx {
			if i > 0 {
				renderBuffer.WriteString(div)
			}

			renderBuffer.Write(renderLLCorner)
			for x := 0; x < mx[i].W*xMultiplier; x++ {
				renderBuffer.Write(renderHLine)
			}
			renderBuffer.Write(renderLRCorner)
		}

		renderBuffer.WriteRune('\n')

		for i, m := range mx {
			if i > 0 {
				renderBuffer.WriteString(div)
			}

			renderPlayerDetails(m, bs)
		}
	}

	for i := range mx {
		mx[i].Unlock()
	}
}

func logMessage(message string) {
	logMutex.Lock()

	var prefix string
	if !wroteFirstLogMessage {
		wroteFirstLogMessage = true
	} else {
		prefix = "\n"
	}

	recent.Write([]byte(prefix + time.Now().Format(event.LogFormat) + " " + message))

	draw <- event.DrawMessages

	logMutex.Unlock()
}