Skip to content

Instantly share code, notes, and snippets.

@adam-phillipps
Last active March 16, 2016 06:27
Show Gist options
  • Save adam-phillipps/8006b7423db3153b0fa8 to your computer and use it in GitHub Desktop.
Save adam-phillipps/8006b7423db3153b0fa8 to your computer and use it in GitHub Desktop.
using System;
namespace ConsoleApplication1
{
struct Disk : IComparable<Disk>, IEquatable<Disk>
{
public readonly string color;
public readonly int slot;
public Disk(string givenColor, string locationString)
{
Random rnd = new Random();
color = givenColor;
if (color == null)
color = "Open";
if (locationString == "")
{
locationString = ((int)rnd.Next(6)).ToString();
}
try
{
slot = int.Parse(locationString);
}
catch (FormatException ex)
{
slot = rnd.Next(6);
Console.WriteLine($"{ex.Message}");
}
}
public static bool operator ==(Disk thisDisk, Disk otherDisk)
{
return thisDisk.Equals(otherDisk);
}
public static bool operator !=(Disk thisDisk, Disk otherDisk)
{
// the only thing that matters for equality is color
return !(thisDisk == otherDisk);
}
public int CompareTo(Disk other)
{
if (Equals(other)) { return 0; }
else if (GetHashCode() < other.GetHashCode()) { return -1; }
else { return 1; }
}
public override int GetHashCode()
{
int tempColor;
int.TryParse(color, out tempColor);
return slot * tempColor;
}
public override string ToString()
{
string tempColor = color == null ? "Open" : color;
return string.Format($" {tempColor,8} ");
}
public bool Equals(Disk other)
{
return color == other.color;
}
public override bool Equals(Object obj)
{
return color == ((Disk)obj).color;
}
}
}
using ConsoleApplication1;
using System;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
namespace ConnectFour
{
class ConsoleGame
{
private Panel panel;
string playerOneName;
string playerOneColor = "Yellow";
string[] turn;
string playerTwoName;
string playerTwoColor = "Red";
public ConsoleGame()
{
turn = new string[] { playerOneName, playerOneColor };
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
panel = new Panel();
Greet();
Console.Clear();
while (PlayGame()) ;
}
private void Greet()
{
Console.WriteLine($"Welcome to connect 4, I need your 2 names:\n");
playerOneName = Console.ReadLine();
Console.WriteLine($"Thanks, {playerOneName}.\n next, please...");
playerTwoName = Console.ReadLine();
Console.WriteLine($"OK {playerTwoName} and {playerOneName}\nLet's begin ...");
Console.Clear();
}
public bool PlayGame()
{
int turnCounter = 0;
turn = new string[] { playerOneName, playerOneColor };
DrawPanel();
bool notAMatchYet = true;
while (notAMatchYet && turnCounter < 42)
{
turn = ((turnCounter += 1) % 2 == 0)
? new string[] { playerOneName, playerOneColor }
: new string[] { playerTwoName, playerTwoColor };
notAMatchYet = !IsWinningMove(turn);
DrawPanel();
}
Console.WriteLine($"Yay and hurray for {turn[0]} because said person was a person \n who was the one person who won this time.");
Console.WriteLine("Do you want to paly again?");
string reply = Console.ReadLine();
Console.Clear();
panel = new Panel();
return reply == "yes";
}
private bool IsWinningMove(string[] currentTurn)
{
Console.WriteLine($"{currentTurn[0]}'s turn...");
string currentMove = Console.ReadLine();
if (currentMove == "")
{
Random rnd = new Random();
currentMove = rnd.Next(panel.panel.GetLength(1)).ToString(); ;
}
Disk disk = new Disk(currentTurn[1], currentMove);
return (disk.color != null)
? panel.DropDiskAndCheckForWin(currentMove, disk)
: false;
}
private void DrawPanel()
{
Console.SetCursorPosition(0, 2);
for (int i = 0; i < panel.panel.GetLength(0); i++)
{
for (int j = 0; j < panel.panel.GetLength(1); j++)
{
string currentColor = panel.panel[i, j].color;
if (currentColor == null || currentColor == "Open")
{
Console.ForegroundColor = ConsoleColor.Gray;
}
else
{
Console.ForegroundColor =
panel.panel[i, j].color == "Yellow" ? ConsoleColor.Yellow : ConsoleColor.Red;
}
Console.Write($"{panel.panel[i, j]}");
}
Console.WriteLine();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConnectFour
{
class ConnectFour
{
static void Main(string[] args)
{
ConsoleGame cg = new ConsoleGame();
cg.PlayGame();
}
}
}
<Window x:Class="Prac.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Prac"
mc:Ignorable="d"
Title="Connect 4" Height="350" Width="525">
<Grid x:Name="BaseOrganizer" Background="BlueViolet">
<Grid.RowDefinitions>
<RowDefinition Height="7*"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid x:Name="slots" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="6*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="slot" Width="*"/>
</Grid.ColumnDefinitions>
<Grid x:Name="gamePanel"
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="7"
Background="Blue"
ShowGridLines="True">
<!--
<Border x:Name="cellBorder"
BorderBrush="Black"
BorderThickness="12"
CornerRadius="10"/>
-->
<!--
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
-->
<!--
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
-->
</Grid>
</Grid>
<DockPanel x:Name="UserControlls" Grid.Row="2" >
<Button x:Name="resetButton"
Content="Reset the game"
Click="resetButton_Click">
<Button.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.0" Color="Red" />
<GradientStop Offset="1.0" Color="Blue" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Button.Background>
</Button>
</DockPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Prac
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetUpGamePanel();
}
private Grid SetUpGamePanel()
{
for (int row = 0; row < 7; row++)
{
if (row > 0)
{
gamePanel.RowDefinitions.Add(Row());
}
gamePanel.ColumnDefinitions.Add(Col());
for (int col = 0; col < 7; col++)
{
Border circle = CellHole();
gamePanel.Children.Add(circle);
Grid.SetRow(circle, row);
Grid.SetColumn(circle, col);
}
}
return gamePanel;
}
private RowDefinition Row()
{
return new RowDefinition();
}
private ColumnDefinition Col()
{
return new ColumnDefinition();
}
private Border CellHole()
{
Border b = new Border();
b.BorderThickness = new Thickness(10);
b.BorderBrush = Brushes.Transparent;
// b.Margin = new Thickness(10);
// b.CornerRadius = new CornerRadius(25);
EllipseGeometry circleShape = new EllipseGeometry();
circleShape.RadiusX = 15;
circleShape.RadiusY = 15;
circleShape.Center = new Point(
circleShape.Bounds.Size.Height,
circleShape.Bounds.Size.Width
);
b.Clip = circleShape;
return b;
}
private void resetButton_Click(object sender, RoutedEventArgs e)
{
}
}
}
using System;
namespace ConsoleApplication1
{
class Panel
{
public Disk[,] panel;
public Panel()
{
panel = new Disk[6,7];
}
public bool DropDiskAndCheckForWin(string currentMove, Disk disk)
{
try
{
int slot = int.Parse(currentMove) - 1;
int height = GetHeight(slot);
panel[height, slot] = disk;
return (CheckDiagonal(height, slot)
|| CheckHorizontal(height, slot)
|| CheckVertical(height, slot));
}
catch (System.ArgumentOutOfRangeException ex)
{
Console.WriteLine($"{ex.Message}");
return false;
}
catch (System.IndexOutOfRangeException ex)
{
Console.WriteLine($"Maybe try to choose a slot that's real:\n {ex.Message}");
return false;
}
}
private bool CheckDiagonal(int height, int slot)
{
int count = 0;
int reverseCount = 0;
int tempHeight = height;
// count from all four lines going diagonally away from the current move
// counts up and to the right
for (int tempSlot = slot; (tempSlot < panel.GetLength(1) && tempHeight < panel.GetLength(0)); tempSlot++)
{
if (panel[tempHeight, tempSlot] == panel[height, slot])
{
count += 1;
}
else
{ break; }
tempHeight += 1;
}
tempHeight = height;
if (count == 4)
return true;
// counts down and to the left to join the first partial line with this one
for (int tempSlot = slot; (tempSlot > 0 && tempHeight > 0); tempSlot++)
{
if (panel[tempHeight, tempSlot] == panel[height, slot])
{ // don't count the origin again
if (tempSlot != slot && tempHeight != height)
count += 1;
}
else { break; }
tempHeight -= 1;
}
if (count == 4)
return true;
tempHeight = height;
// counts up and to the left
for (int tempSlot = slot; (tempSlot > 0 && tempHeight < panel.GetLength(0)); tempSlot--)
{
if (panel[tempHeight, tempSlot] == panel[height, slot])
{
reverseCount += 1;
}
else { break; }
tempHeight += 1;
}
tempHeight = height;
// counts down and to the right to finish the up and to the left line
for (int tempSlot = slot; (tempSlot < panel.GetLength(1) && tempHeight > 0); tempSlot++)
{
if (panel[tempHeight, tempSlot] == panel[height, slot])
{ // don't count the origin again
if (tempSlot != slot && tempHeight != height)
reverseCount += 1;
}
else { break; }
tempHeight -= 1;
}
if (reverseCount == 4)
return true;
return (count >= 4 || reverseCount >= 4);
}
private bool CheckHorizontal(int height, int slot)
{
int count = 0;
for (int i = 0; i < panel.GetLength(1); i++)
{
if (panel[height, i] == panel[height, slot])
{
if ((count += 1) == 4)
break;
}
else
count = 0;
}
return count == 4;
}
private bool CheckVertical(int height, int slot)
{
int count = 0;
for (int j = 0; j < panel.GetLength(0); j++)
{
if (panel[j, slot] == panel[height, slot])
{
if ((count += 1) == 4)
break;
}
else
count = 0;
}
return count == 4;
}
private int GetHeight(int slot)
{
int number = 6;
bool slotAlreadyFilled = true;
try
{
for (int j = 0; j < 6; ++j)
{
if (panel[j, slot].color == null)
{
slotAlreadyFilled = false;
number = j;
}
else
break;
}
if (slotAlreadyFilled)
throw new ArgumentOutOfRangeException("This slot is filled up already");
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine($"{ex.Message}");
Random rnd = new Random();
number = rnd.Next(panel.GetLength(1));
}
return number;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment