控制台小遊戲之貪吃蛇

2021-07-09 04:52:58 字數 2247 閱讀 3256

貪吃蛇和俄羅斯方塊差不多,都是另起乙個執行緒監聽鍵盤輸入,然後就是不斷重新整理。(控制台跳屏的感覺真不爽,感覺要瞎了)

很簡單的就乙個snake類和乙個game類外加輔助的random_food可呼叫物件類。用列舉變數代表snake當前的行進方向

point_and_dir.h

#ifndef _point_and_dir_h

#define _point_and_dir_h

enum _direction;

class _pt

inline int x()const

inline int y()const

inline void set(int x, int y)

bool operator== (const _pt & rhs)

private:

int _x;

int _y;

};#endif

random_food.h

#ifndef _random_food_h

#define _random_food_h

#include#include"point_and_dir.h"

struct random_food

};#endif

snake.h

#ifndef _snake_h

#define _snake_h

#include#include"point_and_dir.h"

class snake

void move();

void grow();

bool collided();

bool setdir(_direction);

int length()const

_pt bodies(int i)

private:

_direction dir;

std::list<_pt> body;

};#endif

game.h

#ifndef _game_h

#define _game_h

#include#include"snake.h"

class game

void start();

private:

void print();

void keylistener();

void keydown(char);

void move();

bool setdir(_direction);

void makefood();

bool crashed();

void checkfood();

std::mutex mtx;

int score;

int width;

int height;

bool growing;

_pt food;

snake snake;

};#endif

snake.cpp

#include"snake.h"

void snake::move()

void snake::grow()

body.push_front(offset);

}bool snake::collided()

bool snake::setdir(_direction d)

game.cpp

#include#include#include#include#include#include#include"game.h"

#include"random_food.h"

void game::print()

void game::keylistener()

mtx.unlock();

}void game::start()

sleep(200);

} mtx.unlock();

std::cout << "game over!" << std::endl;

}

食用方法:

main.cpp

#include"game.h"

int main()

貪吃蛇 控制台

本文把遊戲區域就行編號,第一行從0到width 1,到height 1 到 width height 1 二維陣列 並用trace len 陣列儲存snake移動的軌跡 儲存的是數值,數值就能表現出所在的行和列 trace 0 始終為snake的頭部 根據display 函式繪圖,延時,在繪圖,達到...

C 控制台實現貪吃蛇遊戲

剛學完了c語言,便嘗試的寫了貪吃蛇的 但是效果不佳,很多的bug,所以,這個學了c 便重新的寫了這個小遊戲,用類來封裝!先是標頭檔案 struct snake class snake snake void display 顯示蛇身函式 void rightmove 右移函式 void leftmov...

控制台版貪吃蛇

include include include include include 地圖大小 define map size 20 全域性螢幕輸出快取區控制代碼 handle g houtput 地圖屬性 struct mapnode s nodetype e type 全域性地圖資料 mapnode ...