]> git.saurik.com Git - wxWidgets.git/blob - demos/bombs/game.cpp
48bd783d794d485c5a2caeeed7644688b1d9b794
[wxWidgets.git] / demos / bombs / game.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: bombs1.cpp
3 // Purpose: Implementation of the class BombsGame
4 // Author: P. Foggia 1996
5 // Modified by: Wlodzimierz Skiba (ABX) since 2003
6 // Created: 1996
7 // Copyright: (c) 1996 P. Foggia
8 // Licence: wxWindows licence
9 ///////////////////////////////////////////////////////////////////////////////
10
11 #include "wx/wxprec.h"
12
13 #ifdef __BORLANDC__
14 #pragma hdrstop
15 #endif
16
17 #ifndef WX_PRECOMP
18 # include "wx/wx.h"
19 #endif
20
21 #include "game.h"
22 #include <stdlib.h>
23 #include <limits.h>
24
25 #define PROB 0.2
26
27 #ifndef RAND_MAX
28 # define RAND_MAX INT_MAX
29 #endif
30
31
32 BombsGame::~BombsGame()
33 {
34 if (m_field)
35 {
36 delete[] m_field;
37 }
38 }
39
40 // Initialize the play field. Returns false on failure
41 bool BombsGame::Init(int aWidth, int aHeight, bool easyCorner)
42 {
43 m_gridFocusX = m_gridFocusY = -1;
44
45 int x, y;
46 int xx, yy;
47
48 if (m_field)
49 {
50 delete[] m_field;
51 }
52
53 m_field = new short[aWidth*aHeight];
54 if (!m_field)
55 {
56 m_width = m_height = 0;
57 return false;
58 }
59
60 m_width = aWidth;
61 m_height = aHeight;
62
63 for(x=0; x<m_width; x++)
64 {
65 for(y=0; y<m_height; y++)
66 {
67 m_field[x+y*m_width] = ((float)rand()/RAND_MAX <PROB)
68 ? BG_HIDDEN | BG_BOMB
69 : BG_HIDDEN;
70 }
71 }
72
73 /* Force (0,0) not to have a bomb for those that don't want to have
74 to guess on the first move. Better would be to for the MS rule that
75 whatever is picked first isn't a bomb.
76 */
77 if(easyCorner)
78 {
79 m_field[0] = BG_HIDDEN;
80 }
81
82 m_numBombCells = 0;
83 for(x=0; x<m_width; x++)
84 for(y=0; y<m_height; y++)
85 if (m_field[x+y*m_width] & BG_BOMB)
86 {
87 m_numBombCells++;
88
89 for(xx=x-1; xx<=x+1; xx++)
90 if (xx>=0 && xx<m_width)
91 for(yy=y-1; yy<=y+1; yy++)
92 if (yy>=0 && yy<m_height && (yy!=y || xx!=x))
93 m_field[xx+yy*m_width]++;
94 }
95
96 m_numRemainingCells = m_height*m_width-m_numBombCells;
97 m_numMarkedCells = 0;
98
99 return true;
100 }
101
102 void BombsGame::Mark(int x, int y)
103 {
104 m_field[x+y*m_width] ^= BG_MARKED;
105 if (IsMarked(x, y))
106 m_numMarkedCells++;
107 else
108 m_numMarkedCells--;
109 }
110
111 void BombsGame::Unhide(int x, int y, bool b_selected)
112 {
113 if (!IsHidden(x,y))
114 {
115 return;
116 }
117
118 if (b_selected)
119 m_field[x+y*m_width] |= BG_SELECTED;
120
121 m_field[x+y*m_width] &= ~BG_HIDDEN;
122
123 if (!IsBomb(x,y))
124 {
125 m_numRemainingCells--;
126 }
127 }
128
129
130 void BombsGame::Explode(int x, int y)
131 {
132 m_field[x+y*m_width] |= BG_EXPLODED;
133 }