// 记忆翻牌 —— 用 **Go** 写的手机小游戏
// Memory matching — a small phone game written in **Go**
//
// 玩法（与 Examples/c/app/memory.c / Examples/python/app/memory.py 同一套）：
// Gameplay (same rules as the C / Python versions):
//   · 4×4 共 8 对；点一张翻开，再点第二张；
//   · 4x4, eight pairs; tap one card to flip it, tap a second;
//   · 一样就留在明面，不一样 **0.4 秒**后扣回去；全部配对完成即通关；
//   · an equal pair stays revealed, a different pair flips back after 0.4 s; clear all pairs to win;
//   · 通关后点屏幕（或按 ESC / R）重开。
//
// ## Go 这一路的写法约束（见 Examples/go/app/snake.go 文件头）
// ## Style constraints on this Go path (see the header of Examples/go/app/snake.go)
//
//   · **全部状态放一个模块级数组 `A`**（包级标量在函数里读回 0）；
//   · **all state lives in one module-level array `A`** (package-level scalars read back 0 in functions);
//   · **字符串拼接编出来是空串** ⇒ 数字用逐位 `digitStr`（if 链返回字面量）；
//   · **string concatenation compiles to an empty string** => digits go through a per-digit
//     `digitStr` (an if-chain returning literals);
//   · 函数名带自己的前缀（别和标准库撞）；随机数走 `ui_math_rand`。
//   · function names carry their own prefix (never collide with the standard library); randomness is
//     `ui_math_rand`.
//
// 跑法 —— 手机：vml run examples/go/memory.go
// How to run — on the phone: vml run examples/go/memory.go
// 跑法 —— 桌面：vmlcli Examples/go/memory.go --screen 480x640 --frames /tmp/fr
// How to run — on the desktop: vmlcli Examples/go/memory.go --screen 480x640 --frames /tmp/fr

import "vmlui"

// 状态表（一个数组放全部，见文件头）：
//   0..15   = pairOf[i]（配对号；-1 = 已配对）
//   16..31  = up[i]（是否翻开）
//   32=firstX 33=firstY 34=hide 35=moves 36=matched 37=won 38=seed
//   39=cell 40=ox 41=oy 42=w 43=h 44=lang 45=tid 46=frames 47=hitX 48=hitY
//   49..52 = 四个颜色索引占位（本文件颜色走函数）
var A [64]int

const (
	maxFrames = 8000
	hideTicks = 8
)

func memDigitStr(d int) string {
	if d == 0 {
		return "0"
	}
	if d == 1 {
		return "1"
	}
	if d == 2 {
		return "2"
	}
	if d == 3 {
		return "3"
	}
	if d == 4 {
		return "4"
	}
	if d == 5 {
		return "5"
	}
	if d == 6 {
		return "6"
	}
	if d == 7 {
		return "7"
	}
	if d == 8 {
		return "8"
	}
	return "9"
}

func memDrawNum(x int, y int, v int) {
	if v < 10 {
		ui_2d_text(x, y, memDigitStr(v), -1513232, 15, 0)
		return
	}
	ui_2d_text(x, y, memDigitStr(v/10), -1513232, 15, 0)
	ui_2d_text(x+9, y, memDigitStr(v%10), -1513232, 15, 0)
}

func memPairColor(p int) int {
	if p == 0 {
		return -2069424
	}
	if p == 1 {
		return -2509750
	}
	if p == 2 {
		return -11409298
	}
	if p == 3 {
		return -11890471
	}
	if p == 4 {
		return -6591248
	}
	if p == 5 {
		return -2069336
	}
	if p == 6 {
		return -11871802
	}
	return -4145088
}

func memRelayout() {
	A[42] = ui_scr_get_w()
	A[43] = ui_scr_get_h()
	if A[42] <= 0 {
		A[42] = 360
	}
	if A[43] <= 0 {
		A[43] = 620
	}
	// 顶部步数 / 底部提示先占掉固定份，4×4 牌面按宽高较小的一边铺满可用区。
	pad := A[42] / 40
	if pad < 8 {
		pad = 8
	}
	top := 62
	bottom := 38
	avail := A[43] - top - bottom
	if avail < 24 {
		avail = 24
	}
	side := A[42] - 2*pad
	if avail < side {
		side = avail
	}
	A[39] = side / 4
	if A[39] < 6 {
		A[39] = 6
	}
	A[40] = (A[42] - 4*A[39]) / 2
	A[41] = top + (avail - 4*A[39]) / 2
}

