board.go 18.6 KB
Newer Older
Michael Gebhard's avatar
Michael Gebhard committed
1
2
3
4
5
6
7
8
9
package main

import (
	tg "fahrradwurstmond2.0/telnet_gui"
	"os"
	"bufio"
	"bytes"
	"strings"
	"strconv"
ceddral's avatar
ceddral committed
10
	"sync"
Michael Gebhard's avatar
Michael Gebhard committed
11
12
13
14
15
16
17
18
19
)


const (
	pieceWidth int = 5
	pieceHeight    = 3
)
// 'constants'
var (
ceddral's avatar
ceddral committed
20
21
	typeBG map[FType]tg.Color
	typeFG map[FType]tg.Color
Michael Gebhard's avatar
Michael Gebhard committed
22
23
24
25
)

func InitBoard() {
	// I miss c++ constexpr
ceddral's avatar
ceddral committed
26
27
28
29
30
31
32
33
34
35
	typeBG = make(map[FType]tg.Color)
	typeFG = make(map[FType]tg.Color)
	typeBG[fCloister] = tg.ColorRed
	typeBG[fFarm] = tg.ColorGreen
	typeBG[fRoad] = tg.ColorGreen
	typeBG[fCity] = tg.ColorYellow
	typeFG[fCloister] = tg.ColorBlack
	typeFG[fFarm] = tg.ColorBlack
	typeFG[fRoad] = tg.ColorWhite
	typeFG[fCity] = tg.ColorBlack
Michael Gebhard's avatar
Michael Gebhard committed
36
37
}

ceddral's avatar
ceddral committed
38
39
40
41
42
43
44
45
46
47
type FType byte

const (
	fRoad     FType = 'w'
	fCity     FType = 'r'
	fCloister FType = 'm'
	fFarm     FType = 'b'
	fTower    FType = 't'
)

48
49
50
51
52
53
54
55
type FSpecial byte

const (
	fPennant   FSpecial = 'p'
	fInn       FSpecial = 'i'
	fCathedral FSpecial = 'c'
)

Michael Gebhard's avatar
Michael Gebhard committed
56
type Field struct {
57
	preRendered []byte
ceddral's avatar
ceddral committed
58
	t  FType
ceddral's avatar
ceddral committed
59
	id byte
Michael Gebhard's avatar
Michael Gebhard committed
60
61
62
63
64
65
66
	fgOverride tg.Color
	c  byte
	placeable bool
}

type Piece struct {
	f [][][]Field // 'graphic' representation [rotation][row][col]
ceddral's avatar
ceddral committed
67
	fieldIdToType map[byte]FType
68
	fieldIdToSpecial map[byte][]FSpecial
Michael Gebhard's avatar
Michael Gebhard committed
69
70
71
72
73
74
75
76
	copies int
}

type Rotation int

type Place struct {
	piece *Piece
	rot Rotation
ceddral's avatar
ceddral committed
77
	fieldIdToPlayer map[byte]*GamePlayer
ceddral's avatar
ceddral committed
78
	fieldIdToToken  map[byte]Token
Michael Gebhard's avatar
Michael Gebhard committed
79
80
}

ceddral's avatar
ceddral committed
81
type Board struct {
ceddral's avatar
ceddral committed
82
	// bounding box of placeable area
ceddral's avatar
ceddral committed
83
84
85
86
87
	minx int // min inclusive
	miny int
	maxx int // max exclusive
	maxy int
	m *sync.Map
ceddral's avatar
ceddral committed
88
	free *sync.Map
ceddral's avatar
ceddral committed
89
}
Michael Gebhard's avatar
Michael Gebhard committed
90

ceddral's avatar
ceddral committed
91
func NewPlace(p *Piece, rot Rotation) Place {
ceddral's avatar
ceddral committed
92
	return Place{p, rot, make(map[byte]*GamePlayer), make(map[byte]Token)}
ceddral's avatar
ceddral committed
93
94
}

ceddral's avatar
ceddral committed
95
func NewBoard(g *Game) (board *Board) {
ceddral's avatar
ceddral committed
96
	board = &Board{0, 0, 1, 1, &sync.Map{}, &sync.Map{}}
ceddral's avatar
ceddral committed
97
	board.Set(0, 0, NewPlace(g.drawPiece(), 0))
Michael Gebhard's avatar
Michael Gebhard committed
98
99
100
	return
}

ceddral's avatar
ceddral committed
101
102
103
104
105
106
type Coord struct {
	x int
	y int
}

func (b *Board) Set(x, y int, p Place) {
ceddral's avatar
ceddral committed
107
108
109
110
	if x <= b.minx { b.minx = x - 1 }
	if y <= b.miny { b.miny = y - 1}
	if b.maxx <= x + 1 { b.maxx = x + 2 }
	if b.maxy <= y + 1 { b.maxy = y + 2 }
ceddral's avatar
ceddral committed
111
	b.m.Store(Coord{x, y}, p)
ceddral's avatar
ceddral committed
112
113
114
115
116
117
118
119
	b.free.Delete(Coord{x, y})
	cs := getAdjacentCoords(x, y)
	for _, c := range cs {
		_, ok := b.Get(c.x, c.y)
		if !ok {
			b.free.Store(Coord{c.x, c.y}, struct{}{})
		}
	}
ceddral's avatar
ceddral committed
120
121
122
123
124
125
126
127
128
129
130
}

func (b *Board) Get(x, y int) (Place, bool) {
	ip, ok := b.m.Load(Coord{x, y})
	p := Place{}
	if ok {
		p = ip.(Place)
	}
	return p, ok
}

131
132
133
134
135
136
func (b *Board) GetWritable(x, y int) (Place, bool) {
	pro, ok := b.Get(x, y)
	p := pro
	if ok {
		p.fieldIdToPlayer = make(map[byte]*GamePlayer)
		copyMapByteGamePlayer(p.fieldIdToPlayer, pro.fieldIdToPlayer)
ceddral's avatar
ceddral committed
137
138
		p.fieldIdToToken = make(map[byte]Token)
		copyMapByteToken(p.fieldIdToToken, pro.fieldIdToToken)
139
140
141
142
	}
	return p, ok
}

143
144
145
146
147
148
type MapCursor struct {
	x int
	y int
	id byte
}

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
func (b *Board) GetNeighbourStructures(c MapCursor, includeMissing bool) (res []MapCursor) {
	res = make([]MapCursor, 0)
	place, _ := b.Get(c.x, c.y)
	nCs := getAdjacentCoords(c.x, c.y)
	for _, nCoord := range nCs {
		nPlace, nOk := b.Get(nCoord.x, nCoord.y)
		dirx := nCoord.x - c.x
		diry := nCoord.y - c.y
		fmidx  := 2 + (2 * dirx)
		fmidy  := 1 + diry
		nfmidx := 2 - (2 * dirx)
		nfmidy := 1 - diry
		// iterate left middle right edge fields
		for _, lmr := range []int{-1, 0, 1} {
			fx := fmidx + lmr * diry
			fy := fmidy + lmr * dirx
			nfx := nfmidx + lmr * diry
			nfy := nfmidy + lmr * dirx
			// check if this edge field is part of our structure
			if place.piece.f[place.rot][fy][fx].id != c.id {
				continue
			}
			nc := MapCursor{nCoord.x, nCoord.y, 0}
			if !nOk {
				// cursor with 0 id represents missing neighbour / open structure edge
				if includeMissing {
					res = append(res, nc)
				}
				break
			}
			nid := nPlace.piece.f[nPlace.rot][nfy][nfx].id
			nc.id = nid
			res = append(res, nc)
		}
	}
	return
}

