Skip to content

Instantly share code, notes, and snippets.

@moccos
Last active December 13, 2015 19:59
Show Gist options
  • Save moccos/4967078 to your computer and use it in GitHub Desktop.
Save moccos/4967078 to your computer and use it in GitHub Desktop.
My first F# code. F#談話室(2) http://www.zusaar.com/event/491059 で約90分使って書いたもの。
open System
open System.Drawing
open System.Windows.Forms
// Configuration
let nGrid = 12
let gridSize = 30
let stoneSize = gridSize - 2
let fieldMargin = 10
let fieldEdgeMax = fieldMargin + nGrid * gridSize
let formSize = fieldEdgeMax + fieldMargin
// Windows form settings
let f = new Form()
f.Text <- "リバーシ"
f.ClientSize <- new Size(formSize, formSize)
f.BackColor <- Color.Green
// Data structures
type State =
| None
| White
| Black
type gameState = {
field: State[,]
mutable turn: int
mutable nBlack: int
}
let getColorFromTurn (turn: int) =
if turn % 2 = 0 then
White
else
Black
let currentGame = {
field = Array2D.create nGrid nGrid None
turn = 1
nBlack = 0
}
// Drawing operation
let drawGrid (e: PaintEventArgs) =
for i = 0 to nGrid do
e.Graphics.DrawLine(Pens.Black, i * gridSize + fieldMargin, fieldMargin, i * gridSize + fieldMargin, fieldEdgeMax)
e.Graphics.DrawLine(Pens.Black, fieldMargin, i * gridSize + fieldMargin, fieldEdgeMax, i * gridSize + fieldMargin)
let calcDrawPos n = n * gridSize + fieldMargin + 1
let drawStone (e: PaintEventArgs) x y (brush: Brush) =
e.Graphics.FillEllipse(brush, calcDrawPos(x), calcDrawPos(y), stoneSize, stoneSize)
let draw (s: State) (e: PaintEventArgs) x y =
match s with
| Black -> drawStone e x y Brushes.Black
| White -> drawStone e x y Brushes.White
| otherwise -> ()
let drawField (e: PaintEventArgs) (field: State[,]) =
let func x y (s: State) =
draw s e x y
Array2D.iteri func field
// Put stone and calculate result
let flipStone (s: State) (field: State[,]) x y =
() // not implemented
let putStone (s: State) (field: State[,]) x y =
field.[x, y] <- s
flipStone s field x y
// Experimental functions
let putInitialStone (e: PaintEventArgs) =
let centerPos = (nGrid - 1) / 2
draw White e centerPos centerPos
draw Black e centerPos (centerPos + 1)
draw Black e (centerPos + 1) centerPos
draw White e (centerPos + 1) (centerPos + 1)
let isBlank (field: State[,]) x y =
if field.[x, y] = None then
true
else
false
// Event handlers
f.Paint.Add <| fun e ->
drawGrid(e)
drawField e currentGame.field
f.MouseDown.Add <| fun e ->
let isInside n =
n >= fieldMargin && n <= fieldEdgeMax
let calcIndex n =
(n - fieldMargin) / gridSize
if (isInside e.X) && (isInside e.Y) then
let color = getColorFromTurn currentGame.turn
let x = calcIndex e.X
let y = calcIndex e.Y
let field = currentGame.field
if (isBlank field x y) then
putStone color field x y
currentGame.turn <- currentGame.turn + 1
f.Refresh()
else
()
else
()
// Run!
Application.Run(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment