forked from scala-js/scala-js
/
Reversi.scala
266 lines (214 loc) · 6.9 KB
/
Reversi.scala
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
/* Scala.js example code
* Public domain
* @author Sébastien Doeraene
*/
package reversi
import scala.annotation.tailrec
import scala.scalajs.js
import scala.scalajs.js.annotation._
sealed abstract class OptPlayer
sealed abstract class Player extends OptPlayer {
val opponent: Player
}
case object NoPlayer extends OptPlayer
case object White extends Player {
val opponent = Black
}
case object Black extends Player {
val opponent = White
}
@JSExportTopLevel("Reversi")
class Reversi(jQuery: JQueryStatic, playground: JQuery) {
// The Model -----------------------------------------------------------------
val BoardSize = 8 // size of a Reversi board
def inBounds(index: Int): Boolean = index >= 0 && index < BoardSize
def inBounds(x: Int, y: Int): Boolean = inBounds(x) && inBounds(y)
class Square(val x: Int, val y: Int) {
private var _owner: OptPlayer = NoPlayer
var onOwnerChange: (OptPlayer, OptPlayer) => Unit = (oldP, newP) => ()
def owner = _owner
def owner_=(value: OptPlayer): Unit = {
val previous = _owner
if (value != previous) {
_owner = value
onOwnerChange(previous, value)
}
}
override def toString() = "Square("+x+", "+y+", "+owner+")"
}
val board = Array.tabulate[Square](BoardSize, BoardSize)(new Square(_, _))
val allSquares = board.flatten
var currentPlayer: Player = White // Irrelevant, set again in startGame()
// The GUI -------------------------------------------------------------------
val resetButton = createResetButton()
val passButton = createPassButton()
val status = createStatus()
buildUI()
def createResetButton() = {
jQuery("<input>", js.Dynamic.literal(
`type` = "button", value = "Reset"
)).click(() => reset())
}
def createPassButton() = {
jQuery("<input>", js.Dynamic.literal(
`type` = "button", value = "Pass"
)).click(() => pass())
}
def createStatus() = {
jQuery("<span>")
}
def buildUI(): Unit = {
// Some dimensions
val SquareSizePx = 48
val HalfSquareSizePx = SquareSizePx/2
val PawnRadiusPx = HalfSquareSizePx-4
val BoardSizePx = BoardSize*SquareSizePx + 3
// Creat the board canvas
val boardCanvas = jQuery(
"<canvas width='"+BoardSizePx+"' height='"+BoardSizePx+"'></canvas>")
val domCanvas = boardCanvas.get(0).asInstanceOf[HTMLCanvasElement]
val context = domCanvas.getContext("2d").asInstanceOf[CanvasRenderingContext2D]
playground.append(jQuery("<div>").append(boardCanvas))
/** Draw the specified square on the board canvas */
def drawSquare(square: Square): Unit = {
val x = square.x * SquareSizePx
val y = square.y * SquareSizePx
// Background
context.fillStyle = "green"
context.fillRect(x, y, SquareSizePx, SquareSizePx)
// Border
context.fillStyle = "black"
context.lineWidth = 3
context.strokeRect(x, y, SquareSizePx, SquareSizePx)
// Pawn
if (square.owner != NoPlayer) {
context.fillStyle = if (square.owner == White) "white" else "black"
context.beginPath()
context.arc(x+HalfSquareSizePx, y+HalfSquareSizePx, PawnRadiusPx,
0, 2*Math.PI, true)
context.fill()
}
}
// Draw squares now, and everytime they change ownership
for (square <- allSquares) {
drawSquare(square)
square.onOwnerChange = { (prevOwner, newOwner) =>
drawSquare(square)
}
}
// Configure clicks on the board
boardCanvas.click { (event: JQueryEvent) =>
val offsetX = event.pageX - boardCanvas.offset().left
val offsetY = event.pageY - boardCanvas.offset().top
val x = offsetX.toInt / SquareSizePx
val y = offsetY.toInt / SquareSizePx
if (inBounds(x, y))
clickSquare(board(x)(y))
}
// Build the status bar
val statusBar = jQuery("<p>")
statusBar.append(resetButton)
statusBar.append(status)
statusBar.append(passButton)
playground.append(statusBar)
}
// The Game ------------------------------------------------------------------
def reset(): Unit = {
startGame()
}
@JSExport
def startGame(): Unit = {
// Set up the board
allSquares foreach (_.owner = NoPlayer)
board(3)(3).owner = White
board(3)(4).owner = Black
board(4)(3).owner = Black
board(4)(4).owner = White
// White begins
currentPlayer = White
// Let's go!
startTurn()
}
def startTurn(): Unit = {
val (scoreWhite, scoreBlack) = computeScore()
status.text(""+currentPlayer+"'s turn -- White: "+scoreWhite+
" -- Black: "+scoreBlack)
passButton.prop("disabled", true)
if (!existsValidMove()) {
// Test if the other player can do something
currentPlayer = currentPlayer.opponent
val opponentCanDoSomething = existsValidMove()
currentPlayer = currentPlayer.opponent
if (opponentCanDoSomething) {
passButton.prop("disabled", false)
} else {
// End of game
val winnerText =
if (scoreWhite > scoreBlack) "White won!"
else if (scoreBlack > scoreWhite) "Black won!"
else "Draw"
status.text("Game finished -- White: "+scoreWhite+
" -- Black: "+scoreBlack+" -- "+winnerText)
}
}
}
def clickSquare(square: Square): Unit = {
val toFlip = computeFlips(square)
if (!toFlip.isEmpty) {
(square :: toFlip) foreach (_.owner = currentPlayer)
nextTurn()
}
}
def pass(): Unit = {
assert(!existsValidMove())
nextTurn()
}
def existsValidMove(): Boolean = {
allSquares.exists(isValidMove)
}
def isValidMove(square: Square): Boolean = {
!computeFlips(square).isEmpty
}
def computeFlips(square: Square): List[Square] = {
if (square.owner != NoPlayer) Nil
else {
for {
i <- (-1 to 1).toList
j <- -1 to 1
if i != 0 || j != 0
flip <- computeFlipsInDirection(square.x, square.y, i, j)
} yield flip
}
}
def computeFlipsInDirection(x: Int, y: Int,
dirx: Int, diry: Int): List[Square] = {
val allInDir = allSquaresInDirection(x, y, dirx, diry)
val (toFlip, remaining) =
allInDir.span(_.owner == currentPlayer.opponent)
val success = remaining.headOption.exists(_.owner == currentPlayer)
if (success) toFlip
else Nil
}
def allSquaresInDirection(fromx: Int, fromy: Int,
dirx: Int, diry: Int): List[Square] = {
val nextx = fromx + dirx
val nexty = fromy + diry
if (inBounds(nextx, nexty))
board(nextx)(nexty) :: allSquaresInDirection(nextx, nexty, dirx, diry)
else
Nil
}
def computeScore(): (Int, Int) = {
allSquares.foldLeft((0, 0)) { case ((white, black), square) =>
square.owner match {
case White => (white+1, black)
case Black => (white, black+1)
case NoPlayer => (white, black)
}
}
}
def nextTurn(): Unit = {
currentPlayer = currentPlayer.opponent
startTurn()
}
}