File: Sample_Minesweeper.cpp

package info (click to toggle)
cegui-mk2 0.7.6-3.3
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 105,388 kB
  • ctags: 82,178
  • sloc: cpp: 142,729; ansic: 27,984; sh: 11,010; makefile: 2,275; python: 916; xml: 17
file content (529 lines) | stat: -rw-r--r-- 19,029 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/***********************************************************************
    filename:   Sample_Minesweepze.cpp
    created:    05/08/2006
    author:     Olivier Delannoy (Dalfy)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGuiSample.h"
#include "CEGUI.h"
#include "Minesweeper_Timer.h"
#include <ctime>
#include <cstdlib>
struct Location
{
    size_t d_row;
    size_t d_col;
};
const size_t MinesweeperSize = 10;
const size_t MineCount = 15;

class MinesweeperSample : public CEGuiSample
{
public:
    // method to initialse the samples windows and events.
    bool initialiseSample();

    // method to perform any required cleanup operations.
    void cleanupSample(void);

protected:
    // Handle new game
    bool handleGameStartClicked(const CEGUI::EventArgs& event);
    // Handle click on a button of the board
    bool handleMineButtonClicked(const CEGUI::EventArgs& event);
    // Handle mouse button down on a button of the board
    bool handleMineButtonDown(const CEGUI::EventArgs& event);
    // Update the timer if needed
    bool handleUpdateTimer(const CEGUI::EventArgs& event);
    // reset the board
    void boardReset();
    // place mine and computes mine neighborhood
    void boardPositionMines();
    // Test whether the player wins or not
    bool isGameWin();
    // Call this function if the game is finished
    void gameEnd(bool victory);
    // When a button is clicked
    bool boardDiscover(const Location& location);
    // Store all buttons needed
    CEGUI::PushButton* d_buttons[MinesweeperSize][MinesweeperSize];
    // Store button location
    Location d_buttonsMapping[MinesweeperSize][MinesweeperSize];
    // Store the value of the board itself
    size_t d_board[MinesweeperSize][MinesweeperSize];
    // Store the number of case the user discovered
    size_t d_boardCellDiscovered;
    // Store the number of mine to find
    CEGUI::Editbox* d_counter;
    // Store the number of second elapsed
    CEGUI::Editbox* d_timer;
    // Used to display the result text
    CEGUI::Window* d_result;

    // True if the game is started false otherwise
    bool d_gameStarted;
    // time at the start of the game
    clock_t d_timerStartTime;
    // current value of the timer
    clock_t d_timerValue;
    // Custom window type to force refresh of the timer
    Timer* d_alarm;
};
///////////////////////////////////////////////////////////////////////////
/**************************************************************************

    Main

**************************************************************************/
int main(int /*argc*/, char* /*argv*/[])
{
    // This is a basic start-up for the sample application which is
    // object orientated in nature, so we just need an instance of
    // the CEGuiSample based object and then tell that sample application
    // to run.  All of the samples will use code similar to this in the
    // main/WinMain function.
    MinesweeperSample app;
    return app.run();
}
//////////////////////////////////////////////////////////////////////////
/*************************************************************************

    MinesweeperSample class

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
    Sample specific initialisation goes here.
*************************************************************************/
bool MinesweeperSample::initialiseSample()
{
    using namespace CEGUI;
    // Register Timer Window
    WindowFactoryManager::getSingleton().addFactory( &getTimerFactory() );

    d_gameStarted = false;

    // Get window manager which we wil use for a few jobs here.
    WindowManager& winMgr = WindowManager::getSingleton();

	// Load the scheme to initialse the VanillaSkin which we use in this sample
    SchemeManager::getSingleton().create("VanillaSkin.scheme");
    SchemeManager::getSingleton().create("TaharezLook.scheme");
    System::getSingleton().setDefaultTooltip("TaharezLook/Tooltip");

    // set default mouse image
    System::getSingleton().setDefaultMouseCursor("Vanilla-Images", "MouseArrow");

    // Load font
    FontManager::getSingleton().create("DejaVuSans-10.font");

    // load an image to use as a background
    ImagesetManager::getSingleton().createFromImageFile("BackgroundImage", "GPN-2000-001437.tga");

    // here we will use a StaticImage as the root, then we can use it to place a background image
    Window* background = winMgr.createWindow("Vanilla/StaticImage");

    // set area rectangle
    background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1)));

    // disable frame and standard background
    background->setProperty("FrameEnabled", "false");
    background->setProperty("BackgroundEnabled", "false");

    // set the background image
    background->setProperty("Image", "set:BackgroundImage image:full_image");

    // install this as the root GUI sheet
    System::getSingleton().setGUISheet(background);
    d_alarm = (Timer*)winMgr.createWindow("Timer");
    background->addChildWindow(d_alarm);
    d_alarm->setDelay(0.5); // Tick each 0.5 seconds

    // create the game frame
    Window* frame = winMgr.createWindow("Vanilla/FrameWindow");
    d_alarm->addChildWindow(frame);
    frame->setXPosition(UDim(0.3f, 0.0f));
    frame->setYPosition(UDim(0.15f, 0.0f));
    frame->setWidth(UDim(0.4f, 0.0f)); 
    frame->setHeight(UDim(0.7f, 0.0f)); 
    frame->setText("CEGUI Minesweeper");

    // create the action panel
    Window* action = winMgr.createWindow("DefaultWindow");
    frame->addChildWindow(action);
    action->setXPosition(UDim(0.03f, 0.0f));
    action->setYPosition(UDim(0.10f, 0.0f));
    action->setWidth(UDim(0.94f, 0.0f));
    action->setHeight(UDim(0.1f, 0.0f));
    d_counter = (Editbox*)winMgr.createWindow("Vanilla/Editbox", "mine_counter");
    action->addChildWindow(d_counter);
    d_counter->setText("0");
    d_counter->setTooltipText("Number of mine");
    d_counter->setReadOnly(true);
    d_counter->setXPosition(UDim(0.0f, 0.0f));
    d_counter->setYPosition(UDim(0.0f, 0.0f));
    d_counter->setWidth(UDim(0.3f, 0.0f));
    d_counter->setHeight(UDim(1.0f, 0.0f));

    Window* newGame = winMgr.createWindow("Vanilla/Button", "new_game");
    action->addChildWindow(newGame);
    newGame->setText("Start");
    newGame->setTooltipText("Start a new game");
    newGame->setXPosition(UDim(0.35f, 0.0f));
    newGame->setYPosition(UDim(0.0f, 0.0f));
    newGame->setWidth(UDim(0.3f, 0.0f));
    newGame->setHeight(UDim(1.0f, 0.0f));
    newGame->subscribeEvent(PushButton::EventClicked,  Event::Subscriber(&MinesweeperSample::handleGameStartClicked, this));

    d_timer = (Editbox*)winMgr.createWindow("Vanilla/Editbox", "timer");
    action->addChildWindow(d_timer);
    d_timer->setText("0");
    d_timer->setTooltipText("Time elapsed");
    d_timer->setReadOnly(true);
    d_timer->setXPosition(UDim(0.7f, 0.0f));
    d_timer->setYPosition(UDim(0.0f, 0.0f));
    d_timer->setWidth(UDim(0.3f, 0.0f));
    d_timer->setHeight(UDim(1.0f, 0.0f));
    d_alarm->subscribeEvent(Timer::EventTimerAlarm, Event::Subscriber(&MinesweeperSample::handleUpdateTimer, this));

    // Board button grid
    Window* grid = winMgr.createWindow("DefaultWindow");
    frame->addChildWindow(grid);
    grid->setXPosition(UDim(0.03f, 0.0f));
    grid->setYPosition(UDim(0.23f, 0.0f));
    grid->setWidth(    UDim(0.94f, 0.0f));
    grid->setHeight(   UDim(0.74f, 0.0f));
    const float d_inc = 1.0f / MinesweeperSize; 
    for(size_t i = 0 ; i < MinesweeperSize ; ++i)
    {
        // create a container for each row
        Window* row = winMgr.createWindow("DefaultWindow");
        row->setArea(URect(UDim(0,0), UDim(d_inc * i, 0),
            UDim(1,0), UDim(d_inc * (i + 1), 0)));
        grid->addChildWindow(row);
        for(size_t j = 0 ; j < MinesweeperSize ; ++j)
        {
            // Initialize buttons coordinate
            d_buttonsMapping[i][j].d_col = j;
            d_buttonsMapping[i][j].d_row = i;
            d_buttons[i][j] = (PushButton*)winMgr.createWindow("Vanilla/Button");
            row->addChildWindow(d_buttons[i][j]);
            d_buttons[i][j]->setArea(URect(UDim(d_inc * j, 0), UDim(0,0),
                                 UDim(d_inc * (j + 1), 0), UDim(1,0)));
            d_buttons[i][j]->setEnabled(false);
            // Associate user data
            d_buttons[i][j]->setUserData(&(d_buttonsMapping[i][j]));
            d_buttons[i][j]->setID(0);
            // Connect event handlers
            d_buttons[i][j]->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&MinesweeperSample::handleMineButtonClicked, this));
            d_buttons[i][j]->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&MinesweeperSample::handleMineButtonDown, this));
        }
    }
    d_result = winMgr.createWindow("Vanilla/StaticText");
    grid->addChildWindow(d_result);
    d_result->setXPosition(UDim(0.0, 0.0));
    d_result->setYPosition(UDim(0.0, 0.0));
    d_result->setWidth(UDim(1.0, 0.0));
    d_result->setHeight(UDim(1.0, 0.0));
    d_result->setAlwaysOnTop(true);
    d_result->setProperty("HorzFormatting", "HorzCentred");
    d_result->setVisible(false);
    d_result->setAlpha(0.67f);
    // activate the background window
    background->activate();
    // success!
    return true;
}


/*************************************************************************
    Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void MinesweeperSample::cleanupSample()
{
    //delete d_console;
}
/*************************************************************************
    Handle new game started event
*************************************************************************/
bool MinesweeperSample::handleGameStartClicked(const CEGUI::EventArgs&)
{
    d_result->setVisible(false);
    boardReset();
    boardPositionMines();
    for (size_t i = 0 ; i < MinesweeperSize ; ++i)
    {
        for(size_t j = 0 ; j < MinesweeperSize ; ++j)
        {
            d_buttons[i][j]->setProperty("DisabledTextColour", "FF000000");
            d_buttons[i][j]->setText("");
            d_buttons[i][j]->setEnabled(true);
        }
    }
    d_counter->setText(CEGUI::PropertyHelper::uintToString(MineCount));
    // Handle timer
    d_timerStartTime = ::clock();
    d_timerValue = 0;
    d_timer->setText("0");
    d_gameStarted = true;
    d_alarm->start();
    return true;
}
/************************************************************************
    Handle click on a mine button
************************************************************************/
bool MinesweeperSample::handleMineButtonClicked(const CEGUI::EventArgs& event)
{
    const CEGUI::WindowEventArgs* evt = static_cast<const CEGUI::WindowEventArgs*>(&event);
    CEGUI::PushButton* button = static_cast<CEGUI::PushButton*>(evt->window);
    Location* buttonLoc = static_cast<Location*>(button->getUserData());
    if (button->getID() > 0)
    {
        // dont touch flagged buttons
        return true;
    }
    if (boardDiscover(*buttonLoc))
    {
        // We did not find a mine
        button->setText(CEGUI::PropertyHelper::uintToString(d_board[buttonLoc->d_row][buttonLoc->d_col]));
        if (isGameWin())
            gameEnd(true);
    }
    else
    {
        for(size_t i = 0 ; i < MinesweeperSize ; ++i)
        {
            for (size_t j = 0 ;  j < MinesweeperSize ; ++j)
            {
                if (! d_buttons[i][j]->isDisabled())
                {
                    if (d_board[i][j] > 8)
                    {
                        d_buttons[i][j]->setText("B");
                        d_buttons[i][j]->setProperty("DisabledTextColour", "FFFF1010");
                    }
                    else
                    {
                        d_buttons[i][j]->setText(CEGUI::PropertyHelper::uintToString(d_board[i][j]));
                    }
                }
                d_buttons[i][j]->setEnabled(false);
            }
        }
        gameEnd(false);
    }
    return true;
}
/************************************************************************
    Handle click on a mine button (any mouse button)
************************************************************************/
bool MinesweeperSample::handleMineButtonDown(const CEGUI::EventArgs& event)
{
    const CEGUI::MouseEventArgs& me = static_cast<const CEGUI::MouseEventArgs&>(event);
    if (me.button == CEGUI::RightButton)
    {
        CEGUI::Window* button = me.window;
        if (!button->isDisabled())
        {
            if (button->getID() == 0)
            {
                button->setID(1);
                button->setText("F");
            }
            else
            {
                button->setID(0);
                button->setText("");
            }
            return true;
        }
    }
    return false;
}
/***********************************************************************
    Handle timer refresh
***********************************************************************/
bool MinesweeperSample::handleUpdateTimer(const CEGUI::EventArgs&)
{
    if (d_gameStarted)
    {
        clock_t time = ::clock();
        time -= d_timerStartTime;
        if (time != d_timerValue)
        {
            d_timer->setText(CEGUI::PropertyHelper::uintToString(time /  CLOCKS_PER_SEC));
            d_timerValue = time;
        }
    }
    return true;
}
/************************************************************************
    Create the board
************************************************************************/
void MinesweeperSample::boardReset()
{
    d_boardCellDiscovered = 0;
    for(size_t i = 0 ; i < MinesweeperSize ; ++i)
    {
        for(size_t j = 0 ; j < MinesweeperSize ; ++j)
        {
            d_board[i][j] = 0;
        }
    }
}
/************************************************************************
    Position mine on the board
************************************************************************/
void MinesweeperSample::boardPositionMines()
{
    size_t x = 0 ;
    size_t y = 0 ;
    ::srand(::clock());
    for(size_t i = 0 ; i < MineCount ; ++i)
    {
        do
        {
            x = (size_t) ((float)MinesweeperSize * (::rand() / (RAND_MAX + 1.0)));
            y = (size_t) ((float)MinesweeperSize * (::rand() / (RAND_MAX + 1.0)));
        }
        while(d_board[x][y] > 8);

        d_board[x][y] += 10;
        if (x > 0)
        {
            if (y > 0)
               ++ d_board[x - 1][y - 1];

            ++ d_board[x - 1][y    ];

            if (y < MinesweeperSize - 1)
                ++ d_board[x - 1][y + 1];
        }

        if (y > 0)
            ++ d_board[x    ][y - 1];

        if (y < MinesweeperSize - 1)
            ++ d_board[x    ][y + 1];

        if (x < MinesweeperSize - 1)
        {
            if (y > 0)
                ++ d_board[x + 1][y - 1];

            ++ d_board[x + 1][y    ];

            if (y < MinesweeperSize - 1)
                ++ d_board[x + 1][y + 1];
        }
    }
}
/************************************************************************
    Check wether the game is won or not
************************************************************************/
bool MinesweeperSample::isGameWin()
{
    return d_boardCellDiscovered + MineCount == MinesweeperSize * MinesweeperSize;
}


void MinesweeperSample::gameEnd(bool victory)
{
    d_gameStarted = false;
    d_alarm->stop();
    CEGUI::String message;
    if (victory)
    {
        message = CEGUI::String((CEGUI::utf8*)"You win");
    }
    else
    {
        message = CEGUI::String((CEGUI::utf8*)"You lose");
    }
    // Display a message to the user
    d_result->setText(message);
    d_result->setVisible(true);
}

bool MinesweeperSample::boardDiscover(const Location& loc)
{
    CEGUI::PushButton* btn = d_buttons[loc.d_row][loc.d_col];
    if (btn->isDisabled() || btn->getID() > 0)
        return true;

    if (d_board[loc.d_row][loc.d_col] > 8)
        return false;
    d_buttons[loc.d_row][loc.d_col]->setText(CEGUI::PropertyHelper::uintToString(d_board[loc.d_row][loc.d_col]));
    d_buttons[loc.d_row][loc.d_col]->setEnabled(false);
    ++d_boardCellDiscovered;
    // Discover surrounding case
    if (d_board[loc.d_row][loc.d_col] == 0)
    {
        Location l;
        if (loc.d_row > 0)
        {
            l.d_row = loc.d_row - 1;
            if ( loc.d_col > 0)
            {
                l.d_col = loc.d_col - 1;
                boardDiscover(l);
            }
            l.d_col = loc.d_col;
            boardDiscover(l);
            if ( loc.d_col < MinesweeperSize - 1)
            {
                l.d_col = loc.d_col + 1;
                boardDiscover(l);
            }
        }
        l.d_row = loc.d_row;
        if ( loc.d_col > 0)
        {
            l.d_col = loc.d_col - 1;
            boardDiscover(l);
        }
        if ( loc.d_col < MinesweeperSize  - 1)
        {
            l.d_col = loc.d_col + 1;
            boardDiscover(l);
        }
        if (loc.d_row < MinesweeperSize - 1)
        {
            l.d_row = loc.d_row + 1;
            if ( loc.d_col > 0)
            {
                l.d_col = loc.d_col - 1;
                boardDiscover(l);
            }
            l.d_col = loc.d_col;
            boardDiscover(l);
            if ( loc.d_col < MinesweeperSize - 1)
            {
                l.d_col = loc.d_col + 1;
                boardDiscover(l);
            }
        }
    }
    return true;
}