C语言简易2048

it2022-05-08  13

#include <stdio.h> #include<stdlib.h> #include<time.h> #include<windows.h> #include<conio.h> #define DIR_UP -1//UP #define DIR_DOWN 1//DOWN #define DIR_LEFT -2//LEFT #define DIR_RIGHT 2//RIGHT int g_map[4][4] = { 0 }; int g_score = 0;//分数 void drawMpa();//画地图 void randNum(int n);//随机产生数 void gotoxy(int x ,int y);//到达相应坐标 void movePoint(int dir);//移动点 int main() { system("color f0"); randNum(2); randNum(2); drawMpa(); while (true) { if (_kbhit()) { int key = _getch(); switch (key) { case 'w':case 72:movePoint(DIR_UP); randNum(4); break; case 's':case 80:movePoint(DIR_DOWN); randNum(4); break; case 'a':case 75:movePoint(DIR_LEFT); randNum(4); break; case 'd':case 77:movePoint(DIR_RIGHT); randNum(4); break; } system("cls"); drawMpa(); gotoxy(30, 5); printf("%d", g_score); } Sleep(300); } system("pause"); return 0; } void drawMpa() { for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { printf("+---"); } printf("+\n"); for (int j = 0; j < 4; j++) { if (g_map[i][j] == 0) { printf("| "); } else { printf("|=", g_map[i][j]); } } printf("|\n"); } for (int j = 0; j < 4; j++) { printf("+---"); } printf("+\n"); } void randNum(int n=2) { srand((unsigned int)time(NULL)); int *p = (int *)g_map; if (n==4) { int x = rand() % 2; if (x == 0) n = 2; else n = 4; } int i = 0; while (1) { i = rand() % 16; if (p[i]==0) { p[i] = n; return; } } } void gotoxy(int x,int y) { HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); COORD pos = { x,y }; SetConsoleCursorPosition(hout, pos); } void movePoint(int dir) { int minI = 0, maxI = 0,minJ=0,maxJ=0; int nextX = 0,nextY = 0; if (dir == DIR_UP) { minI = 1; maxI = 4; minJ = 0; maxJ = 4; nextX = -1; } if (dir == DIR_DOWN) { minI = 0; maxI = 3; minJ = 0; maxJ = 4; nextX = 1; } if (dir == DIR_LEFT) { minI = 0; maxI = 4; minJ = 1; maxJ = 4; nextY = -1; } if (dir == DIR_RIGHT) { minI = 0; maxI = 4; minJ = 0; maxJ = 3; nextY = 1; } for (int i = minI; i < maxI; i++) { for (int j = minJ; j < maxJ; j++) { //如果当前结点是0,不用移动 if (g_map[i][j] == 0) { continue; } //如果下一个结点是0 else if (g_map[i + nextX][j+nextY] == 0) { g_map[i + nextX][j + nextY] = g_map[i][j]; g_map[i][j] = 0; movePoint(dir); return; } //如果下一个结点和当前结点相等 else if (g_map[i + nextX][j + nextY] == g_map[i][j]) { g_score++; g_map[i + nextX][j + nextY] *= 2; g_map[i][j] = 0; movePoint(dir); return; } } } }

 


最新回复(0)