#include <stdio.h> #define ROWS 10 #define COLS 11
void showMap();
char enterDirection();
void moveToUp(); void moveToDown(); void moveToLeft(); void moveToRight(); char map[ROWS][COLS] = { "##########", "# #### #", "# X#### #", "# O #", "###### #", "# #### #", "# #", "# ######", "# ", "##########" };
int personCurrenRow = 3; int personCurrenCol = 2; int main(int argc, const char * argv[]) { showMap(); char dir = enterDirection(); //根据用户的输入移动 switch (dir) { //向上移动 case 'w': case 'W': moveToUp(); break; //向下移动 case 's': case 'S': moveToDown(); break; //向左移动 case 'a': case 'A': moveToLeft(); break; //向右移动 case 'd': case 'D': moveToRight(); break; case 'q': case 'Q': printf("游戏结束\n"); return 0; default: break; } return 0; } void showMap () { for (int i = 0; i < ROWS; i++) { printf("%s\n", map); } }
char enterDirection() { char ch = 'a'; printf("请输入方向: w:上 s:下 a:左 d:右 q:退出游戏"); rewind(stdin); scanf("%c",&ch); return ch; } void moveToUp() { int personNextRow = personCurrenRow -1; int personNextCol = personCurrenCol; if (map[personNextRow][personNextCol] == ' ') { map[personCurrenRow][personCurrenCol] = ' '; map[personNextRow][personNextCol] = 'O'; personCurrenRow = personNextRow; personCurrenCol = personNextCol; } else if (map[personNextRow][personNextCol] == 'X') { int boxNextRow = personNextRow -1; int boxNextCol = personNextCol; if (map[boxNextRow][boxNextCol] == ' ') { map[boxNextRow][boxNextCol] = 'X'; map[personNextRow][personNextCol] = 'O'; map[personCurrenRow][personCurrenCol] = ' '; personCurrenRow = personNextRow; personCurrenCol = personNextCol; } } } void moveToDown(); void moveToLeft(); void moveToRight();
|