贪吃蛇

https://blog.csdn.net/misayaaaaa/article/details/146101447

 

 

L G U G R G G
3 4
F E F E
E H E E
E E F E

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <deque>
#include <unordered_map>
#include <algorithm> // 用于 find_if
using namespace std;

typedef struct {
    int dx;
    int dy;
} Direction;

int main() {
    string input_line;
    vector<char> orders;
    int n, m;
    
    // 读取指令
    getline(cin, input_line);
    istringstream iss(input_line);
    char order;
    while (iss >> order) {
        orders.push_back(order);
    }
    
    // 读取地图
    cin >> n >> m;
    vector<vector<char>> matrix(n, vector<char>(m));
    deque<pair<int, int>> body; // 蛇身体
    vector<pair<int, int>> foods; // 食物列表
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> matrix[i][j];
            if (matrix[i][j] == 'H') {
                body.push_front({i, j}); // 蛇头
            } else if (matrix[i][j] == 'F') {
                foods.push_back({i, j}); // 存储食物
            }
        }
    }
    
    // 初始方向向左
    char current_dir = 'L';
    unordered_map<char, Direction> dir_map = {
        {'U', {-1, 0}},
        {'D', {1, 0}},
        {'L', {0, -1}},
        {'R', {0, 1}}
    };
    
    // 处理指令
    for (char cmd : orders) {
        if (cmd == 'G') {
            // 计算新蛇头位置
            Direction dir = dir_map[current_dir];
            int nx = body.front().first + dir.dx;
            int ny = body.front().second + dir.dy;
            
            // 碰撞检测:边界、障碍物、身体
            if (nx < 0 || nx >= n || ny < 0 || ny >= m || matrix[nx][ny] == 'S') {
                break; // 游戏结束
            }
            
            // 检查是否撞到身体(除了蛇尾)
            bool collide = false;
            for (auto it = body.begin(); it != body.end(); ++it) {
                if (it != body.end() - 1 && nx == it->first && ny == it->second) {
                    collide = true;
                    break;
                }
            }
            if (collide) {
                break; // 游戏结束
            }
            
            // 移动蛇头
            body.push_front({nx, ny});
            
            // 检查是否吃到食物(遍历 foods)
            auto it = find_if(foods.begin(), foods.end(), [nx, ny](const pair<int, int>& p) {
                return p.first == nx && p.second == ny;
            });
            
            if (it != foods.end()) {
                foods.erase(it); // 删除该食物
            } else {
                body.pop_back(); // 没吃到食物,删除蛇尾
            }
        } else {
            // 更新方向
            current_dir = cmd;
        }
    }
    
    cout << body.size() << endl;
    return 0;
}

 

posted @ 2025-08-10 16:12  最近饭吃的很多  阅读(8)  评论(0)    收藏  举报