Permalink
Browse files

Merge remote-tracking branch 'upstream/master'

  • Loading branch information...
2 parents ceacab2 + 6a0625a commit 520611bd23529ad7bef3b0ece01f54ed106ac05a @retupmoca committed Feb 11, 2012
Showing with 47 additions and 42 deletions.
  1. +47 −42 perl6/tictactoe.pl
View
@@ -42,13 +42,53 @@
+#= calculations for tic-tac-toe
+class TTT-calc {
+ method check-for-win(@board,$player) {
+ for 0..2 {
+
+ #rows
+ if (@board[(1 + ($_ * 3))-1] &
+ @board[(2 + ($_ * 3))-1] &
+ @board[(3 + ($_ * 3))-1] eq $player) {
+
+ return True;
+ }
+
+ #cols
+ if (@board[(1+$_)-1] &
+ @board[(4+$_)-1] &
+ @board[(7+$_)-1] eq $player) {
+
+ return True;
+ }
+ }
+
+ #diagnals
+ if ((@board[0] &
+ @board[4] &
+ @board[8])
+ |
+ (@board[2] &
+ @board[4] &
+ @board[6]) eq $player) {
+
+ return True;
+ }
+ return False;
+ }
+}
+
+
#= A text-based tic-tac-toe game
class TicTacToe {
has $!board;
+ has $!calc;
submethod BUILD() {
$!board = TTT-board.new();
+ $!calc = TTT-calc.new();
}
method play() {
@@ -60,26 +100,28 @@
# - iterate over players -
for @players -> $player {
- self!move-via-user-input();
+ self!move-via-user-input($player);
# - print the board -
say $!board.Str();
# - check for win -
- if (self!check-for-win($player)) {
+ if ($!calc.check-for-win($!board.pieces(), $player)) {
say "player $player wins!";
exit();
}
}
}
}
- method !move-via-user-input() {
+ method !move-via-user-input(Str $player) {
my $move-valid;
+ my $player-move;
+
while (!$move-valid) {
# get player input
- my $player-move = prompt("Player $player:");
+ $player-move = prompt("Player $player:");
# loop untill the user gives us a good value
while ($player-move !~~ /<[1..9]>/) {
@@ -94,45 +136,8 @@
say "spot taken! move again.";
}
}
- return $player-move;
- }
-
-
-
- method !check-for-win(Str $player) {
- #rows
- for 0..2 -> $x {
- if ($!board.pieces()[(1 + ($x * 3))-1] &
- $!board.pieces()[(2 + ($x * 3))-1] &
- $!board.pieces()[(3 + ($x * 3))-1] eq $player) {
-
- return True;
- }
- }
-
- #cols
- for 0..2 -> $x {
- if ($!board.pieces()[(1+$x)-1] &
- $!board.pieces()[(4+$x)-1] &
- $!board.pieces()[(7+$x)-1] eq $player) {
-
- return True;
- }
- }
-
- #diagnals
- if (($!board.pieces()[0] &
- $!board.pieces()[4] &
- $!board.pieces()[8])
- |
- ($!board.pieces()[2] &
- $!board.pieces()[4] &
- $!board.pieces()[6]) eq $player) {
-
- return True;
- }
- return False;
+ return $player-move;
}
}

0 comments on commit 520611b

Please sign in to comment.