簡易迷宮程序

      通過W、S、A、D四個按鍵分別控制上、下、左、右移動,Q退出程序,利用數組自己設定了一個簡單的迷宮圖,並通過for循環利用puts顯示,通過system("cls");刷新屏幕顯示。

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
class Maze
{
private:
	int x, y, xout, yout;
	char ch;
	char a[100][100] = { "**********",
		"*O       *",
		"**  ******",
		"***      *",
		"* ****** *",
		"*     ** *",
		"* ***    *",
		"* *   ****",
		"* ********",
		"* ********",
	};//豎着的是x,橫着的是y
public:
	void Run();
};


void Maze::Run()
{
	x = 1; y = 1; xout = 9; yout = 1;
	for (int i = 0; i <= 10; i++)
	{
		puts(a[i]); //用於打印顯示a中的數據
	}
	while (x != xout || y != yout)//如果未走到終點則繼續走,或者通過q退出
	{
		cin >> ch;
		//ch=getchar();
		cout << ch <<'\n'<< endl;
		if (ch == 'q' || ch == 'Q')
		{
			cout << "退出遊戲" << endl;
			break;
		}
		if (ch == 's' || ch == 'S')//上移
		{
			if (a[x + 1][y] != '*')
			{
				a[x][y] = ' ';
				x++;
				cout << x << endl;
				a[x][y] = 'O';
			}
		}
		if (ch == 'w' || ch == 'W')//下移
		{
			if (a[x - 1][y] != '*')
			{
				a[x][y] = ' ';
				x--;
				a[x][y] = 'O';
			}
		}
		if (ch == 'a' || ch == 'A')//左移
		{
			if (a[x][y - 1] != '*')
			{
				a[x][y] = ' ';
				y--;
				a[x][y] = 'O';
			}
		}
		if (ch == 'd' || ch == 'D')//右移
		{
			if (a[x][y + 1] != '*')
			{
				a[x][y] = ' ';
				y++;
				a[x][y] = 'O';
			}
		}
		system("cls");
		for (int i = 0; i <= 10; i++)
		{
			puts(a[i]);//用於打印顯示a中的數據
		}
	}
	system("cls");
	cout << "恭喜你贏了!" << endl;
}

int main()
{
	Maze maze;
	maze.Run();
	Sleep(5000);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章