简单Windows控制台贪吃蛇(二维数组模拟地图, 链表模拟贪吃蛇, WASD控制行走, gotoxy替换刷新操作)
2016-07-07 16:29
423 查看
#include <stdlib.h> #include <iostream> #include <list> #include <conio.h> #include <time.h> #include <algorithm> #include <windows.h> using namespace std; const int MAXR = 20; const int MAXC = 50; void gotoxy(int x, int y) //定位到第y行的第x列 { int xx=0x0b; HANDLE hOutput; COORD loc; loc.X = x; loc.Y=y; hOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput, loc); return; } struct point { int x; int y; point& operator=(const point &p) { if(&p == this) return *this; x = p.x; y = p.y; return *this; } bool operator==(const point &p) { if(&p == this) return true; else if(x == p.x && y == p.y) return true; return false; } }; list<point> snake; point randP; void randPoint() { randP.x = 0 + (MAXR - 1 + 1) * rand() / RAND_MAX; randP.y = 0 + (MAXC - 1 + 1) * rand() / RAND_MAX; list<point>::iterator itor = find(snake.begin(), snake.end(), randP); if(itor == snake.end()) return; else randPoint(); } void initSnake() { point p; p.x = MAXR / 2; p.y = 2; snake.push_back(p); p.y--; snake.push_back(p); p.y--; snake.push_back(p); randPoint(); } void printArr(char arr[][MAXC]) { gotoxy(0, 0); cout << "w a s d控制方向,q退出:" << endl; for(int i = 0; i < MAXR; i++) for(int j = 0; j < MAXC; j++) arr[i][j] = '-'; arr[randP.x][randP.y] = '*'; list<point>::iterator itor; for(itor = snake.begin(); itor != snake.end(); itor++) arr[(*itor).x][(*itor).y] = '*'; for(int i = 0; i < MAXR; i++) { for(int j = 0; j < MAXC; j++) cout << arr[i][j]; cout << endl; } } int main(int argc, char* argv[]) { srand((int)time(0)); char arr[MAXR][MAXC]; initSnake(); printArr(arr); char inputC; bool effInput; point p = snake.front(); char state = 'd'; while((inputC = getch()) != 'q') { switch(inputC) { case 'w': if(state == 's') continue; state = 'w'; p.x--; break; case 'a': if(state == 'd') continue; state = 'a'; p.y--; break; case 's': if(state == 'w') continue; state = 's'; p.x++; break; case 'd': if(state == 'a') continue; state = 'd'; p.y++; break; default: continue; } if(p.x >= MAXR) p.x = 0; if(p.x < 0) p.x = MAXR - 1; if(p.y >= MAXC) p.y = 0; if(p.y < 0) p.y = MAXC - 1; snake.push_front(p); if(p == randP) randPoint(); else snake.pop_back(); //system("cls"); printArr(arr); } system("pause"); return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Linux C函数参考手册(PDF版)
- C# partial关键字说明
- Lua中调用C++函数示例
- Lua教程(十七):C API简介
- 简单谈谈lua和c的交互
- Lua教程(一):在C++中嵌入Lua脚本
- C#用链式方法表达循环嵌套
- Lua教程(二):C++和Lua相互传递数据示例
- C#中list用法实例
- C#中Ilist与list的区别小结
- C#中的委托数据类型简介
- C#中IList<T>与List<T>的区别深入解析
- C++联合体转换成C#结构的实现方法
- C#编写的艺术字类实例代码
- C#实现打造气泡屏幕保护效果