187
188
189
190
191
192
193
194
195
func (b *Board) MapStructure(f func(interface{}, MapCursor)interface{}, acc interface{}, x, y int, fieldId byte) interface{} {
	visited := make(map[MapCursor]struct{})
	queue := []MapCursor{MapCursor{x, y, fieldId}}
	var c MapCursor
	for len(queue) > 0 {
		c, queue = queue[0], queue[1:]
		if _, ok := visited[c]; ok {
			continue
		}
196
		acc = f(acc, c)
197
		visited[c] = struct{}{}
198
199
200
		for _, n := range b.GetNeighbourStructures(c, false) {
			if _, ok := visited[n]; !ok {
				queue = append(queue, n)
201
202
203
204
205
206
			}
		}
	}
	return acc
}

207
208
func getAdjacentCoords(x, y int) []Coord {
	r := make([]Coord, 0, 4)
ceddral's avatar
ceddral committed
209
210
211
	dx := 1
	dy := 0
	for i := 0; i < 4; i++ {
212
213
		r = append(r, Coord{x + dx, y + dy})
		// iterate 4 adjacent coords clockwise
ceddral's avatar
ceddral committed
214
215
216
		dx, dy = dy, dx
		dx = -dx
	}
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
	return r
}

func (b *Board) GetNeighbours(x, y int) ([]Coord, []Place) {
	cs := getAdjacentCoords(x, y)
	rc := make([]Coord, 0, 4)
	rp := make([]Place, 0, 4)
	for _, c := range cs {
		p, ok := b.Get(c.x, c.y)
		if ok {
			rc = append(rc, c)
			rp = append(rp, p)
		}
	}
	return rc, rp
}

func (b *Board) HasNeighbour(x, y int) (ok bool) {
	cs := getAdjacentCoords(x, y)
	for _, c := range cs {
		_, ok := b.Get(c.x, c.y)
		if ok { return true }
	}
ceddral's avatar
ceddral committed
240
241
242
	return false
}

