Skip to content

Instantly share code, notes, and snippets.

@sarna
Created July 29, 2018 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarna/70eeeead6f3f488501407a061a12f470 to your computer and use it in GitHub Desktop.
Save sarna/70eeeead6f3f488501407a061a12f470 to your computer and use it in GitHub Desktop.
#! /usr/bin/env false
use v6.c;
unit module App::ConnectFour;
sub cont-dups(Array:D $collection, Any:D $what, Int:D $how-many) returns Bool:D
{
my sub how-many(Array:D $collection, Any:D $what) returns Int:D
{
my $n = 0, my $most = 0;
for $collection -> $item
{
if $item eqv $what
{
$n += 1;
if $n > $most
{
$most = $n;
}
}
else
{
$n = 0;
}
}
return $most;
}
return how-many($collection, $what) == $how-many;
}
# for now I'm using 'o' and 'x'
# maybe it'll be a real color when I learn how terminal themes work
enum Coin is export ( blue => 'x', red => 'o');
class Slot is export
{
has Coin $.coin;
method has-coin(--> Bool:D)
{
self.coin.Bool;
}
method insert(Coin:D $coin)
{
$!coin = $coin;
}
method to-str() returns Str:D
{
if self.coin
{
self.coin.value;
}
else
{
' ';
}
}
}
class Grid is export
{
has $.rows = 6;
has $.columns = 7;
has @.slots of Array[Slot];
method populate()
{
loop (my $i = 0; $i < $!rows; $i++)
{ my Slot @a;
self.slots[$i] = @a;
loop (my $j = 0; $j < $.columns; $j++)
{
self.slots[$i][$j] = Slot.new;
}
}
}
method pprint() is export
{
my $b = True;
for self.slots -> @row
{
print '|';
for @row -> $slot
{
print $slot.to-str ~ '|';
}
say '';
}
say ' 1 2 3 4 5 6 7';
}
method insert-precisely(Int:D :$x!, Int:D :$y!, Coin:D :$coin!)
{
self.slots[$y][$x].insert($coin);
}
method insert(Int:D $x, Coin:D $coin)
{
for self.slots.kv -> $y, @row
{
if @row[$x].has-coin
{
self.insert-precisely(x => $x,
y => $y - 1,
coin => $coin);
return;
}
}
self.insert-precisely(x => $x,
y => self.rows - 1,
coin => $coin);
}
method winner()#(--> Coin)
{
my sub check-rows(--> Coin)
{
for self.slots -> @row
{
if cont-dups(@row, Slot.new(coin => red), 4)
{
return red;
}
if cont-dups(@row, Slot.new(coin => blue), 4)
{
return blue;
}
}
}
my sub check-columns()#(--> Coin)
{
loop (my $i = 0; $i < self.columns; $i++)
{
my @arr;
loop (my $j = 0; $j < self.rows; $j++)
{
@arr.push(self.slots[$j][$i]);
}
if cont-dups(@arr, Slot.new(coin => red), 4)
{
return red;
}
elsif cont-dups(@arr, Slot.new(coin => blue), 4)
{
return blue;
}
}
}
check-rows() || check-columns();
}
}
# vim: ft=perl6 noet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment