Archive for March, 2010

31
Mar
10

Tic-Tac-Toe: LOLCode

The clink… clink… clink sound you’ve been hearing was my IQ points sliding off onto the floor one by one as I wrote this.

This program was written against a slightly tweaked version of the the Perl-based YALI interpreter.  You can check out the original, but to run this one you will need my version, which is checked in with the rest of the code.  I also stole the array join implementation from his examples.

HAI

  OBTW
    join
    Basic array join.
  TLDR
  HOW DUZ I join YR a AN YR b
    I HAS A count ITZ ALL a
    LOL count R count NERF 1

    IZ count SMALR DEN 0 ? FOUND YR ""

    I HAS A output ITZ ""
    IM IN YR LOOP
      LOL output R count IN MAH a N output

      IZ count BIGR DEN 0 ? LOL output R b N output
      IZ count LIEK 0 ? GTFO

      LOL count R count NERF 1
    KTHX

    FOUND YR output
  IF U SAY SO

  OBTW
    cell formatting
  TLDR
  HOW DUZ I formatz YR cell
    IZ cell SORTA "\d" ? FOUND YR "(" N cell N ")"
    FOUND YR " " N cell N " "
  IF U SAY SO

  HOW DUZ I printz YR bord
    I HAS A cell
    I HAS A colsep ITZ "|"
    I HAS A rowsep ITZ "\n---+---+---\n"
    I HAS A outputz ITZ ""

    LOL cell R formatz YR 0 IN MAH bord MKAY
    LOL outputz R "\n" N cell N colsep

    LOL cell R formatz YR 1 IN MAH bord MKAY
    LOL outputz R outputz N  cell N colsep

    LOL cell R formatz YR 2 IN MAH bord MKAY
    LOL outputz R outputz N  cell N rowsep

    LOL cell R formatz YR 3 IN MAH bord MKAY
    LOL outputz R outputz N  cell N colsep

    LOL cell R formatz YR 4 IN MAH bord MKAY
    LOL outputz R outputz N  cell N colsep

    LOL cell R formatz YR 5 IN MAH bord MKAY
    LOL outputz R outputz N  cell N rowsep

    LOL cell R formatz YR 6 IN MAH bord MKAY
    LOL outputz R outputz N  cell N colsep

    LOL cell R formatz YR 7 IN MAH bord MKAY
    LOL outputz R outputz N  cell N colsep

    LOL cell R formatz YR 8 IN MAH bord MKAY
    LOL outputz R outputz N cell N "\n"

    FOUND YR outputz
  IF U SAY SO

  HOW DUZ I makezYrMove YR playr AN YR space AN YR bord
    BTW This version of LOLCode has no TROOF values, so I use NUMBRs

    IZ space SMALR DEN 1 ? FOUND YR 0
    IZ space BIGR DEN 9 ? FOUND YR 0

    I HAS A indeks ITZ space NERF 1

    IZ indeks IN MAH bord SORTA "\d" O RLY?
      YA RLY
        LOL indeks IN MAH bord R playr
        FOUND YR 1
      NO WAI
        FOUND YR 0
    KTHX
  IF U SAY SO

  HOW DUZ I canHasWinnarIn YR bord AN YR playr
    I HAS A bordMaidUvYarn ITZ join YR bord AN YR "" MKAY

    BTW rows
    IZ bordMaidUvYarn SORTA "(" N playr N ")(" N playr N ")(" N playr N ")......" ? FOUND YR 1
    IZ bordMaidUvYarn SORTA "...(" N playr N ")(" N playr N ")(" N playr N ")..." ? FOUND YR 1
    IZ bordMaidUvYarn SORTA "......(" N playr N ")(" N playr N ")(" N playr N ")" ? FOUND YR 1

    BTW columns
    IZ bordMaidUvYarn SORTA "(" N playr N ")..(" N playr N ")..(" N playr N ").." ? FOUND YR 1
    IZ bordMaidUvYarn SORTA ".(" N playr N ")..(" N playr N ")..(" N playr N ")." ? FOUND YR 1
    IZ bordMaidUvYarn SORTA "..(" N playr N ")..(" N playr N ")..(" N playr N ")" ? FOUND YR 1

    BTW diagonals
    IZ bordMaidUvYarn SORTA "(" N playr N ")...(" N playr N ")...(" N playr N ")" ? FOUND YR 1
    IZ bordMaidUvYarn SORTA "..(" N playr N ").(" N playr N ").(" N playr N ").." ? FOUND YR 1

    FOUND YR 0
  IF U SAY SO

  HOW DUZ I canHasTieIn YR fantsyBord
    IZ fantsyBord SORTA "\d" ? FOUND YR 0
    FOUND YR 1
  IF U SAY SO

  I HAS A bord
  I HAS A bord_lemf ITZ 9
  I HAS A current_lemf
  IM IN YR loop
    LOL current_lemf R ALL bord
    IZ current_lemf LIEK bord_lemf ? GTFO

    LOL current_lemf IN MAH bord R current_lemf UP 1
  KTHX

  I HAS A playr ITZ "X"
  I HAS A moovWerked ITZ 0

  IM IN YR gaimLoop
    I HAS A fantsyBord ITZ printz YR bord MKAY
    VISIBLE fantsyBord

    I HAS A winnar ITZ canHasWinnarIn YR bord AN YR playr MKAY
    IZ winnar LIEK 1 O RLY?
      YA RLY
        VISIBLE playr N " IS TEH WINNAR!1!!!"
        BTW Use this line instead if you want to run tests
        BTW VISIBLE playr N " Wins!"
        GTFO
    KTHX

    I HAS A tie ITZ canHasTieIn YR fantsyBord MKAY
    IZ tie LIEK 1 O RLY?
      YA RLY
        VISIBLE "NO MOAR WINNARZ!!!?/1!"
        BTW Use this line instead if you want to run tests
        BTW VISIBLE "It's a Draw!"
        GTFO
    KTHX

    IZ moovWerked LIEK 1 O RLY?
      YA RLY
        IZ playr LIEK "X" O RLY?
          YA RLY
            LOL playr R "O"
          NO WAI
            LOL playr R "X"
        KTHX
    KTHX

    I HAS A moov

    VISIBLE "Makez yr moov, " N playr N ": "!
    BTW Use this line instead if you want to run tests
    BTW VISIBLE "Select a square, " N playr N ": "!

    GIMMEH NUMBR moov

    LOL moovWerked R makezYrMove YR playr AN YR moov AN YR bord MKAY
  KTHX

