Update gtk140

This commit is contained in:
daleclack 2022-08-31 19:31:18 +08:00
parent 6be8ba1685
commit 52bd3c24ac
2 changed files with 69 additions and 5 deletions

View File

@ -1,6 +1,12 @@
#include "MineSweeper.hh" #include "MineSweeper.hh"
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>
MineSweeper::MineSweeper() MineSweeper::MineSweeper()
:main_box(Gtk::ORIENTATION_VERTICAL, 5),
btn_box(Gtk::ORIENTATION_HORIZONTAL, 5)
{ {
// Initalize Window // Initalize Window
set_title("Gtkmm MineSweeper"); set_title("Gtkmm MineSweeper");
@ -11,24 +17,78 @@ MineSweeper::MineSweeper()
{ {
for (int j = 0; j < 7; j++) for (int j = 0; j < 7; j++)
{ {
cell[i * 7 + j].set_label("?"); // cell[i * 7 + j].set_label("?");
cell[i * 7 + j].signal_clicked().connect(sigc::bind( cell[i * 7 + j].signal_clicked().connect(sigc::bind(
sigc::mem_fun(*this, &MineSweeper::cell_clicked), &cell[i * 7 + j])); sigc::mem_fun(*this, &MineSweeper::cell_clicked), &cell[i * 7 + j]));
mine_grid.attach(cell[i * 7 + j], j, i); mine_grid.attach(cell[i * 7 + j], j, i);
} }
} }
// Default setting
reset_game();
// Pack widgets
status_label.set_halign(Gtk::ALIGN_CENTER);
btn_box.set_halign(Gtk::ALIGN_CENTER);
main_box.pack_start(status_label, Gtk::PACK_SHRINK);
main_box.pack_start(mine_grid);
main_box.pack_start(btn_box, Gtk::PACK_SHRINK);
// Show everything // Show everything
add(mine_grid); add(main_box);
show_all_children(); show_all_children();
} }
void MineSweeper::reset_game() void MineSweeper::reset_game()
{ {
// Append item mine_count = 0;
// Reset all data
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
cell[i * 7 + j].set_label("?");
}
}
// Reset mines
while(mine_count < 9)
{
srand((unsigned)time(NULL));
int index1 = rand() % 7;
srand((unsigned)time(NULL));
int index2 = rand() % 7;
if(!(cell[index1 * 7 + index2].has_mine)){
cell[index1 * 7 + index2].has_mine = true;
cell[index1 * 7 + index2].set_label("x");
mine_count++;
}
}
game_ended = false;
winned = true;
} }
void MineSweeper::cell_clicked(MineCell *cell) void MineSweeper::cell_clicked(MineCell *cell)
{ {
if (!game_ended)
{
// If get mine, the game will end now
if (cell->has_mine)
{
winned = false;
game_ended = true;
}
else
{
mines_clear++;
cell->set_label(" ");
}
// If all the mines has cleared, you has winned
if (mines_clear == 40)
{
winned = true;
game_ended = true;
}
}
} }

View File

@ -5,7 +5,7 @@
class MineCell : public Gtk::Button class MineCell : public Gtk::Button
{ {
public: public:
bool is_mine = false; bool has_mine = false;
int mines_around; int mines_around;
MineCell(){ MineCell(){
// Set button style // Set button style
@ -21,7 +21,11 @@ public:
private: private:
// Child widgets // Child widgets
Gtk::Grid mine_grid; Gtk::Grid mine_grid;
Gtk::Label status_label;
Gtk::Box main_box, btn_box;
MineCell cell[49]; MineCell cell[49];
bool winned, game_ended;
int mines_clear, mine_count;
// Timer // Timer
sigc::connection mytimer; sigc::connection mytimer;