func memNewGame() {
	i := 0
	for i < 16 {
		A[i] = i / 2
		A[16+i] = 0
		i = i + 1
	}
	i = 15
	for i > 0 {
		A[38] = (A[38] * 1103 + 12345) % 32768
		j := (A[38] / 256) % (i + 1)
		t := A[i]
		A[i] = A[j]
		A[j] = t
		i = i - 1
	}
	A[32] = -1
	A[33] = -1
	A[34] = 0
	A[35] = 0
	A[36] = 0
	A[37] = 0
	A[46] = 0
}

func memDraw() {
	lang := A[44]
	tMoves := "moves"
	tWon := "All matched! Tap for a new one"
	tHint := "Flip two that match"
	if lang == 0 {
		tMoves = "步数"
		tWon = "全配好了！点一下再来"
		tHint = "翻两张一样的"
	}

	ui_2d_clear(-15724520)

	x := 0
	for x < 4 {
		y := 0
		for y < 4 {
			px := A[40] + x*A[39]
			py := A[41] + y*A[39]
			idx := x*4 + y
			if A[idx] < 0 {
				ui_2d_rect(px+3, py+3, A[39]-6, A[39]-6, -15329762, 1, 0, 6)
			} else {
				if A[16+idx] == 1 {
					ui_2d_rect(px+3, py+3, A[39]-6, A[39]-6, memPairColor(A[idx]), 1, 0, 8)
					ui_2d_text(px+A[39]/2, py+A[39]/2+A[39]/8, memDigitStr(A[idx]+1), -15724520, A[39]/2, 1)
				} else {
					ui_2d_rect(px+3, py+3, A[39]-6, A[39]-6, -14013898, 1, 0, 8)
				}
			}
			y = y + 1
		}
		x = x + 1
	}

	memDrawNum(10, 19, A[35])
	ui_2d_text(10, 42, tMoves, -6643536, 10, 0)

	hintSize := 12
	if A[42] < 360 {
		hintSize = 10
	}
	if A[37] == 1 {
		ui_2d_text(A[42]/2, A[43]-30, tWon, -1513232, hintSize+3, 1)
	} else {
		ui_2d_text(A[42]/2, A[43]-30, tHint, -6643536, hintSize, 1)
	}
	ui_2d_present()
}

func memTap() {
	tx := A[47]
	ty := A[48]
	if tx < A[40] || ty < A[41] {
		return
	}
	x := (tx - A[40]) / A[39]
	y := (ty - A[41]) / A[39]
	if x < 0 || y < 0 || x >= 4 || y >= 4 {
		return
	}
	idx := x*4 + y
	if A[idx] < 0 || A[16+idx] == 1 || A[34] > 0 {
		return
	}
	A[16+idx] = 1
	if A[32] < 0 {
		A[32] = x
		A[33] = y
		return
	}
	A[35] = A[35] + 1
	fi := A[32]*4 + A[33]
	if A[fi] == A[idx] {
		A[fi] = -1
		A[idx] = -1
		A[36] = A[36] + 2
		if A[36] >= 16 {
			A[37] = 1
		}
		A[32] = -1
	} else {
		A[34] = hideTicks
	}
}

func main() {
	A[44] = ui_scr_get_language()
	lang := A[44]
	tTitle := "Memory"
	if lang == 0 {
		tTitle = "记忆翻牌"
	}
	ui_win_open(tTitle, 0, 0)
	ui_scr_set_keep_on(1)

	memRelayout()
	A[38] = 20265
	memNewGame()
	memDraw()

	A[45] = ui_timer_set(50, 0)

	for ui_win_is_closed() == 0 {
		t := ui_msg_fetch_wait(0)
		if t == 10 {
			break
		}

		if t == 9 {
			A[46] = A[46] + 1
			if A[46] >= maxFrames {
				break
			}
			if A[34] > 0 {
				A[34] = A[34] - 1
				if A[34] == 0 {
					i := 0
					for i < 16 {
						A[16+i] = 0
						i = i + 1
					}
					A[32] = -1
				}
			}
			memDraw()
			continue
		}

		if t == 6 || t == 4 {
			if A[37] == 1 {
				memNewGame()
			} else {
				A[47] = ui_msg_get_a()
				A[48] = ui_msg_get_b()
				memTap()
			}
			memDraw()
			continue
		}

		if t == 1 {
			k := ui_msg_get_a()
			if k == 27 || k == 82 {
				memNewGame()
				memDraw()
			}
			continue
		}

		if t == 11 {
			memRelayout()
			memDraw()
			continue
		}
	}

	ui_timer_kill(A[45])
	ui_scr_set_keep_on(0)
	ui_win_close()
}
