(如果有谁想要这个软件的话,在评论中留一个邮箱吧。)
前几天好几次看到有朋友晒出玩2048刷高分的截图,我就想我能不能也做一个2048呢?仔细想了想2048游戏的规律,发现其实逻辑上很简单,也不用研究什么算法,于是我马上觉得我可以很快写出来。当天下午我就用了四个小时完成了2048的基本功能。几天后觉得不满足,于是给我的2048加了存档、读档和后退一步的功能,这样就更好刷分了呢!
使用语言:C#; 平台:Visual Studio 2012 Win Form。
如何完成2048的基本功能呢?2048在每一次操作后16个方格的数字就有可能发生变化,所以在我的程序里用一个4乘4的二维数组来存这16个值,0表示没有数字。每一次操作直接改变数组的值,然后再把数组的值填到16个方格中。首先来看程序中几个全局的变量:
public int[,] matrixValue = new int[4, 4];//对应16个方格的数字,0表示没有数字
public bool isThereChanged = false;//表示每一次按键后是否发生改变
public int score = 0;//此次游戏的分数
public int maxScore = 0;//记录最高分,用于判断是否破纪录
public List<storeRecord> dataStoreRecord = new List<storeRecord>();//存储所有存档
public List<int[,]> history = new List<int[,]>();//存最近10步操作 现在想一下,玩2048的时候往一个方向滑动它是怎么改变16个方格的数字的。我把这个过程分解成三个步骤,对应程序中的三个函数。我觉得在软件开发过程中,这种模块化设计的思想是很重要的。
以下是这三个函数(三个步骤):
public void addSameNumber(string command)//first step往指定方向叠加相同数字的相邻两格
public void moveToEdge(string command)//Second step将所有有数字的格子往指定方向靠边移动
public void addAnNumber()//Third step在没有数字的格子中随机选择一个添加数字其实注释上已经说明了其目的。第一个函数会在指定方向上叠加相邻两个相同的数字,相邻的意思是中间没有非0的数字,也就是有可能两个相同数字中间两个空格,这种情况下也要相机;第二个函数是在实现了相同数字的叠加之后把所有数字往一个方向挪动;第三个函数实现的是在一个操作过后16个方格状态有改变的时候随机给空格填入一个数字。
第一个函数:(只贴出向上移动的代码)
public void addSameNumber(string command)//first step往指定方向叠加相同数字的相邻两格
{
if (command == "up")
{
for (int col = 0; col < 4; col++)
{
int firstOfSamePair = -1;
int previousIndex = -1;
for (int row = 0; row < 4; row++)
{
if (matrixValue[row, col] != 0)
{
if (matrixValue[row, col] == firstOfSamePair)
{
score += matrixValue[row, col] * 2;
changeYourScoreHandle();//刷新你的分数
matrixValue[previousIndex, col] *= 2;
matrixValue[row, col] = 0;
firstOfSamePair = -1;
previousIndex = -1;
isThereChanged = true;
}
else
{
firstOfSamePair = matrixValue[row, col];
previousIndex = row;
}
}
}
}
}//if 第二个函数:
public void moveToEdge(string command)//Second step将所有有数字的格子往指定方向靠边移动
{
if (command == "up")
{
for (int col = 0; col < 4; col++)
{
int index = 0;
for (int row = 0; row < 4; row++)
{
if (matrixValue[row, col] != 0)
{
int temp = matrixValue[row, col];
matrixValue[row, col] = matrixValue[index, col];
matrixValue[index, col] = temp;
if (index != row)
isThereChanged = true;
index++;
}
}
}
} 第三个函数:
public void addAnNumber()//Third step在没有数字的格子中随机选择一个添加数字
{
int emptyCount = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(matrixValue[i,j] == 0)
emptyCount++;
}
}
Random rand = new Random();
int temp = rand.Next(emptyCount);
emptyCount = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (matrixValue[i, j] == 0)
{
if (emptyCount == temp)
randomAddNumber(i, j);//往该位置添加数字
emptyCount++;
}
}
}
} 其他的请看下篇文章《我的改进版2048(2)》java File类的基本操作,布布扣,bubuko.com
原文:http://blog.csdn.net/cjc211322/article/details/24833691