Skip to content

Instantly share code, notes, and snippets.

@wandernauta
Created June 28, 2010 14:41
Show Gist options
  • Save wandernauta/455930 to your computer and use it in GitHub Desktop.
Save wandernauta/455930 to your computer and use it in GitHub Desktop.
import structs/ArrayList
import text/StringTokenizer
import os/Terminal
scanf: extern func(String) -> String
players: ArrayList<Player>
map: Map
winner: Player
Player: class {
symbol: String
fullname: String
color: Int
init: func(=symbol, =fullname, =color) {}
}
Map: class {
tiles: ArrayList<Tile>
init: func() {
tiles = ArrayList<Tile> new()
for (x in 0..9) {
tiles add(Tile new(x % 3, x / 3, x+1))
}
}
draw: func() {
disporder := [7, 8, 9, 4, 5, 6, 1, 2, 3] as ArrayList<Int>
" " print()
for (disp in disporder) {
tile := tiles[disp-1]
if (tile player) {
Terminal setFgColor(tile player color)
tile player symbol print()
Terminal reset()
} else {
"." print()
//"(%d,%d,%d)" format(tile x, tile y, tile id) print()
}
" " print()
if (tile x == 2) "\n " print()
}
}
win: func() -> Bool {
winpatterns := "1,2,3; 4,5,6; 7,8,9; 7,4,1; 8,5,2; 9,6,3; 1,5,9; 7,5,3"
for (p in players) {
for (pattern in winpatterns split("; ")) {
pwin := true
for (bit in pattern split(",")) {
if (map tiles[bit toInt() - 1] player != p) pwin = false
}
if (pwin) {
winner = p
return true
}
}
}
return false
}
}
Tile: class {
x: Int
y: Int
id: Int
player: Player
init: func(=x, =y, =id) {}
}
main: func() {
"oxo - noughts and crosses in ooc." println()
Terminal setFgColor(Color grey)
"\n 7 8 9\n 4 5 6\n 1 2 3" println()
Terminal reset()
players = ArrayList<Player> new()
players add(Player new("x", "Team Crosses", Color red))
players add(Player new("o", "Team Noughts", Color blue))
map = Map new()
i := 0
c: Int
while (true) {
println()
map draw()
if (map win()) {
"Done! %s wins after %d turns." format(winner fullname, i) println()
break;
} else {
poffset := 2 + (i % 2) - 2
curplayer := players[poffset]
println()
"%d. %s, where do you want your %s (1-9, enter)? " format(i+1, curplayer fullname, curplayer symbol) print()
c = 0
scanf("%d", c&)
if (map tiles[c-1] player) {
"Someone already took that tile." println()
continue
} else {
map tiles[c-1] player = curplayer
}
i += 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment