board.go 16.5 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
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
// 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
	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 {
					score++
				}
			}
		}
		closed = (score == 9)
	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)
		score = len(visited)
		if closed && hasInn {
			score = 2 * score
		} 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)
		score = pennants + len(visited)
		if closed && hasCathedral {
			score = 3 * score
		} else if closed && !hasCathedral {
			score = 2 * score
		} else if !closed && !hasCathedral {
			score = 1 * score
		} else if !closed && hasCathedral {
			score = 0
		}
	case fFarm:
		println("farm scoring not yet implemented")
		return false, 0
	default:
		panic("trying to score unknown structure type")
	}

	if !closed && !gameEnd {
		return
	}
	// assign score, return followers to players
	majority := 0
	// 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]
		}
		// 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
			}
		}
	}
	return
}

369
370
371
372
373
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)
)

374
375
376
377
378
379
380
381
382
383
384
385
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
386
387
	for y := 0; y < pieceHeight; y++ {
		for x := 0; x < pieceWidth; x++ {
ceddral's avatar
ceddral committed
388
			if p == nil {
389
				b := checkerBoardBlockA
ceddral's avatar
ceddral committed
390
				if (boardx + boardy) % 2 == 0 {
391
					b = checkerBoardBlockB
ceddral's avatar
ceddral committed
392
				}
393
				v.DrawBlockRaw(b, viewx + x, viewy + y)
ceddral's avatar
ceddral committed
394
				continue
ceddral's avatar
ceddral committed
395
			}
Michael Gebhard's avatar
Michael Gebhard committed
396
397
			f := p.f[rot][y][x]
			// underline bottom corners if necessary
398
			underline := ^tg.TermUnderline
Michael Gebhard's avatar
Michael Gebhard committed
399
			if board != nil && y == pieceHeight - 1 {
400
401
402
403
404
405
406
407
408
409
410
411
				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
412
413
414
415
416
417
418
419
420
// 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 |
421
				if downp != nil {
Michael Gebhard's avatar
Michael Gebhard committed
422
					A := f
ceddral's avatar
ceddral committed
423
					B := A
424
					C := downp.f[downpRot][0][x]
ceddral's avatar
ceddral committed
425
					D := C
Michael Gebhard's avatar
Michael Gebhard committed
426
427
					if x == 0 {
						B = p.f[rot][y][x+1]
428
						D = downp.f[downpRot][0][x+1]
Michael Gebhard's avatar
Michael Gebhard committed
429
430
431
					}
					if x == pieceWidth - 1 {
						B = p.f[rot][y][x-1]
432
						D = downp.f[downpRot][0][x-1]
Michael Gebhard's avatar
Michael Gebhard committed
433
434
					}
					if A.t == C.t && (A.id != B.id || C.id != D.id) {
435
						underline = tg.TermUnderline
Michael Gebhard's avatar
Michael Gebhard committed
436
437
438
439
440
441
442
443
444
					}
				}
			}
			fg := typeFG[f.t]
			if f.fgOverride != 0 {
				fg = f.fgOverride
			}
			c := f.c
			bg := typeBG[f.t]
445
446
447
			if spf, ok := s.(*StatePlaceFollower); s != nil && ok && spf.boardx == boardx && spf.boardy == boardy {
				mode = spf.mode
			}
ceddral's avatar
ceddral committed
448
			switch mode {
449
450
			case PMPlayers:
				if f.placeable && board != nil {
ceddral's avatar
ceddral committed
451
452
453
454
455
456
					if place, ok := board.Get(boardx, boardy); ok {
						if p, ok := place.fieldIdToPlayer[f.id]; ok {
							c = byte(p.id) + '0'
						}
					}
				}
457
			case PMPlaces:
458
459
460
461
462
463
464
465
466
				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 {
467
					c = f.id
ceddral's avatar
ceddral committed
468
				}
469
470
471
472
473
474
			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
475
476
477
					}
				}
			}
478
479
480
481
482
			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
483
484
485
486
		}
	}
}