KTHXBYE

BTW vim: ts=2 sw=2 et
24
Mar
10

Tic-Tac-Toe: Python

Lock up the women and children — a rubyist is writing python. I’m curious what the herpetophiles in the audience will think of the code, because I know the Python community spends a reasonable amount of brainpower debating “pythonicness.”

Broadly speaking, there were more places I found commonality between Ruby and Python than differences. This may have been more harmful than helpful in the short run, because it meant I kept reaching for familiar tools a finding they had been moved, or replaced. For example, you can see in several places that I do this: if type(cell) == type(1), meaning if cell is a number. Is this a common Python idiom? It seems unlikely.

Differences I liked:

  • Syntactically-significant indentation.  Makes short functions look great and longer ones look weird, thus encouraging short functions.  :)
  • List comprehensions.  Especially with multiple lists.
  • Real named arguments.
  • Excellent documentation.
  • TIOOWTDI

Differences I didn’t like:

  • Distinction between builtins and methods.  I kept looking for any and map in all the wrong places.
  • No implicit expression value / required explicit return.
  • More difficult reflection/metaprogramming.
  • TIOOWTDI

With just a little practice, I’m sure I could be quite happy and productive in it.

What do you think, Python people?  What should I have done differently?

#!/usr/bin/env python2.6

from __future__ import print_function
import sys

X = 'X'
O = 'O'

starting_player = X
starting_board = [ [1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9] ]

# Input/Output

def format(cell):
    if type(cell) == type(1):
        return "(" + repr(cell) + ")"
    else:
        return " " + cell + " "

def print_board(board):
    print("\n" + "\n---+---+---\n".join(["|".join([format(c) for c in row]) for row in board]) + "\n")

def print_prompt(player):
    print("Select a square, " + player + ": ", end='')

def print_winner(player):
    print(player + " Wins!")

def print_draw():
    print("It's a Draw!")

def read_answer():
    str = sys.stdin.readline()
    return int(str)

# Winner Detection

def rows(board):
    return board[:] # clone

def cols(board):
    return [[row[i] for row in board] for i in [0,1,2]]

def diagonals(board):
    return [[row[i] for row, i in zip(board,[0,1,2])],
            [row[i] for row, i in zip(board,[2,1,0])]]

def lines(board):
    return rows(board) + cols(board) + diagonals(board)

def complete_line(line):
    return line[0] == line[1] and line[1] == line[2]

def winner(board):
    return any([complete_line(line) for line in lines(board)])

