Ho un problema con il mio gioco "Akari". Dunque: dovrei capire come riuscire a salvare la partita in un file e successivamente riuscire a ricaricarla dopo aver chiuso e riaperto il programma. Il gioco ha già a disposizione anche una finestra "New Game" che funziona.
Posto il codice che vorrei modificare grazie al vostro aiuto.
#include "mainwindow.h"
#include "gamegui.h"
#include "akari.h"
#include <fstream>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QLayout>
MainWindow::MainWindow()
{
setWindowTitle(tr("Akari"));
auto menu = menuBar()->addMenu(tr("Game"));
auto game_act = menu->addAction(tr("New"));
connect(game_act, &QAction::triggered,
this, &MainWindow::new_game);
auto load_act = menu->addAction(tr("Load"));
connect(load_act, &QAction::triggered,
this, &MainWindow::load_game);
auto save_act = menu->addAction(tr("Save"));
connect(save_act, &QAction::triggered,
this, &MainWindow::save_game);
new_game();
}
void MainWindow::new_game()
{
if (centralWidget() != nullptr) delete centralWidget();
if (game_ != nullptr) delete game_;
game_ = new Akari;
setCentralWidget(new GameGui{game_});
adjustSize();
}
void MainWindow::load_game()
{
auto fn = QFileDialog::getOpenFileName(this);
if (fn != "") {
if (centralWidget() != nullptr) delete centralWidget();
if (game_ != nullptr) delete game_;
game_ = new Akari{fn.toStdString()};
setCentralWidget(new GameGui{game_});
adjustSize();
}
}
void MainWindow::save_game()
{
auto fn = QFileDialog::getSaveFileName(this);
if (fn != "") {
ofstream out{fn.toStdString()};
if (out.good()) {
// write the whole text
QString text = text_edit->toPlainText();
out << text.toStdString();
}
}
}