C++實現(xiàn)簡單貪吃蛇游戲
我大概在一個多月前把自己上學期寫的c代碼的貪吃蛇游戲push到csdn上,并且說c風格的貪吃蛇寫起來有些麻煩(貪吃蛇游戲的c語言實現(xiàn)),準備用面向?qū)ο蟮腸++再寫一遍。現(xiàn)在我們專業(yè)恰好剛教完了c++,學校也布置了一道簡單的貪吃蛇的編程題目,實現(xiàn)下來,的確覺得c++的思路清晰很多,所以再次把c++的代碼push上來,供大家對比參考:)
直接上代碼,c++把整個游戲拆分成幾個文件,分開上,有一定的c++基礎(chǔ)的同學應(yīng)該可以很容易看懂。
1、全局頭文件(global.hpp)
#ifndef _GLOBAL_H_
#define _GLOBAL_H_
#ifndef SYMBOLS
#define HEAD '@'
#define BODY 'X'
#define EMPTY '+'
#define FOOD '$'
#endif // !SYMBOLS
enum direction { up = 0, down = 1, left = 2, right = 4, freeze = 5 };
struct point {
 int x;
 int y;
 point(int x = 0, int y = 0) : x(x), y(y) {}
 point(const point& another) : x(another.x), y(another.y) {}
 point& operator=(const point& other) {
  x = other.x;
  y = other.y;
  return *this;
 }
 friend bool operator==(const point& point1, const point& point2) {
  return point1.x == point2.x && point1.y == point2.y;
 }
 point& move(direction d) {
  switch (d) {
   case up:
    x--;
    break;
   case down:
    x++;
    break;
   case left:
    y--;
    break;
   case right:
    y++;
    break;
   case freeze:
   default:
    break;
  }
  return *this;
 }
};
#endif // !_GLOBAL_H_
2、snake類的聲明和實現(xiàn)(snake.hpp)
(為了簡化結(jié)構(gòu),把聲明和實現(xiàn)共同放在了hpp文件里,減少了一點封裝性,實際上應(yīng)該分開頭文件和實現(xiàn)文件好一點)
此處使用了容器list作為蛇身(body)的表達形式,這樣可以非常方便地進行表達,讀者有興趣可以用數(shù)組實現(xiàn)一下,一不小心就會出現(xiàn)有趣的內(nèi)存錯誤。。。
#ifndef _SNAKE_H_
#define _SNAKE_H_
#include <iostream>
#include <list>
#include "global.hpp"
class snake {
    point head;
    std::list<point> body;
  public:
    snake(point initial_head);
    snake();
    ~snake() {}
    point& getHead();
    std::list<point>& getbody();
    void grow(point);
    void setHead(point);
};
snake::snake() {
  head.x = 0;
  head.y = 0;
}
snake::snake(point initial_head) {
  setHead(initial_head);
}
void snake::setHead(point _head) {
  head = _head;
}
void snake::grow(point second_node) {
  this -> body.push_front(second_node);
}
point& snake::getHead() {
  return head;
}
std::list<point>& snake::getbody() {
  return body;
}
#endif
3、map類的聲明和實現(xiàn)(map.hpp)
在這里,map中應(yīng)該包含一個snake類作為組合關(guān)系。 
在組合關(guān)系里面,想要直接修改snake的各種參數(shù)是不可行的,所以在前面snake類的聲明里加上了諸如setHead(), getHead(), getbody() 這一類的函數(shù)。
#ifndef _MAP_H_
#define _MAP_H_
#include <iostream>
#include "global.hpp"
#include "snake.hpp"
class map {
  private:
    char** _map;
    snake _snake;
    int height, width;
    std::list<point> foods;
  public:
    map();
    map(point initial_size, point initial_head,
    std::list<point> initial_foods);
    ~map();
    void move(direction d);
    void print();
    bool isGameOver();
    bool isEat();;
    void makemap(void);
};
map::map() {
  _map = NULL;
  height = width = 0;
}
void map::makemap() { // 這個是用來更新地圖的
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++)
      _map[i][j] = 0;
  }
  for (std::list<point>::iterator i = foods.begin(); i != foods.end(); ++i) {
    _map[i->x][i->y] = FOOD;
  }
  _map[_snake.getHead().x][_snake.getHead().y] = HEAD;
  for (std::list<point>::iterator i = _snake.getbody().begin();
  i != _snake.getbody().end(); ++i) {
    _map[i->x][i->y] = BODY;
  }
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      if (_map[i][j] == 0)
        _map[i][j] = EMPTY;
    }
  }
}
map::map(point initial_size, point initial_head, std::list<point> initial_foods)
{
  height = initial_size.x;
  width = initial_size.y;
  _map = new char*[height];
  for (int i = 0; i < height; i++)
    _map[i] = new char[width]();
  _snake.setHead(initial_head);
  foods = initial_foods;
  makemap();
}
map::~map() {
  for (int i = 0; i < height; i++) {
    delete []_map[i];
  }
  delete []_map;
}
void map::print() {
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      std::cout << _map[i][j];
    }
    std::cout << std::endl;    
  }
  std::cout << std::endl;
}
bool map::isGameOver() {
  point temp = _snake.getHead();
  if (temp.x == height || temp.y == width || temp.x < 0 || temp.y < 0)
    return true;
  if (_map[temp.x][temp.y] == BODY) return true;
  return false;
}
bool map::isEat() {
  point temp = _snake.getHead();
  if (temp.x == height || temp.y == width || temp.x < 0 || temp.y < 0)
    return false;
  if (_map[temp.x][temp.y] == FOOD) return true;
  else return false;
}
void map::move(direction d) {
  point temp_f = _snake.getHead();
  if (!(_snake.getbody().empty())) { // 為了避免追尾問題
    _map[_snake.getbody().back().x][_snake.getbody().back().y] = EMPTY;
  }
  _snake.getHead().move(d);
  if (_snake.getHead() == _snake.getbody().front()) { // 判斷蛇是否往回走
    _snake.setHead(temp_f);
    _map[_snake.getbody().back().x][_snake.getbody().back().y] = BODY;
    return;
  }
  if (!isGameOver()) {
    if (isEat()) {
      point eaten = _snake.getHead();
      foods.remove(eaten);
      _snake.grow(temp_f);
    } else {
      _snake.getbody().push_front(temp_f);
      _snake.getbody().pop_back();
    }
    makemap();
  } else {
    if (!(_snake.getbody().empty())) {
      _map[_snake.getbody().back().x][_snake.getbody().back().y] = BODY;
    }
  }
}
#endif
蛇移動的算法是,頭先動,如果判斷可以走,則把頭原來的位置push_front到body的頭部,然后用pop_back把body的尾部抹去 
(讀者不熟悉list容器的操作的話可以先去了解一下,很容易的:))
4、游戲運行主文件(game.cpp)
#include "map.hpp"
#include "global.hpp"
#include <iostream>
#include <list>
#include <algorithm>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
class InvalidInputException {
 public:
 InvalidInputException() { cerr << "Invalid input!" << endl; }
};
class DuplicateInputException : public InvalidInputException {
 public:
 DuplicateInputException() { cerr << "Duplicate input!" << endl; }
};
class GameUI {
 private:
 map* world;
 point initial_size;
 point initial_head;
 std::list<point> initial_foods;
 public:
 GameUI() {
  cout << "please input two positive integers indicates the map size!"
     << endl;
  cin >> initial_size.x >> initial_size.y;
  if (initial_size.x <= 5 || initial_size.y <= 5 || initial_size.x > 15 ||
    initial_size.y > 15) {
   cout << "invalid input" << endl;
   throw InvalidInputException();
  }
  cout << "please input two positive integers(range(0, size_x-1), "
      "range(0,size_y-1)) the initialize snake head position!"
     << endl;
  cin >> initial_head.x >> initial_head.y;
  if (initial_head.x >= initial_size.x || initial_head.x < 0 ||
    initial_head.y >= initial_size.y || initial_head.y < 0) {
   cout << "invalid input" << endl;
   throw InvalidInputException();
  }
  int food_num;
  cout << "please input how many food you will put and then input food "
      "position which is different form each other"
     << endl;
  cin >> food_num;
  if (food_num <= 0) {
   throw InvalidInputException();
  }
  while (food_num > 0) {
   food_num--;
   point temp;
   cin >> temp.x >> temp.y;
   if (temp.x >= 0 && temp.x < initial_size.x && temp.y >= 0 &&
     temp.y < initial_size.y &&
     std::find(initial_foods.begin(), initial_foods.end(), temp) ==
       initial_foods.end() &&
     !(temp.x == initial_head.x && temp.y == initial_head.y)) {
    initial_foods.push_back(temp);
   } else {
    throw DuplicateInputException();
   }
  }
  world = new map(initial_size, initial_head, initial_foods);
 }
 ~GameUI() { delete world; }
 void GameLoop() {
  world->print();
  bool exit = false;
  while (true) {
   char operation = getInput();
   switch (operation) {
    case 'w':
    case 'W':
     this->world->move(up);
     break;
    case 's':
    case 'S':
     this->world->move(down);
     break;
    case 'a':
    case 'A':
     this->world->move(left);
     break;
    case 'd':
    case 'D':
     this->world->move(right);
     break;
    case 'q':
    case 'Q':
     exit = true;
     break;
    default:
     this->world->move(freeze);
   }
   world->print();
   if (world->isGameOver()) {
    cout << "Game Over!" << endl;
    break;
   }
   if (exit) {
    cout << "Bye!" << endl;
    break;
   }
  }
 }
 char getInput() {
  char temp;
  cin >> temp;
  return temp;
 }
};
int main() { // 看,main函數(shù)只有這么短!?。?!
 GameUI greedySnake;
 greedySnake.GameLoop();
 return 0;
}
(事實上為了達到封裝性,gameUI的類也應(yīng)該分開來實現(xiàn)。)
5、小結(jié)
這個貪吃蛇還比較的低端,只能實現(xiàn)一鍵一步的行走方式,還沒有像我的c語言貪吃蛇那樣可以自己走,并且有AI模式。實現(xiàn)自己走要使用到windows的下的一個庫,實現(xiàn)起來還比較麻煩,可以參考我的c貪吃蛇。用c++重寫一遍貪吃蛇,主要作用是可以更加清楚地體會到類的封裝與使用。
以后如果有時間,筆者可能會為這個貪吃蛇寫下補丁什么的,體會一下c++的代碼重用和方便修改的特性,這是c語言所沒有的優(yōu)點。
Enjoy coding! :)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。
您可能感興趣的文章
- 04-02c語言沒有round函數(shù) round c語言
 - 01-10數(shù)據(jù)結(jié)構(gòu)課程設(shè)計-用棧實現(xiàn)表達式求值的方法詳解
 - 01-10使用OpenGL實現(xiàn)3D立體顯示的程序代碼
 - 01-10深入理解C++中常見的關(guān)鍵字含義
 - 01-10求斐波那契(Fibonacci)數(shù)列通項的七種實現(xiàn)方法
 - 01-10C語言 解決不用+、-、&#215;、&#247;數(shù)字運算符做加法
 - 01-10使用C++實現(xiàn)全排列算法的方法詳解
 - 01-10c++中inline的用法分析
 - 01-10用C++實現(xiàn)DBSCAN聚類算法
 - 01-10深入全排列算法及其實現(xiàn)方法
 


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
 - 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
 - 04-02c語言的正則匹配函數(shù) c語言正則表達
 - 04-02c語言用函數(shù)寫分段 用c語言表示分段
 - 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
 - 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
 - 04-02c語言沒有round函數(shù) round c語言
 - 04-02c語言分段函數(shù)怎么求 用c語言求分段
 - 04-02C語言中怎么打出三角函數(shù) c語言中怎
 - 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
 
隨機閱讀
- 04-02jquery與jsp,用jquery
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 08-05織夢dedecms什么時候用欄目交叉功能?
 - 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
 - 01-10delphi制作wav文件的方法
 - 08-05DEDE織夢data目錄下的sessions文件夾有什
 - 01-10C#中split用法實例總結(jié)
 - 01-10使用C語言求解撲克牌的順子及n個骰子
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 01-11ajax實現(xiàn)頁面的局部加載
 