def full(board):
    return not any([type(row[i]) == type(1) for row in board for i in [0,1,2]])

# Game Play

def other_player(player):
    if player == X:
        return O
    else:
        return X

def legal_move(space, board):
    return any([row[i] == space for row in board for i in [0, 1, 2]])

def make_move(player, space, board):
    new_board = [row[:] for row in board]
    new_board[(space-1)/3][(space-1)%3] = player
    return new_board

# Main loop

def loop(player, board):
    print_board(board)
    if winner(board):
        print_winner(other_player(player))
        return
    elif full(board):
        print_draw()
        return
    else:
        print_prompt(player)
        space = read_answer()
        if legal_move(space, board):
            loop(other_player(player), make_move(player, space, board))
        else:
            loop(player, board)

loop(starting_player, starting_board)
17
Mar
10

Tic-Tac-Toe: Java

*Yawn*

(Though I will say that generics and for-each are a big improvement. This is my first time seriously using Java since 1.4.2.)

Happy St. Patrick’s Day!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Queue;
import java.util.Set;

class TicTacToe {

	Queue players;
	Board board;
	BufferedReader in;

	public static void main(String argv[]) {
		new TicTacToe().play();
	}
	
	public TicTacToe() {
		// Player List 
		players = new LinkedList();
		players.add(Player.X);
		players.add(Player.O);
		
		board = new Board();
		
		in = new BufferedReader(new InputStreamReader(System.in));
	}
	
	public void play() {
		Player player = nextPlayer(); 
		while (true) {
			System.out.println("");
			System.out.println(board);
			if (board.winner() != null) {
				System.out.println(String.format("\n%s Wins!", board.winner()));
				break;
			} else if (board.full()) {
				System.out.println("\nIt's a Draw!");
				break;
			} else {
				System.out.print(String.format("\nSelect a square, %s: ", player));
				int move = 0;

				try {
					String answer = in.readLine();
					move = Integer.parseInt(answer);
				} catch (IOException e) {
					e.printStackTrace();
					System.exit(1);
				} catch (NumberFormatException e) {
					continue;
				}

				if (board.place(player, move)) { 
					player = nextPlayer();
				}
			}
		}
	}
	
	public Player nextPlayer() {
		Player nextPlayer = players.remove();
		players.add(nextPlayer);
		return nextPlayer;
	}

	class Cell {
		Player player = null;
		int address;
		List<List> neighborLists;
		
		public Cell(int address) {
			super();
			this.address = address;
			this.neighborLists = new LinkedList<List>();
		}
		
		public boolean assignPlayer(Player player, int targetAddress) {
			if (address == targetAddress) {
				this.player = player;
				return true;
			} else {
				return false;
			}
		}
		
		public void addNeighborList(List list) {
			neighborLists.add(list);
		}
		
		public void addNeighbors(Cell first, Cell second) {
			addNeighborList(Arrays.asList(first, second));
		}
		
		public boolean isWinner() {
			for (List list : neighborLists) {
				boolean result = true;
				for (Cell cell : list) {
					result = result && this.equals(cell);
				}
				if (result) return true;
			}
			return false;
		}

		@Override
		public String toString() {
			if (player == null) {
				return String.format("(%d)", address);
			} else {
				return String.format(" %s ", player);
			}
		}

		@Override
		public boolean equals(Object obj) {
			if (obj.getClass() == Cell.class) {
				return this.player == ((Cell) obj).player;
			} else {
				return false;
			}
		}
		
	}

	enum Player {
		X("X"),
		O("O");
		
		String name;
		
		Player(String name) {
			this.name = name;
		}

		public String toString() {
			return name;
		}
	}
	
	class Board {
		DelimitedList<DelimitedList> cells;
		Set freeCells;
		Player winner;
		
		private final static String COLSEP = "|";
		private final static String ROWSEP = "\n---+---+---\n";
		private static final int SIZE = 3;
		
		public Board() {
			
			// Lay out cells in the board
			freeCells = new HashSet();
			cells = new DelimitedList<DelimitedList>(ROWSEP);
			for (int i = 0; i < SIZE; i++) {
				DelimitedList row = new DelimitedList(COLSEP);
				cells.add(row);
				for (int j = 0; j < SIZE; j++) {
					Cell cell = new Cell(i*SIZE + j + 1);
					row.add(cell);
					freeCells.add(cell);
				}
			}
			
			defineRow(1, 2, 3);
			defineRow(4, 5, 6);
			defineRow(7, 8, 9);
			
			defineRow(1, 4, 7);
			defineRow(2, 5, 8);
			defineRow(3, 6, 9);
			
			defineRow(1, 5, 9);
			defineRow(3, 5, 7);
		}
		
