-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYAPmap.py
executable file
·467 lines (395 loc) · 14.8 KB
/
YAPmap.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
This is a fibble attempt to make a mapping program which is
supposed to be fast and easy to use. One feature I try to
implement here, is randomness. I want the mountains drawen to be
a little different from one - another.
"""
import sys,os
from PyQt4 import QtGui, QtCore
from tile import *
from random import random
class MainGui(QtGui.QWidget):
def __init__(self):
#Setting some important constant.
super(MainGui,self).__init__()
# To handle keyboard keys, I use this flag
self.keepFocus = True
# The starting and ending of the grid
self.endX=25
self.endY=25
self.startX=25
self.startY=15
self.count = 0
self.fams = []
self.names = []
self.curFam = ''
self.radiuses = self.makeRadiuses() # A facntion to create a dict with radiuses as key and i,j indecies as vales
self.loadTilesNames() #Load the tile names and families from hard drive
self.tiles = dict() #Store the tiles
self.selectedTiles=[] #Store the selected tiles
self.topLeft=[0,0] #the i and j indecies of the top left
#corner of the grid displayed
self.mousePressed=False
self.setColors()
self.initUI()
def loadTilesNames(self):
self.tileDB = loadTiles()
self.fams = []
for fam in self.tileDB:
self.fams.append(fam)
self.fams = sorted (self.fams)
def setColors(self):
#Setting colors for future use
self.blue=QtGui.QColor(0,0,255,255)
self.black=QtGui.QColor(0,0,0,255)
self.selBlue=QtGui.QColor(0,0,255,10)
self.trans=QtGui.QColor(0,0,0,0)
def initUI(self):
# Setting the window
self.setGeometry(10,10,1000,600)
self.setWindowTitle('YAPmap.py')
self.setContentsMargins(0,0,0,0)
self.layout = QtGui.QVBoxLayout(self)
self.makeButtons()
self.show()
def makeButtons(self):
#The tile family combo box
self.tileCombo1 = QtGui.QComboBox(self)
for fam in self.fams:
self.tileCombo1.addItem(fam)
self.tileCombo1.move(self.endX-100,self.endY)
#The tile type combo box
self.tileCombo1.resize(10,20)
self.tileCombo2 = QtGui.QComboBox(self)
self.layout.addWidget(self.tileCombo1)
self.layout.addWidget(self.tileCombo2)
self.execButton = QtGui.QPushButton('Do It',self)
self.execButton.clicked.connect(self.buttonDoIt)
self.layout.addWidget(self.execButton)
def buttonDoIt(self):
#For now, this will only generate non-random mountains.
fam = self.tileCombo1.currentText()
tText = self.tileCombo2.currentText()
tileData = self.tileDB[fam][tText]
for sel in self.selectedTiles:
self.tiles[sel].write(tileData,tText)
self.surroundTiles()
self.update()
self.selectedTiles = []
def keyPressEvent(self,event):
super(MainGui,self).keyPressEvent(event)
if (event.key() == QtCore.Qt.Key_Left):
self.topLeft[0] -= 1
self.update()
if (event.key() == QtCore.Qt.Key_Right):
self.topLeft[0] += 1
self.update()
if (event.key() == QtCore.Qt.Key_Up):
self.topLeft[1] -= 1
self.update()
if (event.key() == QtCore.Qt.Key_Down):
self.topLeft[1] += 1
self.update()
def moveButtons(self):
#finding the size of the buttons so they won't
# escape the screen
width = self.frameSize().width()
xsize = width - self.endX - 30
#updating the buttons
self.tileCombo1.move(self.endX+10,50)
self.tileCombo1.resize(xsize,30)
self.tileCombo2.move(self.endX+10,85)
self.tileCombo2.resize(xsize,30)
self.execButton.move(self.endX+10,130)
self.execButton.resize(xsize,30)
def updateTiles(self):
#The tiles family
fam = self.tileCombo1.currentText()
# Erasing the old names
if self.curFam == fam:
# Nothing to do
return
# clear the list
while self.tileCombo2.count() > 0:
self.tileCombo2.removeItem(0)
self.curFam = fam[:]
names = self.tileDB[self.curFam]
self.names = []
for name in names:
self.names.append(name)
self.tileCombo2.addItems(self.names)
def paintEvent(self,e):
self.count += 1
# print (self.count)
qp = QtGui.QPainter()
qp.begin(self)
self.draw(qp)
self.markSelected(qp)
qp.end()
#Updating buttons
self.updateTiles()
self.moveButtons()
if self.keepFocus:
self.setFocus()
else:
self.keepFocus = True
def markSelected(self,qp):
#marking selections
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
qp.setBrush(self.selBlue)
pen.setColor(self.trans)
qp.setPen(pen)
for sel in self.selectedTiles:
x = (sel[0] - self.topLeft[0])*50 + self.startX
y = (sel[1] - self.topLeft[1])*50 + self.startY
qp.drawRect(x,y,50,50)
def draw(self,qp):
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
width= self.frameSize().width()
height = self.frameSize().height()
self.maxI = (width - 150)/50 - 1
self.maxJ = (height - 100)/50 - 1
#Drawing the grid
pen.setStyle(QtCore.Qt.DotLine)
pen.setColor(self.black)
qp.setPen(pen)
x = self.startX
while x <= width -150:
i = int((x-self.startX)/50) + self.topLeft[0]
y = self.startY
while y <= height - 100:
j = int((y-self.startY)/50) + self.topLeft[1]
qp.drawLine(x,y,x+50,y)
qp.drawLine(x,y,x,y+50)
if not (i,j) in self.tiles:
self.tiles[(i,j)] = Tile()
elif len(self.tiles[(i,j)].content) > 0:
self.tiles[(i,j)].paint(qp,x,y)
qp.setPen(pen) #The tile.paint function generate its own pen
y += 50
self.endY = y
x += 50
self.endX=x
#Closing line for the grid
qp.drawLine(self.endX,self.startY,self.endX,self.endY)
qp.drawLine(self.startX,self.endY,self.endX,self.endY)
def immediateSurround(self,ij):
# Get all the tiles arround a certain tile
out = []
for r in range (2,0,-1):
vals = self.radiuses[r]
for v in vals:
out.append((v[0] + ij[0], v[1] + ij[1]))
return out
def getSurrounding(self,sel):
out = dict()
# A function to get the surrounding tiles about a single one
# The surrounding is defined as any tiles at a distance of
# 3 tiles about the center one
for r in range (18,0,-1):
if not r in self.radiuses: continue
vals = self.radiuses[r]
for v in vals:
i,j= v[0] + sel[0], v[1] + sel[1]
ij = (i,j)
#Remove any invalid choices
if i < 0 or j < 0: continue
if i > self.maxI or j > self.maxJ:
continue
if ij in self.tiles and len (self.tiles[ij].types) > 0: continue
out[ij]=r
return out
def decideSurround(self,cands, tText):
for r in cands:
for ij in cands[r]:
if ij in self.selectedTiles:
continue
iSur = self.immediateSurround(ij)
score = dict()
for sur in iSur:
if not sur in self.tiles: continue
types = self.tiles[sur].types
for t in types:
if t in score:
score[t] += 1
else:
score[t] = 1
toPut = self.placeSurround(tText,score,r)
if not toPut: continue
else:
tileData = self.tileDB['Mountains'][toPut]
self.tiles[ij].write(tileData,toPut)
def placeSurround(self,tText,score,r):
if (tText == 'easy mountains'):
prob = 0.3/r
if 'easy mountains' in score:
prob += 0.1*score['easy mountains']/r
elif 'hills' in score:
prob += 0.025/r
rval =random()
if prob > rval:
return 'hills'
else:
return False
return False
def surroundTiles(self):
''' A function to try and fill tiles which sourund
the selected tiles '''
tText = self.tileCombo2.currentText()
#####
# Add a part that determine if the drawn tile should generate
# surrounding
#####
candsByIJ = dict()
for sel in self.selectedTiles:
# Getting the surrounding
neighbors = self.getSurrounding(sel)
for ij in neighbors:
# Placing each tile once in the cands dict
# Giving the shortest possible distance
r = neighbors[ij]
if not ij in candsByIJ:
candsByIJ[ij] = r
elif candsByIJ[ij] > r:
candsByIJ[ij] = r
#sort the cands by distance
cands = dict()
for ij in candsByIJ:
r = candsByIJ[ij]
if not r in cands:
cands[r] = []
cands[r].append(ij)
self.decideSurround(cands,tText)
def mouseMoveEvent(self,e):
super(MainGui, self).mouseMoveEvent(e)
self.markTile(e)
def eventFilter(self,source,event):
""" This class is used for special events which I couldn't
handle otherwize Most events return False to help debugin
"""
if event.type() == QtCore.QEvent.Paint:
return False
elif event.type() == QtCore.QEvent.UpdateRequest:
return False
elif event.type() == QtCore.QEvent.Polish:
return False
elif event.type() == QtCore.QEvent.PolishRequest:
return False
elif event.type() == QtCore.QEvent.LayoutRequest:
return False
elif event.type() == QtCore.QEvent.HideToParent:
return False
elif event.type() == QtCore.QEvent.Hide:
return False
elif event.type() == QtCore.QEvent.FocusOut:
return False
elif event.type() == QtCore.QEvent.FocusIn:
return False
elif event.type() == QtCore.QEvent.MouseMove:
return False
elif event.type() == QtCore.QEvent.WindowActivate:
return False
elif event.type() == QtCore.QEvent.ActivationChange:
return False
elif event.type() == QtCore.QEvent.SockAct:
return False
elif event.type() == QtCore.QEvent.Move:
return False
elif event.type() == QtCore.QEvent.Resize:
return False
elif event.type() == QtCore.QEvent.Enter:
return False
elif event.type() == QtCore.QEvent.HoverMove:
if self.execButton.underMouse():
self.execButton.setFocus()
self.keepFocus=False
else :
self.keepFocus=True
return False
def markTile(self,e):
x=e.pos().x()
y=e.pos().y()
if x >= self.endX: return
if y >= self.endY: return
if x <= self.startX: return
if y <= self.startY: return
i = int((x-self.startX)/50) + self.topLeft[0]
j = int((y-self.startY)/50) + self.topLeft[0]
if not (i,j) in self.selectedTiles:
self.selectedTiles.append((i,j))
self.lastI=i
self.lastJ=j
self.update()
def makeRadiuses(self):
radiuses = dict()
for i in range (-3,4):
for j in range (-3,4):
r = i**2 + j**2
if not r in radiuses:
radiuses[r] = []
radiuses[r].append((i,j))
return radiuses
def loadTiles():
''' A function called when the program start to load the
tiles directions
the tile files directory hirrarchy is
<fam>/<name>.tile
Each .tile file may holds several entries in the following format
tile:\n
<x>,<y>\t<red>\t<green>\t<blue>\t<alpha>\n
The "tile:" line holds only that this line tells the program to start a new tile
<x> and <y> are the x,y coordinates inside the tile (starting from top lef) to color
<red>,<green>,and, <blue> are the red, green, and blue values of the color.
Finally, <alpha> is the transperacy level (0 is compltely transparent).
All valus are integer and the angular brackets are not needed in the file.
Example line:
26, 47, 0, 0, 127, 255
'''
tileDB = dict()
tilesPath = './Tiles'
fams = os.walk(tilesPath).__next__()[1]
for fam in fams:
tileDB[fam] = dict()
path = tilesPath + '/' + fam
names = os.walk(path).__next__()[2]
for n in names:
parts = n.split('.')
if not len(parts) == 2: continue
if not parts[1] == 'tile': continue
tileDB[fam][parts[0]] = []
file = open(path + '/'+n).readlines()[:]
tile = []
for line in file:
if 'tile:' in line:
if len(tile) == 0: continue
tileDB[fam][parts[0]].append(tile)
tile = []
continue
line = line.split()
xyindex = line[0].split(',')
xyindex = (int(xyindex[0]),int(xyindex[1]))
tileLine = [xyindex,int(line[1]),int(line[2]),int(line[3]),int(line[4])]
tile.append(tileLine)
if not len(tile) == 0:
tileDB[fam][parts[0]].append(tile)
'''removing empty entries'''
out = dict()
for fam in tileDB:
if len(tileDB[fam]) == 0:
continue
out[fam] = dict()
for tile in tileDB[fam]:
if len(tileDB[fam][tile]) == 0:
continue
out[fam][tile] = tileDB[fam][tile][:]
return out
def main():
app = QtGui.QApplication(sys.argv)
window=MainGui()
app.installEventFilter(window)
sys.exit(app.exec_())
sys.exit(app.exec())
if __name__ == '__main__':
main()