C语言打砖块小游戏
锦鲤金叔叔 人气:0本文为大家分享了C语言控制台小游戏,打砖块,供大家参考,具体内容如下
这个问题是我在领扣上面看到的一道困难问题,原题是这样的:
#include "stdafx.h" #include<stdio.h> int a[10][10] = { { 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }, { 0, 0, 1, 1, 1, 1, 0, 1, 1, 0 }, { 0, 0, 0, 0, 1, 1, 0, 1, 1, 0 }, { 0, 1, 1, 1, 1, 1, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } };//初始化二维数组,写成这个形状便于一目了然 void down(int a[10][10])//负责控制砖块下落的函数,使被赋值为3的砖块下落,下落到下界或值为1的方块之上 { int i, j; int m, n; for (i = 9; i >=0; i--) for (j = 0; j < 10; j++) if (a[i][j] == 3) { m = i; n = j; while (a[m + 1][n] != 1&&m!=9) { a[m + 1][n] = 1; a[m][n] = 0; m++; } } } void freshen(int a[10][10])//刷新函数,用于每次打过砖块之后,检查所有砖块的松动情况,过程大概是这样的,先将全部为1的砖块赋值为3,之后将四周与墙壁相连并且值为3的砖块赋值为·1,然后再进行一次全体砖块的循环遍历,这一次将所有与1相连接(1上下左右连接的砖块并且值为3的)的砖块赋值为1,这样的操作要做四遍,为什么要做这么多遍,这个问题留给读者体会。 { int i, j; for ( i = 0; i < 10; i++) for ( j = 0; j < 10; j++) if (a[i][j]==1) a[i][j] = 3; for (i = 0; i < 10; i++) { j = 0; while (a[i][j] != 0) { a[i][j] = 1; j++; } } for (i = 0; i < 10; i++) { j = 9; while (a[i][j] != 0) { a[i][j] = 1; j--; } } for (j = 0; j < 10; j++) { i = 0; while (a[i][j] != 0) { a[i][j] = 1; i++; } } for (j = 0; j < 10; j++) { i = 9; while (a[i][j] != 0) { a[i][j] = 1; i--; } } for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) if (a[i][j] == 1) { if (a[i - 1][j] == 3) a[i - 1][j] = 1; else if (a[i + 1][j] == 3) a[i + 1][j] = 1; else if (a[i ][j-1] == 3) a[i ][j-1] = 1; else if (a[i ][j+1] == 3) a[i ][j+1] = 1; } for (i = 9; i >=0; i--) for (j = 9; j >=0; j--) if (a[i][j] == 1) { if (a[i - 1][j] == 3) a[i - 1][j] = 1; else if (a[i + 1][j] == 3) a[i + 1][j] = 1; else if (a[i][j - 1] == 3) a[i][j - 1] = 1; else if (a[i][j + 1] == 3) a[i][j + 1] = 1; } for (i = 9; i >= 0; i--) for (j = 9; j >= 0; j--) if (a[i][j] == 1) { if (a[i - 1][j] == 3) a[i - 1][j] = 1; else if (a[i + 1][j] == 3) a[i + 1][j] = 1; else if (a[i][j - 1] == 3) a[i][j - 1] = 1; else if (a[i][j + 1] == 3) a[i][j + 1] = 1; } for (i = 9; i >= 0; i--) for (j = 9; j >= 0; j--) if (a[i][j] == 1) { if (a[i - 1][j] == 3) a[i - 1][j] = 1; else if (a[i + 1][j] == 3) a[i + 1][j] = 1; else if (a[i][j - 1] == 3) a[i][j - 1] = 1; else if (a[i][j + 1] == 3) a[i][j + 1] = 1; } } void view(int a[10][10])//打印砖块函数 { for (int i = -1; i < 10; i++) { printf("0%d ", i); } printf("\n"); for (int i = 0; i < 10; i++) { printf("%d: ", i); for (int j = 0; j < 10; j++) { if (a[i][j] == 1) printf("* "); else printf(" "); } printf("\n"); } } void beat(int a[10][10],int i,int j)//打砖块函数 { a[i][j] = 0; } void main() { int p,q; view(a); for (int w = 0; w < 18; w++) { printf("beat whichp?\n"); scanf("%d", &p); printf("beat whichq?\n"); scanf("%d", &q); beat(a, p, q); freshen(a); down(a); view(a); } getchar(); return; }
我用到的编译器是VS2013,C语言写控制台程序,大一初学C语言的同学们可以看一下这个编程思想。
最后的效果是这样的:
加载全部内容