		public String toString() {
			StringBuffer sb = new StringBuffer();
			display(sb);
			return sb.toString();
		}
		
		public void display(StringBuffer sb) {
			cells.setStringBuffer(sb);
			for (DelimitedList row : cells) {
				display(row, sb);
			}
		}
		
		public void display(DelimitedList row, StringBuffer sb) {
			row.setStringBuffer(sb);
			for (Cell cell : row) {
				sb.append(cell);
			}
		}
		
		public boolean full() {
			return freeCells.isEmpty();
		}
		
		public Player winner() {
			return this.winner;
		}
		
		public boolean complete() {
			return winner() != null || full();
		}
		
		public boolean place(Player player, int space) {
			Iterator iterator = freeCells.iterator();
			while (iterator.hasNext()) {
				Cell cell = iterator.next();
				if (cell.assignPlayer(player, space)) {
					iterator.remove();
					if (cell.isWinner()) this.winner = player;
					return true;
				}
			}
			return false;
		}
		
		private Cell cellAt(int oneBasedIndex) {
			int i = oneBasedIndex  - 1;
			return cells.get(i / SIZE).get(i % SIZE);
		}
		
		private void defineRow(int first, int second, int third) {
			cellAt(first).addNeighbors(cellAt(second), cellAt(third));
			cellAt(second).addNeighbors(cellAt(third), cellAt(first));
			cellAt(third).addNeighbors(cellAt(first), cellAt(second));
		}
		
	}
	
	private static class DelimitingIterator implements Iterator {

		public DelimitingIterator(ListIterator iterator,
				StringBuffer stringBuffer, String delimiter) {
			super();
			this.iterator = iterator;
			this.stringBuffer = stringBuffer;
			this.delimiter = delimiter;
		}

		ListIterator iterator;
		StringBuffer stringBuffer;
		String delimiter;
		
		@Override
		public boolean hasNext() {
			return iterator.hasNext();
		}

		@Override
		public E next() {
			E nextItem =  iterator.next();
			if (iterator.previousIndex() != 0 && stringBuffer != null) {
				stringBuffer.append(delimiter);
			}
			return nextItem;
		}

		@Override
		public void remove() {
			iterator.remove();
		}

	}
	
	private static class DelimitedList extends ArrayList {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public DelimitedList(String delimiter) {
			super();
			this.delimiter = delimiter;
		}

		StringBuffer stringBuffer;
		String delimiter;
		
		public void setStringBuffer(StringBuffer stringBuffer) {
			this.stringBuffer = stringBuffer;
		}

		@Override
		public Iterator iterator() {
			return new DelimitingIterator(listIterator(), stringBuffer, delimiter);
		}
	}
}

10
Mar
10

Tic-Tac-Toe: Cobra

Cobra is a work-in-progress language that primarily targets the CLR. As far as I could tell, it doesn’t do much pioneering of new ideas, but it does attempt to bring together a bunch of basically good ideas in one place. These include:

  • Mixed static and dynamic typing
  • First class unit tests
  • First class contracts
  • Semantic Indenting
  • Clean, expressive syntax
  • Full-featured OOP (with interfaces, mixins, generics)
  • Accurate decimal arithmetic
  • High performance

How well does it do all this? Reasonably well, I have to say.  The biggest missing features are closures, an an interactive runtime, but according to this presentation they’re on the way. I was excited about the mix of static and dynamic typing. I’ve wanted for a while to be able to hack something up without types and then go back through and tighten things up later. Cobra doesn’t seem like it’s 100% there. You can certainly omit type declarations, but it wasn’t always the case that a semantically valid program would run correctly without its type declarations. For example, there was one place where I left a member variable untyped, and then assigned a list to it in the initializer. It crashed like that. Adding the type declaration fixed it without any other changes.

The documentation is still quite spotty, as you might expect from an unfinished project. Most (all?) of the standard data types seem to be based directly on the .NET standard library, so you can go look some things up on MSDN.

Built-in unit tests are very cool. I could see them being overused and cluttering things up (it would be nice to have the option to pull them back out into another file when you’re done) but having real support from the runtime means that the compiler can tell you things about your test that other languages can’t. For example, assert 2 == 1 will give you an error message like:

(MonoType)
info       = nil
this       = Cell (MonoType)
(2 == 1) = false

