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
|
# The scripts in this tutorial implement the famous minesweeper game
# STEP 2
class(minesweepermain,widget)
{
constructor()
{
$$->$setCaption("KVIrc's Minesweeper (0.1.0)");
$$->%rows = 10
$$->%cols = 10
$$->%mines = 10
$$->%layout = $new(layout,$this)
for(%i = 0;%i < $$->%rows;%i++)
{
for(%j = 0;%j < $$->%cols;%j++)
{
$$->%label{%i,%j}=$new(label,$this,"%i_%j")
$$->%label{%i,%j}->%row = %i
$$->%label{%i,%j}->%col = %j
$$->%layout->$addWidget($$->%label{%i,%j},%i,%j)
}
}
$$->$newGame()
}
newGame()
{
for(%i = 0;%i < $$->%rows;%i++)
{
for(%j = 0;%j < $$->%cols;%j++)
{
%l = $$->%label{%i,%j}
%l->$setFrameStyle(Raised,WinPanel);
%l->%bIsMine = 0
%l->%numMines = 0
%l->%bIsDiscovered = 0
%l->$setText("")
}
}
# Here we drop the mines around: it is a bit complex problem:
# We want to have a fixed number of mines placed randomly in our grid
#
# So .. for each mine that we have to place...
for(%i = 0;%i < $$->%mines;%i++)
{
# Choose a random position for this mine
%row = $rand($($$->%rows - 1))
%col = $rand($($$->%cols - 1))
# Ensure that we're not placing this mine over an existing one
while($$->%label{%row,%col}->%bIsMine != 0)
{
# If there was already a mine, then choose the position again
%row = $rand($($$->%rows - 1))
%col = $rand($($$->%cols - 1))
}
# Ok.. this is a mine then
$$->%label{%row,%col}->%bIsMine = 1
# increase the mine count for the adiacent cells: this is again a bit complex thingie
if(%row > 0)
{
# There is a row over our mine: the cells above must have their mine count updated
# The cell just above us
$$->%label{$(%row - 1),%col}->%numMines++
# The cell above on the left (if exists)
if(%col > 0)$$->%label{$(%row - 1),$(%col - 1)}->%numMines++
# The cell above on the right (if exists)
if(%col < ($$->%cols - 1))$$->%label{$(%row - 1),$(%col + 1)}->%numMines++
}
if(%row < ($$->%rows - 1))
{
# There is a row below our mine: the cells below must have their mine count updated
# The cell just below us
$$->%label{$(%row + 1),%col}->%numMines++
# The cell below on the left (if exists)
if(%col > 0)$$->%label{$(%row + 1),$(%col - 1)}->%numMines++
# The cell below on the right (if exists)
if(%col < ($$->%cols - 1))$$->%label{$(%row + 1),$(%col + 1)}->%numMines++
}
# Now the cell on the left side (if exists)
if(%col > 0)$$->%label{%row,$(%col - 1)}->%numMines++
# And on the right side (if exists)
if(%col < ($$->%cols - 1))$$->%label{%row,$(%col + 1)}->%numMines++
}
}
}
%m = $new(minesweepermain)
%m->$show()
|