周末无聊写写小游戏

小鸡
阅读79 喜欢1 随想 更新2019-8-18

一个半小时写的一个控制台2048小游戏


源码地址:https://git.nowcoder.com/8259730/my2048

【c++,100行】

部分代码如下

class my2048 {
public:
// 单向滑动
void slipe(int da[]) {
vector<int> arr;
for (int i = 0; i < 4; i++)
if (da[i] != 0)
arr.push_back(da[i]);
int len = arr.size();
int i, j = 0;
for (i = 0; i < len; i++) {
if ( i + 1 < len && arr[i] == arr[i + 1] ) da[j++] = arr[i++] * 2;
else da[j++] = arr[i];
}
for ( ; j < 4; j++) da[j] = 0;
}
// 新增一个单元
int add_one() {
vector<int> re;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if(data[i][j] == 0)
re.push_back(i*10 + j);
if (re.empty()) return 0;
int tmp = re[(rand() % re.size())];
data[tmp/10][tmp%10] = 2;
result += 2;
return 1;
}
// 开始游戏
void run_game() {
char ch;
while((ch = getch()) != 0x1B) {
ch = getch();
switch (ch) {
case 75:
for (int i = 0; i < 4; i++) slipe(data[i]);
break;
case 72:
for (int i = 0; i < 4; i++) {
int da[4] = {data[0][i], data[1][i], data[2][i], data[3][i]};
slipe(da);
for (int j = 0; j < 4; j++) data[j][i] = da[j];
}
break;
case 80:
for (int i = 0; i < 4; i++) {
int da[4] = {data[3][i], data[2][i], data[1][i], data[0][i]};
slipe(da);
for (int j = 0; j < 4; j++) data[j][i] = da[3-j];
}
break;
case 77:
for (int i = 0; i < 4; i++) {
int da[4] = {data[i][3], data[i][2], data[i][1], data[i][0]};
slipe(da);
for (int j = 0; j < 4; j++) data[i][j] = da[3-j];
}
break;
default:
break;
}
if (add_one() == 0) {
printf("game end !!! %d", result);
return;
}
print();
}
}
private:
int data[4][4];
int result = 0;
};