No need for awkward constructions like assert_equal or 2.should == 1

There is a JVM port underway, and also what looks like the beginnings of a port to the Objective-C runtime. Looks like one to watch.

Here’s the code (for version 0.8.0 and mono):


class TicTacToe
	"""
	Tic Tac Toe in Cobra
	"""
	def main is shared
		players = Ring("X", "O")
		board = Board(3)

		player = players.next
		cellsRemaining = 9

		while true
			print board
			
			Console.write('Select a square, [player]: ')
			Console.out.flush
			try 
				answer = Console.readLine
				Console.out.flush
			catch System.ArgumentNullException 
				break

			cell = board.getCell(answer)
			if not cell
				continue

			cellsRemaining -= 1

			cell.value = player
			if cell.matchAny(3)
				print board
				print "[player] Wins!"
				break

			if cellsRemaining <= 0
				print board
				print "It's a Draw!"
				break

			player = players.next


class Ring
	"""
	A Ring class that takes its inputs and will return one 
	after the other ad infinitum.
	"""
	var _enumerator as IEnumerator

	test
		ring = Ring(1, 2, 3)
		assert ring.next == 1
		assert ring.next == 2
		assert ring.next == 3
		assert ring.next == 1

	cue init(items as vari T)
		base.init
		_enumerator = List(items).getEnumerator

	def next as T
		if _enumerator.moveNext
			return _enumerator.current
		else
			_enumerator.reset
			return .next

class Cell
	"""
	A mesh-aware cell on the tic-tac-toe board.  It keeps track
	of its neighbors and can detect winners that way.
	"""
	pro address from var as String
	pro value from var as String?

	enum Dir
		East
		Southeast
		South
		Southwest
		West
		Northwest
		North
		Northeast

	# Neighbors
	var _neighbors = Dictionary() 

	cue init(address as String)
		base.init
		.address = address
		for i in 8
			_neighbors[i to Dir] = nil

	cue init(address as String, value as String)
		.init(address)
		.value = value

	def opposite(dir as Dir) as Dir
		test
			cell = Cell('2')
			assert cell.opposite(Dir.East) == Dir.West
			assert cell.opposite(Dir.West) == Dir.East
			assert cell.opposite(Dir.Northeast) == Dir.Southwest
		body
			val = dir to int
			val = (val + 4) % 8
			return val to Dir

	def add(dir as Dir, cell as Cell?)
		if not _neighbors[dir]
			_neighbors[dir] = cell
			if cell, cell.add(.opposite(dir), this)

	def addOtherSide(cell as Cell)
		.add(Dir.East, cell)
		cell.add(Dir.Northwest, _neighbors[Dir.North])
		cell.addBelow(_neighbors[Dir.Northeast])

	def addAbove(cell as Cell)
		.add(Dir.South, cell)
		cell.add(Dir.Northeast, _neighbors[Dir.East])

	def addBelow(cell as Cell?) as Cell
		if cell, cell.addAbove(this)
		return this

	def addBeside(cell as Cell?) as Cell
		if cell, cell.addOtherSide(this)
		return this

	def match(direction as Dir, cell as Cell) as int
		if .value  cell.value
			return 0
		else if _neighbors[direction]
			return 1 + _neighbors[direction].match(direction, this)
		else
			return 1

	def match(dir as Dir, target as int) as bool
		test
			cell1 = Cell('1', "X")
			cell2 = Cell('2', "X").addBeside(cell1)
			cell3 = Cell('3', "X").addBeside(cell2)
			cell4 = Cell('4', "X").addBelow(cell1)
			cell5 = Cell('5', "X").addBeside(cell4)
			cell6 = Cell('6', "X").addBeside(cell5)
			cell7 = Cell('7', "X").addBelow(cell4)
			cell8 = Cell('8', "X").addBeside(cell7)
			cell9 = Cell('9', "X").addBeside(cell8)

			assert cell1.match(Dir.Southeast, 3)
			assert cell7.match(Dir.Southwest, 3)
			assert cell7.match(Dir.Northeast, 3)
			assert cell3.match(Dir.North, 3)
			assert not cell6.match(Dir.Northeast, 3)
			assert cell9.match(Dir.West, 3)

		body
			opp = .opposite(dir)
			num = 1
			if _neighbors[dir], num += _neighbors[dir].match(dir, this)
			if _neighbors[opp], num += _neighbors[opp].match(opp, this)
			return target == num


	def matchAny(target as int) as bool
		return  .match(Dir.East, target) or _
				.match(Dir.North, target) or _
				.match(Dir.Northeast, target) or _
				.match(Dir.Northwest, target)

	
	def toString as String is override
		if .value
			return ' [.value] '
		else
			return '([.address])'

	def rowToString(sb as StringBuilder, sep as String)
		sb.append(this)
		if _neighbors[Dir.East]
			sb.append(sep)
			_neighbors[Dir.East].rowToString(sb, sep)

	
	def allToString(sb as StringBuilder, colsep as String, rowsep as String)
		.rowToString(sb, colsep)
		if _neighbors[Dir.South]
			sb.append(Environment.newLine)
			sb.append(rowsep)
			sb.append(Environment.newLine)
			_neighbors[Dir.South].allToString(sb, colsep, rowsep)


