闲来无事写了个五子棋, 简单的算法部分已经完成。明天有空再做做界面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Chess5
{
class Step
{
public Step(int x, int y, Color color)
{
this.x = x;
this.y = y;
this.color = color;
}
private int x, y;
private Color color;
public Color Color
{
get { return this.color; }
}
public int X
{
get { return this.x; }
}
public int Y
{
get { return this.y; }
}
public bool isWin(List<Step> steps, out List<Step> winningSteps)
{
winningSteps = new List<Step>();
int xCount = 1;
int yCount = 1;
int sCount = 1;
int bCount = 1;
//x axis
if (x > 0 && getStep(steps, x - 1, y) != null)
{
int xCountTemp = 1;//起始step
getCountInDirection(steps, ref xCountTemp, -1, 0, ref winningSteps);
xCount += xCountTemp - 1;//起始step算了1,需要减掉
}
if (getStep(steps, x + 1, y) != null)
{
int xCountTemp = 1;//起始step
getCountInDirection(steps, ref xCountTemp, 1, 0, ref winningSteps);
xCount += xCountTemp-1;
}
if (xCount < 5)
{
winningSteps.Clear();
//y axis
if (y > 0 && getStep(steps, x, y - 1) != null)
{
int yCountTemp = 1;
getCountInDirection(steps, ref yCountTemp, 0, -1, ref winningSteps);
yCount += yCountTemp-1;
}
if (getStep(steps, x, y + 1) != null)
{
int yCountTemp = 1;
getCountInDirection(steps, ref yCountTemp, 0, 1, ref winningSteps);
yCount += yCountTemp-1;
}
if (yCount < 5)
{
winningSteps.Clear();
//slash direction
if (x > 0 && y > 0 && getStep(steps, x - 1, y - 1) != null)
{
int sCountTemp = 1;
getCountInDirection(steps, ref sCountTemp, -1, -1, ref winningSteps);
sCount += sCountTemp-1;
}
if (getStep(steps, x + 1, y + 1) != null)
{
int sCountTemp = 1;
getCountInDirection(steps, ref sCountTemp, 1, 1, ref winningSteps);
sCount += sCountTemp-1;
}
if (sCount < 5)
{
winningSteps.Clear();
//backwardslash direction
if (y > 0 && getStep(steps, x + 1, y - 1) != null)
{
int bCountTemp = 1;
getCountInDirection(steps, ref bCountTemp, 1, -1, ref winningSteps);
bCount += bCountTemp-1;
}
if (getStep(steps, x - 1, y + 1) != null)
{
int bCountTemp = 1;
getCountInDirection(steps, ref bCountTemp, -1, 1, ref winningSteps);
bCount += bCountTemp-1;
}
if (bCount < 5)
winningSteps.Clear();
}
}
}
if (xCount >= 5 || yCount >= 5 || sCount >= 5 || bCount >= 5)
{
winningSteps.Add(this);
return true;
}
else
{
winningSteps.Clear();
return false;
}
}
public void getCountInDirection(List<Step> steps, ref int count, int xIndex, int yIndex, ref List<Step> winningSteps)
{
if (this.x + xIndex * count >= 0 && this.y + yIndex * count >= 0)
{
Step s = getStep(steps, x + xIndex * count, y + yIndex * count);
if (s != null)
{
count++;
winningSteps.Add(s);
getCountInDirection(steps, ref count, xIndex, yIndex, ref winningSteps);
}
}
}
public Step getStep(List<Step> steps, int x, int y)
{
foreach (Step step in steps)
{
if (step.x == x && step.y == y && step.Color == this.color)
return step;
}
return null;
}
}
}