时间:2021-05-20
本文实例介绍了C++模仿华容道小游戏实现代码,分享给大家供大家参考,具体内容如下
#include <stdio.h>#include <stdlib.h>#include <time.h>#include <stdbool.h> #define maxnum 16#define colnum 4 bool numexists(int *numbers, int length, int num);int getnumber(int **numbers, int randIndex, int *length);int* initnumbers(void);void swap(int **a, int **b); int main(int argc, char *argv[]){ int *tempnumbers = initnumbers(); int *randnumbers = initnumbers(); int **numbers; numbers = malloc(maxnum * sizeof(int*)); //bool a = numexists(numbers, 16, 3); //printf("a=%d\n", a); int length = maxnum; srand((unsigned)time(NULL)); for (int i = 0; i < maxnum; i++) { int temp = getnumber(&tempnumbers, rand() % length, &length); randnumbers[i] = temp; numbers[temp] = &randnumbers[i]; //printf("%d%c", temp, (i + 1) % colnum == 0?'\n':'\t'); } if (tempnumbers != NULL) free(tempnumbers); while (true) { system("clear"); for (int i = 0; i < maxnum; i++) printf("%d%c", randnumbers[i], (i + 1) % colnum == 0?'\n':'\t'); printf("move number/ invalid num==exit: "); int i; if (!scanf("%d", &i)) { printf("game over\n"); break; } if (i >= maxnum || i <0) { printf("sorry, i can't find %d\n", i); break; } unsigned char sign = abs(numbers[i] - numbers[0]); switch (sign) { case 1: case 4: swap(&numbers[0], &numbers[i]); break; } } if (numbers != NULL) free(numbers); if (randnumbers != NULL) free(randnumbers);} void swap(int **a, int **b){ int *templocation = *a; int tempvalue = **a; **a = **b; **b = tempvalue; *a = *b; *b = templocation;} int* initnumbers(void){ int *numbers = malloc(maxnum * sizeof(int)); for (int i = 0; i < maxnum; i++) numbers[i] = i; return numbers;} int getnumber(int **numbers, int randIndex, int *length){ int result = (*numbers)[randIndex]; (*numbers)[randIndex] = (*numbers)[--(*length)]; int *temp = realloc(*numbers, (*length) * sizeof(int)); *numbers = temp; return result;} bool _numexists(int *numbers, int start, int end, int num){ printf("start: %d, end: %d, num: %d\n", start, end, num); if (start == end) return numbers[start] == num; else { int middle = (start+end) / 2; if (numbers[middle] == num) return true; else if (numbers[middle] > num) return _numexists(numbers, start, middle-1, num); else return _numexists(numbers, middle+1, end, num); }}bool numexists(int *numbers, int length, int num){ return _numexists(numbers, 0, length-1, num); }希望本文对大家学习C++程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
前言花了两天时间,重构了项目中的一个拼图小游戏(又名数字华容道),为了方便使用抽离成了独立组件,效果如下:线上体验源码地址在文章最后哦!主要重构点原有拼图游戏是
由于比赛需要,我这边制作了一份数字华容道,内含有3,4,5阶的数字华容道,开头在壳窗口内选择,运用了随机数模块(random)和图形化用户界面(tkinter)
本文实例为大家分享了C++实现走迷宫小游戏的具体代码,供大家参考,具体内容如下源码下载:C++实现走迷宫小游戏主程序代码:#include#include#in
C/C++实现扫雷小游戏源代码:github:https://github.com/KamSss/C-Practice/tree/master/Mineswee
大一,上学期学完了C,写了几个控制台游戏这学期自学C++,由于学校课程第七周才有C++边学边写了这个小游戏,SDL图形库完成的图形绘画时间匆忙,BUG也有,代码