爬格子呀--2048
好长时间没写啦,中间花了一段时间学习了一下数据结构的知识,因为我的专业并不学这个,想要在码农的路上走的更远,怕是自己还得多学一点呀;
国庆去了一趟长沙张家界也耽误了一段时间,要不会更早完成的;
本来这段小代码是想送给一个人玩的,结果懒得调试了也就不送了哈哈哈,被人家笑话,坏习惯坏习惯,得改,嘿嘿(挠头);
代码如下:
#include<cstdio>
#include<stdlib.h>
#include<time.h>
#include<string.h>
const int N = 4;
int a[N][N] = {0};
int x = 0, y = 0, num = 0;
int getRand() {
return rand() / (RAND_MAX + 1.0)*15+1;
}
void print_board() {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d", a[i][j]);
while (j % 3 == 0 && j != 0) {
printf("\n");
break;
}
}
}
}
void generator() {
num = getRand() > 12 ? 2 : 4;
}
void insert() {
generator();
int i = getRand();
x = i / 4;
y = i % 4;
if (a[x][y] == 0) {
a[x][y] = num;
}
else insert();
}
void col_change(int i, int j, int flag) {
int ini = i;
while (j < N) {
if (a[i][j] == a[i + flag][j]) {
a[i][j] += a[i + flag*2][j];
while (i + flag*2 <= N - 1) {
a[i + flag][j] = a[i + flag*2][j];
a[i + flag*2][j] = 0;
i++;
}
i = ini;
j++;
}
else {
i += flag;
continue;
}
}
}
void row_change(int i, int j, int flag) {
int ini = j;
while (i < N) {
if (a[i][j] == a[i][j + flag]) {
a[i][j] += a[i][j + flag * 2];
while (j + flag * 2 <= N - 1) {
a[i][j + flag] = a[i][j + flag * 2];
a[i][j + flag * 2] = 0;
j++;
}
j = ini;
i++;
}
else {
j += flag;
continue;
}
}
}
int main() {
print_board();
char cmd;
insert();
while (scanf_s("%c",&cmd)){
if (cmd == '#')
break;
switch (cmd) {
case('w'):
insert();
col_change(0,0,1);
print_board();
break;
case('s'):
insert();
col_change(N - 1, 0, -1);
print_board();
break;
case('a'):
insert;
row_change(0, 0, 1);
print_board();
break;
case('d'):
insert;
row_change(0, N - 1, -1);
print_board;
break;
}
}
return 0;
}