ceddral's avatar
ceddral committed
243
244
245
246
247
248
249
250
251
252
// assign score to majority players if structure is closed or game is ending
// TryScore may be called repeatedly on previously scored structure
func (b *Board) TryScore(x, y int, id byte, gameEnd bool) (closed bool, score int) {
	place, ok := b.Get(x, y)
	if !ok {
		return false, score
	}
	// evaluate score, closed
	closed = true
	score = 0
ceddral's avatar
ceddral committed
253
	baseScore := 0 // score but without multiplicators, e.g. just number of tiles in city or number of cities in farm
ceddral's avatar
ceddral committed
254
255
256
257
258
259
260
	pennants := 0
	switch place.piece.fieldIdToType[id] {
	case fCloister:
		for dx := -1; dx <= 1; dx++ {
			for dy := -1; dy <= 1; dy++ {
				_, ok := b.Get(x + dx, y + dy)
				if ok {
ceddral's avatar
ceddral committed
261
					baseScore++
ceddral's avatar
ceddral committed
262
263
264
				}
			}
		}
ceddral's avatar
ceddral committed
265
		score = baseScore
266
		closed = (score == 9)
ceddral's avatar
ceddral committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
	case fRoad:
		visited := make(map[Coord]struct{})
		hasInn := false
		b.MapStructure(func(acc interface{}, cur MapCursor)interface{} {
			c := Coord{cur.x, cur.y}
			if _, ok := visited[c]; !ok {
				place, _ := b.Get(c.x, c.y) // can never fail, map only visits placed pieces
				for _, s := range place.piece.fieldIdToSpecial[cur.id] {
					switch s {
					case fInn: hasInn = true
					}
				}
			}
			visited[c] = struct{}{}
			for _, nStructure := range b.GetNeighbourStructures(cur, true) {
				if 0 == nStructure.id {
					closed = false
				}
			}
			return struct{}{}
		}, struct{}{}, x, y, id)
ceddral's avatar
ceddral committed
288
289
		baseScore = len(visited)
		score = baseScore
ceddral's avatar
ceddral committed
290
		if closed && hasInn {
ceddral's avatar
ceddral committed
291
			score = 2 * baseScore
ceddral's avatar
ceddral committed
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
		} else if !closed && hasInn {
			score = 0
		}
	case fCity:
		visited := make(map[Coord]struct{})
		hasCathedral := false
		b.MapStructure(func(acc interface{}, cur MapCursor)interface{} {
			c := Coord{cur.x, cur.y}
			if _, ok := visited[c]; !ok {
				place, _ := b.Get(c.x, c.y) // can never fail, map only visits placed pieces
				for _, s := range place.piece.fieldIdToSpecial[cur.id] {
					switch s {
					case fPennant: pennants++
					case fCathedral: hasCathedral = true
					}
				}
			}
			visited[c] = struct{}{}
			for _, nStructure := range b.GetNeighbourStructures(cur, true) {
				if 0 == nStructure.id {
					closed = false
				}
			}
			return struct{}{}
		}, struct{}{}, x, y, id)
ceddral's avatar
ceddral committed
317
		baseScore = pennants + len(visited)
ceddral's avatar
ceddral committed
318
		if closed && hasCathedral {
ceddral's avatar
ceddral committed
319
			score = 3 * baseScore
ceddral's avatar
ceddral committed
320
		} else if closed && !hasCathedral {
ceddral's avatar
ceddral committed
321
			score = 2 * baseScore
ceddral's avatar
ceddral committed
322
		} else if !closed && !hasCathedral {
ceddral's avatar
ceddral committed
323
			score = 1 * baseScore
ceddral's avatar
ceddral committed
324
325
326
327
		} else if !closed && hasCathedral {
			score = 0
		}
	case fFarm:
ceddral's avatar
ceddral committed
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
		// collect city tiles connected to our farm
		connectedCityTiles := make(map[MapCursor]struct{})
		b.MapStructure(func(acc interface{}, c MapCursor)interface{} {
			place, _ := b.Get(c.x, c.y) // can never fial, map only visits placed pieces
			// iterate neighbour fields of all fields within piece
			fs := place.piece.f[place.rot]
			for y := range fs {
				for x, f := range fs[y] {
					// iterate top left half of neighbours
					// 0 1 2
					// 3 x -
					// - - -
					for i := 0; i < 4; i++ {
						dx := -1 + (i % 3)
						dy := -1 + (i / 3)
						ny := y + dy
						nx := x + dx
						if ny < 0 { continue }
						if ny >= len(fs) { continue }
						if nx < 0 { continue }
						if nx >= len(fs[ny]) { continue }
						nf := fs[y + dy][x + dx]
						if f.id != c.id && nf.id != c.id {
							// neither of the pair is our farm
							continue
						}
						if f.t == fCity {
							connectedCityTiles[MapCursor{c.x, c.y, f.id}] = struct{}{}
						}
						if nf.t == fCity {
							connectedCityTiles[MapCursor{c.x, c.y, nf.id}] = struct{}{}
						}
					}
				}
			}
			return struct{}{}
		}, struct{}{}, x, y, id)
		// filter city tiles belonging to the same city
		baseScore := 0
		for c, _ := range connectedCityTiles {
			b.MapStructure(func(acc interface{}, cur MapCursor)interface{} {
				delete(connectedCityTiles, cur)
				return struct{}{}
			}, struct{}{}, c.x, c.y, c.id)
			baseScore++
		}
		closed = false
		score = 3 * baseScore
ceddral's avatar
ceddral committed
376
377
378
379
380
381
382
383
384
	default:
		panic("trying to score unknown structure type")
	}

	if !closed && !gameEnd {
		return
	}
	// assign score, return followers to players
	majority := 0
ceddral's avatar
ceddral committed
385
	playerToBonus := make(map[*GamePlayer]int)
ceddral's avatar
ceddral committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
	// map player -> sum of token weights
	weights := make(map[*GamePlayer]int)
	b.MapStructure(func(acc interface{}, c MapCursor)interface{} {
		place, _ := b.GetWritable(c.x, c.y) // can never fail, map only visits placed pieces
		p := place.fieldIdToPlayer[c.id]
		if p == nil {
			return struct{}{}
		}
		t := place.fieldIdToToken[c.id]
		if _, ok := weights[p]; !ok {
			weights[p] = 0
		}
		weights[p] += t.weight(pennants)
		if majority < weights[p] {
			majority = weights[p]
		}
ceddral's avatar
ceddral committed
402
403
404
		if t == tPig {
			playerToBonus[p] = baseScore
		}
ceddral's avatar
ceddral committed
405
406
407
408
409
410
411
412
413
414
415
		// return followers
		delete(place.fieldIdToPlayer, c.id)
		delete(place.fieldIdToToken, c.id)
		p.tokens[t]++
		b.Set(c.x, c.y, place)
		return struct{}{}
	}, struct{}{}, x, y, id)
	if majority > 0 {
		for p, w := range weights {
			if majority == w {
				p.score += score
ceddral's avatar
ceddral committed
416
417
418
				if bonus, ok := playerToBonus[p]; ok {
					p.score += bonus
				}
ceddral's avatar
ceddral committed
419
420
421
422
423
424
			}
		}
	}
	return
}

