首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >undo操作在2048游戏中的实现

undo操作在2048游戏中的实现
EN

Stack Overflow用户
提问于 2018-02-10 20:11:15
回答 2查看 481关注 0票数 1

我已经在C++中实现了2048游戏,github链接:2048

为了实现撤销操作,也就是返回到之前的游戏状态,我为之前的棋盘配置维护了一个矩阵,但是如果我允许许多连续的撤销操作,我就不能保持矩阵的数量。

有什么方法可以改进这种方法?

我认为的一种方法是只保留之前的移动(向上、向下、向左或向右),但只有这些信息不能帮助重新生成以前的状态,如果我在这种方法中遗漏了什么,或者它可以扩展,请建议一种方法来做到这一点。

EN

回答 2

Stack Overflow用户

发布于 2018-02-10 20:38:43

你可以将棋盘的当前状态存储到堆栈中,所以每次用户进行移动时,只要将其放入堆栈中,就可以得到一个堆栈,其中充满了用户移动的棋盘当前状态矩阵,并从最新的一个开始排序。因此,当你想要撤销他们的最新动作时,只需从堆栈中弹出,这将为你提供他们的最新操作。

代码语言:javascript
复制
...
std::stack<std::array<int, 16>> boardStates;
std::array<16, int> currentBoardState;
// whenever user makes a move
makeMove(currentBoardState)

//when they want to undo    
tempBoardState = undoMove();
if(tempBoardState != nullptr)
{
   currentBoardState = tempBoardState;
}
else
{
   std::cout << "No previous move available" << std::endl
}
...

void makeMove(std::array<int, 16> currentState)
{
   boardStates.push(currentState);
}

std::array<int, 16> undoMove()
{
    if(!boardStates.empty())
    {
        return boardStates.pop();
    }

    return nullptr;
}
票数 0
EN

Stack Overflow用户

发布于 2018-02-12 19:09:01

实现历史记录,以存储后续的板状态更改。

代码语言:javascript
复制
//maximum history size (can be whatever reasonable value)
const int MAX_UNDO = 2048;

//give a shorter name to the type used to store the board status
typedef std::array<int, 16> snapshot; 

//use a double ended queue to store the board statuses
std::deque<snapshot> history;

//this function saves the current status, has to be called each time 
//the board status changes, i.e. after the board initialization 
//and after every player move
void save()
{
    //make a copy of g, the current status
    snapshot f;
    std::copy(&g[0][0], &g[0][0] + 16, f.begin());

    //push the copy on top
    history.push_back(f); 

    //check history size
    if(history.size() > MAX_UNDO)
    {
        //remove one element at the bottom end
        history.pop_front();
    }
}

bool undo()
{
    //history must hold at least one element 
    //other than the current status copy
    if(history.size() > 1)
    {
        //the top element of the queue always holds a copy of the 
        //current board status: remove it first
        history.pop_back(); 

        //now the top element is the previous status copy
        snapshot f = history.back();

        //copy it back to g
        std::copy(f.begin(), f.end(), &g[0][0]);

        //undo operation succedeed
        return true;
    }

    //undo operation failed
    return false;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48720622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档