ceddral's avatar
ceddral committed
487
func (b *Board) DetectCollisions(x, y int, p *Piece, rot Rotation) []bool {
488
	cs := getAdjacentCoords(0, 0)
489
	r := make([]bool, 0, 4)
490
	for _, c := range cs {
ceddral's avatar
ceddral committed
491
		nPlace, ok := b.Get(x + c.x, y + c.y)
492
493
494
495
		if !ok {
			r = append(r, false)
		} else {
			// field and neighbouring field are the middle fields on the border of both pieces
496
			nField := nPlace.piece.f[nPlace.rot][1 - c.y][2 - (2 * c.x)]
ceddral's avatar
ceddral committed
497
			field := p.f[rot][1 + c.y][2 + (2 * c.x)]
498
499
500
501
502
503
			r = append(r, nField.t != field.t)
		}
	}
	return r
}

ceddral's avatar
ceddral committed
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
}

524
525
func (b *Board) renderCurrentPiece(p *GamePlayer, s *StatePlacePiece) {
	viewx, viewy := boardToView(s.boardx, s.boardy, p)
526
	s.p.render(p.boardv, viewx, viewy, b, s.boardx, s.boardy, s.rot, p.boardMode, nil)
527
528
529
530
	// draw markers around piece
	viewx += pieceWidth
	viewy += pieceHeight
	cs := getAdjacentCoords(0, 0)
ceddral's avatar
ceddral committed
531
	collisions := b.DetectCollisions(s.boardx, s.boardy, s.p, s.rot)
532
	_, occupied := b.Get(s.boardx, s.boardy)
533
	hasNeighbour := b.HasNeighbour(s.boardx, s.boardy)
534
535
536
537
538
539
540
541
542
543
544
545
	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
		}
546
547
548
		if !hasNeighbour {
			fg = tg.ColorRed
		}
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
		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
571
func (b *Board) Redraw(p *GamePlayer, s GameState) {
ceddral's avatar
ceddral committed
572
573
574
575
	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
576
			place, _ := b.Get(x, y)
ceddral's avatar
ceddral committed
577
			viewx, viewy := boardToView(x, y, p)
578
			place.piece.render(p.boardv, viewx, viewy, b, x, y, place.rot, p.boardMode, s)
ceddral's avatar
ceddral committed
579
580
		}
	}
581
	if spp, ok := s.(*StatePlacePiece); ok {
582
		b.renderCurrentPiece(p, spp)
583
	}
ceddral's avatar
ceddral committed
584
585
}

Michael Gebhard's avatar
Michael Gebhard committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
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
652
			curPiece.fieldIdToType = make(map[byte]FType)
653
			curPiece.fieldIdToSpecial = make(map[byte][]FSpecial)
Michael Gebhard's avatar
Michael Gebhard committed
654
			meta := strings.Split(s.Text(), " ")
ceddral's avatar
ceddral committed
655
			curPiece.fieldIdToType['X'] = fFarm
Michael Gebhard's avatar
Michael Gebhard committed
656
			for i, c := range []byte(meta[0]) {
657
658
659
				id := byte(i) + '0'
				curPiece.fieldIdToType[id] = FType(c)
				curPiece.fieldIdToSpecial[id] = make([]FSpecial, 0)
Michael Gebhard's avatar
Michael Gebhard committed
660
661
662
663
664
665
666
667
668
			}
			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()) {
669
				x := i % 5
Michael Gebhard's avatar
Michael Gebhard committed
670
				if i < 5 {
671
672
					fields[x].id = c
					fields[x].t = curPiece.fieldIdToType[c]
Michael Gebhard's avatar
Michael Gebhard committed
673
				} else if i < 10 {
674
675
					fields[x].c = c
					fg := typeFG[fields[x].t]
Michael Gebhard's avatar
Michael Gebhard committed
676
					if c == '*' {
677
678
						fields[x].fgOverride = tg.ColorBlue
						fg = fields[x].fgOverride
Michael Gebhard's avatar
Michael Gebhard committed
679
					}
680
					fields[x].preRendered = tg.RenderBlock(fg, typeBG[fields[x].t], fields[x].c, ^tg.TermUnderline, ^tg.TermBold)
Michael Gebhard's avatar
Michael Gebhard committed
681
				} else {
682
683
684
685
686
687
688
689
					if c == '_' {
						continue
					}
					id := fields[x].id
					if c == id {
						fields[x].placeable = true
						continue
					}
ceddral's avatar
ceddral committed
690
691
692
693
					if rotation != 0 {
						// only add specials once, do not duplicate for each rotation
						continue
					}
694
695
					sm := curPiece.fieldIdToSpecial
					sm[id] = append(sm[id], FSpecial(c))
Michael Gebhard's avatar
Michael Gebhard committed
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
				}
			}
			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
}