425
426
427
428
429
var (
	checkerBoardBlockA []byte = tg.RenderBlock(tg.ColorDefault, tg.ColorDefault, ' ', ^tg.TermUnderline, ^tg.TermBold)
	checkerBoardBlockB []byte = tg.RenderBlock(tg.ColorDefault, tg.ColorDefault, '\'', ^tg.TermUnderline, ^tg.TermBold)
)

430
431
432
433
434
435
436
437
438
439
440
441
type PieceMode int
const (
	// modes available inside board view
	PMPlayers PieceMode = iota
	PMTokens
	PMMaxBoard
	// other modes
	PMPlaces
	PMMax
)

func (p *Piece) render(v *tg.View, viewx, viewy int, board *Board, boardx, boardy int, rot Rotation, mode PieceMode, s GameState) {
Michael Gebhard's avatar
Michael Gebhard committed
442
443
	for y := 0; y < pieceHeight; y++ {
		for x := 0; x < pieceWidth; x++ {
ceddral's avatar
ceddral committed
444
			if p == nil {
445
				b := checkerBoardBlockA
ceddral's avatar
ceddral committed
446
				if (boardx + boardy) % 2 == 0 {
447
					b = checkerBoardBlockB
ceddral's avatar
ceddral committed
448
				}
449
				v.DrawBlockRaw(b, viewx + x, viewy + y)
ceddral's avatar
ceddral committed
450
				continue
ceddral's avatar
ceddral committed
451
			}
Michael Gebhard's avatar
Michael Gebhard committed
452
453
			f := p.f[rot][y][x]
			// underline bottom corners if necessary
454
			underline := ^tg.TermUnderline
Michael Gebhard's avatar
Michael Gebhard committed
455
			if board != nil && y == pieceHeight - 1 {
456
457
458
459
460
461
462
463
464
465
466
467
				var downp *Piece
				var downpRot Rotation
				if spp, ok := s.(*StatePlacePiece); s != nil && ok && spp.boardx == boardx && spp.boardy == boardy+1 {
					downp = spp.p
					downpRot = spp.rot
				} else {
					place, ok := board.Get(boardx, boardy+1)
					if ok {
						downp = place.piece
						downpRot = place.rot
					}
				}
Michael Gebhard's avatar
Michael Gebhard committed
468
469
470
471
472
473
474
475
476
// Compare the fields ABCD in this and the downward neighbor piece
// to determine if A and C are are connected through B and D.
// Otherwise draw a seperator between A and C.
// Analogous for for the righthand side.
// | cur |
// |AB   |
// +-----+
// |CD   |
// | dwn |
477
				if downp != nil {
Michael Gebhard's avatar
Michael Gebhard committed
478
					A := f
ceddral's avatar
ceddral committed
479
					B := A
480
					C := downp.f[downpRot][0][x]
ceddral's avatar
ceddral committed
481
					D := C
Michael Gebhard's avatar
Michael Gebhard committed
482
483
					if x == 0 {
						B = p.f[rot][y][x+1]
484
						D = downp.f[downpRot][0][x+1]
Michael Gebhard's avatar
Michael Gebhard committed
485
486
487
					}
					if x == pieceWidth - 1 {
						B = p.f[rot][y][x-1]
488
						D = downp.f[downpRot][0][x-1]
Michael Gebhard's avatar
Michael Gebhard committed
489
490
					}
					if A.t == C.t && (A.id != B.id || C.id != D.id) {
491
						underline = tg.TermUnderline
Michael Gebhard's avatar
Michael Gebhard committed
492
493
494
495
496
497
498
499
500
					}
				}
			}
			fg := typeFG[f.t]
			if f.fgOverride != 0 {
				fg = f.fgOverride
			}
			c := f.c
			bg := typeBG[f.t]
501
502
503
			if spf, ok := s.(*StatePlaceFollower); s != nil && ok && spf.boardx == boardx && spf.boardy == boardy {
				mode = spf.mode
			}
ceddral's avatar
ceddral committed
504
			switch mode {
505
506
			case PMPlayers:
				if f.placeable && board != nil {
ceddral's avatar
ceddral committed
507
508
509
510
511
512
					if place, ok := board.Get(boardx, boardy); ok {
						if p, ok := place.fieldIdToPlayer[f.id]; ok {
							c = byte(p.id) + '0'
						}
					}
				}
513
			case PMPlaces:
514
515
516
517
518
519
520
521
522
				if !f.placeable {
					break
				}
				// if this is the current piece we can show the places that can actually be placed on. otherwise show all places
				if spf, ok := s.(*StatePlaceFollower); s != nil && ok && spf.boardx == boardx && spf.boardy == boardy {
					if len(spf.placements[f.id]) > 0 {
						c = f.id
					}
				} else {
523
					c = f.id
ceddral's avatar
ceddral committed
524
				}
525
526
527
528
529
530
			case PMTokens:
				if f.placeable && board != nil {
					if place, ok := board.Get(boardx, boardy); ok {
						if t, ok := place.fieldIdToToken[f.id]; ok {
							c = t.toByte()
						}
Michael Gebhard's avatar
Michael Gebhard committed
531
532
533
					}
				}
			}
534
535
536
537
538
			if c != f.c || underline != ^tg.TermUnderline {
				v.DrawBlockAttr(fg, bg, c, viewx + x, viewy + y, underline, ^tg.TermBold)
			} else {
				v.DrawBlockRaw(f.preRendered, viewx + x, viewy + y)
			}
Michael Gebhard's avatar
Michael Gebhard committed
539
540
541
542
		}
	}
}

ceddral's avatar
ceddral committed
543
func (b *Board) DetectCollisions(x, y int, p *Piece, rot Rotation) []bool {
544
	cs := getAdjacentCoords(0, 0)
545
	r := make([]bool, 0, 4)
546
	for _, c := range cs {
ceddral's avatar
ceddral committed
547
		nPlace, ok := b.Get(x + c.x, y + c.y)
548
549
550
551
		if !ok {
			r = append(r, false)
		} else {
			// field and neighbouring field are the middle fields on the border of both pieces
552
			nField := nPlace.piece.f[nPlace.rot][1 - c.y][2 - (2 * c.x)]
ceddral's avatar
ceddral committed
553
			field := p.f[rot][1 + c.y][2 + (2 * c.x)]
554
555
556
557
558
559
			r = append(r, nField.t != field.t)
		}
	}
	return r
}

ceddral's avatar
ceddral committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
func viewToBoard(x, y int, p *GamePlayer) (int, int) {
	x += p.boardx
	y += p.boardy
	if x < 0 {
		x -= pieceWidth
	}
	if y < 0 {
		y -= pieceHeight
	}
	x = x / pieceWidth
	y = y / pieceHeight
	return x, y
}

func boardToView(x, y int, p *GamePlayer) (int, int) {
	x = (x * pieceWidth) - p.boardx
	y = (y * pieceHeight) - p.boardy
	return x, y
}

580
581
func (b *Board) renderCurrentPiece(p *GamePlayer, s *StatePlacePiece) {
	viewx, viewy := boardToView(s.boardx, s.boardy, p)
582
	s.p.render(p.boardv, viewx, viewy, b, s.boardx, s.boardy, s.rot, p.boardMode, nil)
583
584
585
586
	// draw markers around piece
	viewx += pieceWidth
	viewy += pieceHeight
	cs := getAdjacentCoords(0, 0)
ceddral's avatar
ceddral committed
587
	collisions := b.DetectCollisions(s.boardx, s.boardy, s.p, s.rot)
588
	_, occupied := b.Get(s.boardx, s.boardy)
589
	hasNeighbour := b.HasNeighbour(s.boardx, s.boardy)
590
591
592
593
594
595
596
597
598
599
600
601
	for i, c := range cs {
		sym := byte('/')
		if i % 2 == 0 {
			sym = '\\'
		}
		fg := tg.ColorBlue
		if collisions[i] || collisions[(i+1) % 4] {
			fg = tg.ColorRed
		}
		if occupied {
			fg = tg.ColorRed
		}
602
603
604
		if !hasNeighbour {
			fg = tg.ColorRed
		}
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
		p.boardv.DrawBlockAttr(fg, tg.ColorKeep, sym, viewx, viewy, tg.TermKeep, tg.TermBold)
		viewx -= c.x * (pieceWidth + 1)
		viewy -= c.y * (pieceHeight + 1)
	}
}

func (b *Board) HighlightStructure(p *GamePlayer, x, y int, id byte) {
	b.MapStructure(func(acc interface{}, c MapCursor)interface{}{
		place, _ := b.Get(c.x, c.y)
		for y := range place.piece.f[place.rot] {
			for x, f := range place.piece.f[place.rot][y] {
				if f.id != c.id {
					continue
				}
				viewx, viewy := boardToView(c.x, c.y, p)
				p.boardv.DrawBlockAttr(tg.ColorKeep, tg.ColorMagenta, '\x00', viewx + x, viewy + y, tg.TermKeep, tg.TermKeep)
			}
		}
		return nil
	}, nil, x, y, id)
}

ceddral's avatar
ceddral committed
627
func (b *Board) Redraw(p *GamePlayer, s GameState) {
ceddral's avatar
ceddral committed
628
629
630
631
	minx, miny := viewToBoard(0, 0, p)
	maxx, maxy := viewToBoard(p.boardv.W, p.boardv.H, p)
	for x := minx; x < maxx + 1; x++ {
		for y := miny; y < maxy + 1; y++ {
ceddral's avatar
ceddral committed
632
			place, _ := b.Get(x, y)
ceddral's avatar
ceddral committed
633
			viewx, viewy := boardToView(x, y, p)
634
			place.piece.render(p.boardv, viewx, viewy, b, x, y, place.rot, p.boardMode, s)
ceddral's avatar
ceddral committed
635
636
		}
	}
637
	if spp, ok := s.(*StatePlacePiece); ok {
638
		b.renderCurrentPiece(p, spp)
639
	}
ceddral's avatar
ceddral committed
640
641
}

Michael Gebhard's avatar
Michael Gebhard committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
type PieceFormatError struct {
	s string
}

func (e PieceFormatError) Error() string {
	return e.s
}

func NewPieceFormatError(s string) PieceFormatError {
	return PieceFormatError{s}
}

