C++遊戲編程:Pacman

Pacman

基於貪吃蛇小遊戲,本人寫了個界面極其簡單的吃豆人遊戲。
“#”代表吃豆人,遊戲邊框用“@”表示,豆子用“o”表示。
豆子每次吃完隨機出現在界面,吃到豆子加1分。
當人撞牆遊戲結束,並顯示最終分數。

源代碼:

#include<iostream>
#include<windows.h>
#include<ctime>
#include<cstdlib>
#include<conio.h>
using namespace std;
#define N 20
#define M 50
char board[N][M];
int a = 12;
int b = 10;
int food_x;
int food_y;
int count = 0;

//遊戲邊框
void Fence(){
	for(int i = 0;i<N;i++)
	    for(int j = 0;j<M;j++){
	    	if(i == 0 || i == N-1 || j == 0 || j == M-1){
	    		board[i][j] = '@';
	    	}
	    	else{
	    		board[i][j] = ' ';
	    	}
	    }
}

//界面顯示
void Display(){
	cout<<"方向鍵控制,吃豆子獲得分數!"<<endl;
	for(int i = 0;i<N;i++){
		for(int j = 0;j<M;j++){
	    	cout<<board[i][j];
	    }
	    cout<<endl;
	}
	cout<<"您的分數:"<<count<<endl;
}

//隨機出現的豆子
void Food(){
	srand((unsigned int) time(NULL)); //做種子(程序運行時間);
    food_x = rand() % 18 + 1;
    food_y = rand() % 48 + 1;

    while(board[food_x][food_y] == 'o'){
        food_x = rand() % 18 + 1;
        food_y = rand() % 48 + 1;
    }

    board[food_x][food_y] = 'o';
}

//判斷撞牆和吃到豆子
int Judge(){
	if(a == 0 || a == N-1 || b == 0 || b == M-1){
		board[a][b] = '#';
		return 0;
	}
	else if(a == food_x && b == food_y){
		board[a][b] = '#';
		count++;
		Food();
		return 1;
	}
	else{
		board[a][b] = '#';
		return 2;
	}
}

//控制吃豆人
void Move(int key){
	board[a][b] = ' ';
	switch(key){
		case 72: --a; break;
        case 80: ++a; break;
        case 75: --b; break;
        case 77: ++b; break;
	}
}



int main(){
	Fence();
	board[a][b] = '#';
	Food();
	Display();
	int key = getch();
	int res;
	
	while(1){
		while(!kbhit()){
			system("cls");
		    Move(key);
		    res = Judge();
		    if(res == 0)  break;
		    Display();
		}
		if(res == 0)  break;
		key = getch();
	}
	
	Display();
    cout<<"Game Over!"<<endl;
    cout<<"您的最終分數:"<<count<<endl;
	system("pause");
	return 0;
}

遊戲界面:
在這裏插入圖片描述
在這裏插入圖片描述

發佈了18 篇原創文章 · 獲贊 85 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章