大家一起来,打地鼠
无聊编了个打地鼠的字符简易小游戏,与大家一起分享这个游戏需要 SDL 的支持,用 SDL 检测按键还有定时器确是比较方便阿(不过这个小游戏只用到了定时器)
还有一个小缺陷,因为是个简易版就懒得搞了,就是按键之后还得再按下回车,不过“有条件的同学”可以把 getchar 换成 getch 就 OK 了
还有 clear_screen,windows 下的同学需要修改一下 system ("cls");
小游戏,结构简单,不多说了,上代码
程序代码:
#include "stdlib.h" #include "stdio.h" #include "SDL2/SDL.h" struct map { char state[3][3]; //state of every cave }; struct map map = {{0, 0, 0, 0, 0, 0, 0, 0, 0}}; void clear_screen (void) { system ("clear"); //clear the screen, can't use gotoxy } void draw_map (struct map *map) //use pointer can save space { clear_screen (); int i,j; for (i=0; i<3; i++) { for (j=0; j<3; j++) { if ((*map).state[i][j]) //map[y][x] { printf ("%c ", '$'); //use $ represent mouse } else { printf ("%c ", '0'); } } printf ("\n"); } } void change_state (struct map *map, int pos) //pos range [0, 8] { int x, y; x = pos%3; y = pos/3; (*map).state[y][x] = !(*map).state[y][x]; } int get_state (struct map *map, int pos) //pos range [0, 8] { int x, y; x = pos%3; y = pos/3; return (*map).state[y][x]; } int judge (struct map *map) { int i,j; for (i=0; i<3; i++) { for (j=0; j<3; j++) { if ((*map).state[i][j]) { return 1; } } } return 0; } void over (void) { printf ("Game Over"); exit (0); } Uint32 SDL_callback (Uint32 interval, struct map *map) { if (judge(map)) { over (); } else { change_state (map, rand()%9); draw_map (map); return interval; } } /* change 7 8 9 to 1 2 3 * 4 5 6 4 5 6 * 1 2 3 7 8 9 */ void change_key (int *key) //change the key to adapt the program { switch (*key) { case 7: *key=1; break; case 8: *key=2; break; case 9: *key=3; break; case 1: *key=7; break; case 2: *key=8; break; case 3: *key=9; break; } } int main (void) { int key; SDL_TimerID timer; SDL_Init (SDL_INIT_TIMER); change_state (&map, rand()%9); draw_map (&map); timer = SDL_AddTimer (2000, (SDL_TimerCallback)SDL_callback, &map); while (key = getchar ()) { //handle the key if ((key<'1') || (key>'9')) { continue; } key -= 0x30; change_key (&key); key -= 1; if (get_state (&map, key)) { change_state (&map, key); draw_map (&map); } } SDL_RemoveTimer (timer); return 0; }
不足之处,敬请指正
[ 本帖最后由 pycansi 于 2014-9-13 15:50 编辑 ]