func readpieces(filename string) (pieces []Piece, err error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	s := bufio.NewScanner(f)
	line := 0
	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		if atEOF && len(data) == 0 {
			return 0, nil, nil
		}
		if line % 4 == 0 {
			line++
			if i := bytes.IndexByte(data, '\n'); i >= 0 {
				return i + 1, data[:i], nil
			}
			if atEOF {
				return 0, nil, NewPieceFormatError("Unexpected EOF")
			}
			return 0, nil, nil
		} else {
			if data[0] == '\n' {
				line++
				return 1, []byte{}, nil
			}
			if len(data) < 15 {
				return 0, nil, nil
			}
			return 15, data[:15], nil
		}
	}
	s.Split(split)
	nToken := 0
	rotation := 0
	row := 0
	var curPiece Piece
	for s.Scan() {
		if len(s.Text()) == 0 {
			continue
		}
		if nToken % (3*4 + 1) == 0 {
			curPiece = Piece{
				f: make([][][]Field, 0),
			}
			for i := 0; i < 4; i++ {
				curPiece.f = append(curPiece.f, make([][]Field, 0))
				for j := 0; j < 3; j++ {
					curPiece.f[i] = append(curPiece.f[i], make([]Field, 0))
					for k := 0; k < 5; k++ {
						curPiece.f[i][j] = append(curPiece.f[i][j], Field{})
					}
				}
			}
			row = 0
ceddral's avatar
ceddral committed
708
			curPiece.fieldIdToType = make(map[byte]FType)
709
			curPiece.fieldIdToSpecial = make(map[byte][]FSpecial)
Michael Gebhard's avatar
Michael Gebhard committed
710
			meta := strings.Split(s.Text(), " ")
ceddral's avatar
ceddral committed
711
			curPiece.fieldIdToType['X'] = fFarm
Michael Gebhard's avatar
Michael Gebhard committed
712
			for i, c := range []byte(meta[0]) {
713
714
715
				id := byte(i) + '0'
				curPiece.fieldIdToType[id] = FType(c)
				curPiece.fieldIdToSpecial[id] = make([]FSpecial, 0)
Michael Gebhard's avatar
Michael Gebhard committed
716
717
718
719
720
721
722
723
724
			}
			curPiece.copies, err = strconv.Atoi(meta[1])
			if err != nil {
				return nil, err
			}

		} else {
			fields := curPiece.f[rotation][row]
			for i, c := range []byte(s.Text()) {
725
				x := i % 5
Michael Gebhard's avatar
Michael Gebhard committed
726
				if i < 5 {
727
728
					fields[x].id = c
					fields[x].t = curPiece.fieldIdToType[c]
Michael Gebhard's avatar
Michael Gebhard committed
729
				} else if i < 10 {
730
					fields[x].c = c
ceddral's avatar
ceddral committed
731
					if '0' <= c && c <= '9' {
732
						fields[x].fgOverride = tg.ColorBlue
Michael Gebhard's avatar
Michael Gebhard committed
733
734
					}
				} else {
735
					id := fields[x].id
ceddral's avatar
ceddral committed
736
737
738
					switch c {
					case '_':
					case id:
739
						fields[x].placeable = true
ceddral's avatar
ceddral committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
					case byte(fInn), byte(fPennant):
						// foreground contains id this special belongs to
						// which is not trivial for inns
						specialId := fields[x].c
						fields[x].c = '*'
						if rotation == 0 {
							// only add the special once
							sm := curPiece.fieldIdToSpecial
							sm[specialId] = append(sm[specialId], FSpecial(c))
						}
					case byte(fCathedral):
						if rotation == 0 {
							// only add the special once
							sm := curPiece.fieldIdToSpecial
							sm[id] = append(sm[id], FSpecial(c))
						}
					default: panic("unexpected symbol in card definition")
757
					}
ceddral's avatar
ceddral committed
758
759
760
					fg := typeFG[fields[x].t]
					if fields[x].fgOverride != 0 {
						fg = fields[x].fgOverride
ceddral's avatar
ceddral committed
761
					}
ceddral's avatar
ceddral committed
762
					fields[x].preRendered = tg.RenderBlock(fg, typeBG[fields[x].t], fields[x].c, ^tg.TermUnderline, ^tg.TermBold)
Michael Gebhard's avatar
Michael Gebhard committed
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
				}
			}
			rotation++
			rotation %= 4
			if rotation == 0 {
				row++
			}
		}
		nToken++
		if nToken%(3*4 + 1) == 0 {
			pieces = append(pieces, curPiece)
		}
	}
	if err = s.Err(); err != nil {
		return nil, err
	}
	return pieces, nil
}