class Board

	pro dim from var as int
	pro head from var as Cell?
	var _cells as IList
	var _rowsep as String

	cue init(dim as int)
		ensure
			dim >= 3
		body
			base.init
			_dim = dim
			_cells = List()
			_constructBoard
			_rowsep = "---"
			for i in 1 : dim
				_rowsep += "+---"

	def _constructBoard
		head = nil
		tail = nil
		for i in .dim
			for j in .dim
				cell = Cell((i*.dim + j + 1).toString)
				_cells.add(cell)
				if j == 0
					head = tail = cell.addBelow(head)
				else
					tail = cell.addBeside(tail)
		.head = _cells[0]

	def getCell(address as String?) as Cell?
		if not address, return nil
		for cell in _cells
			if cell.address == address
				_cells.remove(cell)
				return cell
		return nil

	def toString as String is override
		sb = StringBuilder()
		sb.append(Environment.newLine)
		.head.allToString(sb, "|",_rowsep)
		sb.append(Environment.newLine)
		return sb.toString

03
Mar
10

Tic-Tac-Toe: LOGO

I couldn’t write it in LOGO and not use turtle graphics to draw the board. This runs in UCBLogo 6.0.

#!/usr/bin/env logo

make "cells {1 2 3 4 5 6 7 8 9}
make "cellPositions {
	[-121  121]
	[   0  121]
	[ 121  121]
	[-121    0]
	[   0    0]
	[ 121    0]
	[-121 -121]
	[   0 -121]
	[ 121 -121]
}

TO drawLine :x  :y :nx :ny
	penup
	setxy x y
	pendown
	setxy nx ny
	penup
END
	
TO drawX :x  :y
	drawLine (x - 50) (y + 50) (x + 50) (y - 50)
	drawLine (x + 50) (y + 50) (x - 50) (y - 50)
END

TO drawO :x  :y
	penup
	setxy x y
	pendown
	arc 360 50
	penup
END

TO drawGrid
	drawLine 61 171 61 -171
	drawLine -61 171 -61 -171
	drawLine 171 61 -171 61
	drawLine 171 -61 -171 -61
END

TO markPos :player :numpos
	localmake "coords (item :numpos cellPositions)
	setitem numpos cells player
	ifelse (player = "X) [
		drawX (item 1 coords) (item 2 coords)
	] [
		drawO (item 1 coords) (item 2 coords)
	]
end
	
TO swapPlayer
	ifelse (currentPlayer = "X) [
		make "currentPlayer "O
	] [
		make "currentPlayer "X
	]
END

TO checkRow :x  :y :z
	output (and ((item x cells) = currentPlayer)
				((item y cells) = currentPlayer)
				((item z cells) = currentPlayer))
END

TO checkWinner
	if (or (checkRow 1 2 3)
		   (checkRow 4 5 6)
		   (checkRow 7 8 9)
		   (checkRow 1 4 7)
		   (checkRow 2 5 8)
		   (checkRow 3 6 9)
		   (checkRow 1 5 9)
		   (checkRow 3 5 7)) [ 
		print `[,currentPlayer Wins!]
		bye
	]
END

TO checkDraw
	FOR [i 1 9 1] [
		IF (number? (item i cells)) [	
			STOP
		]
	]
	print [It's a Draw!]
	bye
END
		
TO promptMove 
	type `[Select a square, ,currentPlayer] 
	type `[,": ," ]
	localmake "numpos readword
	if (number? numpos) [
		if (and (numpos > 0) (numpos < 10) (number? (item numpos cells))) [
			markPos currentPlayer numpos
			checkWinner
			checkDraw
			swapPlayer
		]
	]
END

penup
hideturtle

drawGrid 

make "currentPlayer "X

forever [ promptMove ]




Follow

Get every new post delivered to your Inbox.