-
Notifications
You must be signed in to change notification settings - Fork 4
/
blocku.py
1933 lines (1705 loc) · 76.1 KB
/
blocku.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
Main Blocku game logic class
import every thing that the activity needs and run game code
Original creators: Fran Rogers and Ariel Zamparini
Developed by: Kai Ito
"""
import pygame
import random
import os.path
import os
import sys
import string
from itertools import chain
from pygame import QUIT, KEYDOWN, MOUSEBUTTONDOWN, MOUSEBUTTONUP, KEYUP, \
Rect, Color, mouse, event
from pygame.locals import K_0, K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, \
K_BACKSPACE, K_RETURN, K_SPACE, K_ESCAPE, K_LEFT, K_RIGHT, K_UP, K_DOWN, \
K_KP1, K_KP2, K_KP3, K_KP4, K_KP6, K_KP8
try:
import gtk
except ImportError:
print('gtk error')
gtk = None
#see if we can load more than standard BMP
if not pygame.image.get_extended():
raise SystemExit("Sorry, extended image module required")
#game constants
SCREENRECT = Rect(0, 0, 1200, 900)
KEYBOARDMOVESPEED = 10
def load_image(file, alpha=False):
"loads an image, prepares it for play"
file = os.path.join('data', file)
try:
surface = pygame.image.load(file)
except pygame.error:
raise SystemExit('Could not load image "%s" %s' % (file,
pygame.get_error()))
if alpha:
return surface.convert_alpha()
else:
return surface.convert()
def display_box(screen, message, x, y, w, h, size):
"Print a message in a box in the middle of the screen"
font = pygame.font.Font(None, size)
rect = pygame.Rect([x, y, w, h])
#center = screen.get_rect().center
#rect.center = center
pygame.draw.rect(screen, (255, 255, 255), rect, 0)
pygame.draw.rect(screen, (0, 0, 0), rect, 1)
screen.blit(font.render(message, 1, (0, 0, 0)), rect.topleft)
pygame.display.flip()
def ask(screen, question, x, y, w, h, size, numOnly, limit, allow=True):
pygame.font.init()
text = ""
display_box(screen, question + ": " + text, x, y, w, h, size)
while 1:
pygame.time.wait(50)
pyevent = pygame.event.poll()
if not numOnly:
if pyevent.type == QUIT:
sys.exit()
if pyevent.type != KEYDOWN:
continue
if pyevent.key == K_BACKSPACE:
text = text[0:-1]
elif pyevent.key == K_RETURN:
break
elif pyevent.key == K_SPACE and not allow:
continue
elif len(text) < limit:
text += pyevent.unicode.encode("ascii")
else:
if pyevent.type == QUIT:
sys.exit()
if pyevent.type != KEYDOWN:
continue
if pyevent.key == K_BACKSPACE:
text = text[0:-1]
elif pyevent.key == K_RETURN:
break
elif len(text) < 6 and (pyevent.key == K_0 or
pyevent.key == K_1 or
pyevent.key == K_2 or
pyevent.key == K_3 or
pyevent.key == K_4 or
pyevent.key == K_5 or
pyevent.key == K_6 or
pyevent.key == K_7 or
pyevent.key == K_8 or
pyevent.key == K_9):
text += pyevent.unicode.encode("ascii")
display_box(screen, question + ": " + text, x, y, w, h, size)
if text == '':
text = '0'
return text
# num - number of blocks on one side of grid (ex: pass in 3 for a 3x3 grid)
def GenerateAddition(num, answer):
rows = list([] for i in range(num))
blocks = list([] for i in range(num * num))
for i in range(num):
rows[i] = list([] for i in range(num))
# x and y positions of starting point of grid
x = 398
y = 298
# answer to solve for
# populate the list with blocks
#blocks are Block(n,s,e,w,x,y) xy= starting position
for i in range(num):
for k in range(num):
temp = Block(-1, -1, -1, -1, (x + (i * 108)+100),
(y + (k * 108)+50))
rows[i][k] = temp
#blocks[(i * 3) + k] = temp
# Left and right answers
for i in range(num):
for k in range(num):
# set the block's right side answer
rows[i][k].origEast = rows[i][k].east = random.randint(0, answer)
# generate a random num for the block's west answer
if rows[i][k].west == -1:
rows[i][k].origWest = rows[i][k].west = random.randint(
0, answer + 10)
# check the left side answer of the block in the adjacent row
if (i + 1) < num:
rows[i + 1][k].origWest = rows[i + 1][k].west = (
answer - rows[i][k].east)
#rows[i + 1][k].west
#print(rows[3][2])
# Top and bottom answers
for i in range(num):
for k in range(num):
# set top answer if empty
if (rows[i][k].north == -1):
rows[i][k].origNorth = rows[i][k].north = random.randint(
0, answer + 10)
#rows[i][k].north
# get random number for south
rows[i][k].origSouth = rows[i][k].south = random.randint(
0, answer)
# get answer in block below the block we just filled in
if (k + 1) < num:
rows[i][k].origNorth = rows[i][k + 1].north = (
answer - rows[i][k].south)
# get all the blocks into a single list
count = 0
#print(count)
for i in range(num):
for k in range(num):
blocks[count] = rows[i][k]
count += 1
# make sure all the original positions are saved
for block in blocks:
block.origNorth = block.north
block.origSouth = block.south
block.origEast = block.east
block.origWest = block.west
#print(count)
return blocks
# num - number of blocks on one side of grid (ex: pass in 3 for a 3x3 grid)
def GenerateSubtraction(num, answer):
rows = list([] for i in range(num))
blocks = list([] for i in range(num * num))
for i in range(num):
rows[i] = list([] for i in range(num))
# x and y positions of starting point of grid
x = 398
y = 298
# answer to solve for
# populate the list with blocks
#blocks are Block(n,s,e,w,x,y) xy= starting position
for i in range(num):
for k in range(num):
temp = Block(-1, -1, -1, -1, (x + (i * 108)+100),
(y + (k * 108)+50))
rows[i][k] = temp
#blocks[(i * 3) + k] = temp
# Left and right answers
for i in range(num):
for k in range(num):
# set the block's right side answer
rows[i][k].origEast = rows[i][k].east = random.randint(0, answer)
# generate a random num for the block's west answer
if rows[i][k].west == -1:
rows[i][k].origWest = rows[i][k].west = random.randint(
0, answer + 10)
# check the left side answer of the block in the adjacent row
if (i+1) < num:
rows[i+1][k].origWest = rows[i + 1][k].west = (
answer + rows[i][k].east)
#rows[i + 1][k].west
#print(rows[3][2])
# Top and bottom answers
for i in range(num):
for k in range(num):
# set top answer if empty
if (rows[i][k].north == -1):
rows[i][k].origNorth = rows[i][k].north = random.randint(
0, answer + 10)
#rows[i][k].north
# get random number for south
rows[i][k].origSouth = rows[i][k].south = random.randint(0, answer)
# get answer in block below the block we just filled in
if (k+1) < num:
rows[i][k].origNorth = rows[i][k+1].north = (
answer + rows[i][k].south)
# get all the blocks into a single list
count = 0
#print(count)
for i in range(num):
for k in range(num):
blocks[count] = rows[i][k]
count += 1
# make sure all the original positions are saved
for block in blocks:
block.origNorth = block.north
block.origSouth = block.south
block.origEast = block.east
block.origWest = block.west
#print(count)
return blocks
def Solve(blocks):
for block in blocks:
# checks original position
if block.rect.x != (block.origX + 0) or \
block.rect.y != (block.origY + 0):
return "Incomplete"
# checks original rotation
if block.north != block.origNorth or \
block.south != block.origSouth or \
block.east != block.origEast or \
block.west != block.origWest:
return "Incomplete"
return "Solved!"
# puts the blocks in random positions
def Randomize(blocks):
for block in blocks:
block.rect.x = random.randint(200, 900)
block.rect.y = random.randint(200, 700)
# read in a board called testFile.txt
def LoadBoard(nm, directory='boards'):
# File format:
# ---------------
# Number of blocks in board
# X-Pos Y-Pos N S W E
# NSWE = directions
try:
file = open(directory + os.sep + nm + ".txt", "r")
numLines = file.readline()
#print(numLines)
blocks = list([] for i in range(int(numLines)))
# read in each line and split it
for i in range(int(numLines)):
line = file.readline()
args = line.rsplit()
#save file is (x,y,n,e,s,w)
#blocks are Block(n,e,s,w,x,y) xy= starting position
blocks[i] = Block(args[2], args[3], args[4],
args[5], int(args[0]), int(args[1]))
file.close()
except:
return "Can't load board"
return blocks
# Will grab the last line of the file
def LastLine(nm, directory='boards'):
try:
file = open(directory + os.sep + nm + ".txt", 'r')
lines = file.readlines()
file.close()
except:
lines = 'Solve for: X + Y = 42'
val = lines[len(lines)-1]
val = ''.join([c for c in val if c in string.printable])
return val
def GenerateGrid(blocks):
gridPos = list([] for i in range(len(blocks)))
for k in range(len(blocks)):
gridPos[k] = (blocks[k].rect.x - 6, blocks[k].rect.y - 6)
#print(gridPos)
return gridPos
class dummysound:
def play(self):
pass
def load_sound(file):
if not pygame.mixer:
return dummysound()
file = os.path.join('data', file)
try:
sound = pygame.mixer.Sound(file)
return sound
except pygame.error:
print('Warning, unable to load,', file)
return dummysound()
# Dictionary load in for different language strings
def loadDictionary(language):
lang = {}
tempLines = []
tempKey = ''
tempVal = ''
f = open('data' + os.sep + language, 'r')
tempLines = f.readlines()
f.close()
for line in tempLines:
tempKey = line.rsplit('<>')[0]
tempVal = line.rsplit('<>')[1][1:-2]
#tempVal = ''.join([c for c in tempVal if c in '\"'])
lang[tempKey] = tempVal
return lang
# Block class. this is the block with the numbers on it.
# http://www.pygame.org/docs/tut/chimp/chimp.py.html
class Block(pygame.sprite.Sprite):
permImages = []
images = []
north = ''
east = ''
south = ''
west = ''
origNorth = ''
origSouth = ''
origWest = ''
origEast = ''
isLast = 0
isMoving = False
globX = 1
globY = 1
origX = 0
origY = 0
rangeRender = 0
text = ''
def __init__(self, n='', e='', s='', w='', x='', y=''):
pygame.sprite.Sprite.__init__(self)
self.image = self.images[0].copy()
self.rect = self.images[0].copy()
self.blankImage = self.image.copy()
Block.images = self.images[1:]
if len(Block.images) == 0:
Block.images = Block.permImages
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.rect = pygame.Rect(x, y, 96, 96)
#self.update()
#self.rect = pygame.Rect(x,y,96,96)
self.origX = x
self.origY = y
self.font = pygame.font.Font(None, 30)
self.color = Color('black')
self.north = n
self.east = e
self.south = s
self.west = w
self.origNorth = n
self.origEast = e
self.origSouth = s
self.origWest = w
self.update()
def update(self):
#keep the block on the screen
self.rect = self.rect.clamp(SCREENRECT)
self.image = self.blankImage.copy()
self.image.blit(
self.font.render(
str(self.north), 0, self.color), (39, 3))
if self.east < 10:
self.rangeRender = 65
else:
self.rangeRender = 57
self.image.blit(
self.font.render(
str(self.east), 0, self.color), (self.rangeRender, 42))
self.image.blit(
self.font.render(
str(self.south), 0, self.color), (39, 75))
self.image.blit(
self.font.render(
str(self.west), 0, self.color), (5, 42))
def edit(self, n, e, s, w):
#print (str(self.rect.x) + ", " + str(self.rect.y))
self.north = n
self.east = e
self.south = s
self.west = w
self.update()
def setGrabbed(self, sett):
self.isMoving = sett
def isGrabbed(self):
return self.isMoving
def grab(self, pos):
x, y = pos
self.globX = x
self.globY = y
# Remember the offset here is 48 as this will
# center the mouse in our 96 pixel image
self.newPos = self.rect.move((x, y))
self.rect.left = x - 48
self.rect.top = y - 48
def getX(self):
return self.globX
def getY(self):
return self.globY
def rotate(self):
temp = self.north
self.north = self.east
self.east = self.south
self.south = self.west
self.west = temp
class Highlight(pygame.sprite.Sprite):
def __init__(self, x=1300, y=1000):
pygame.sprite.Sprite.__init__(self)
img = load_image('hilite.png', True)
self.image = img
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.rect = pygame.Rect(x, y, 120, 120)
def setpos(self, pos):
x, y = pos
self.globX = x
self.globY = y
# Remember the offset here is 48 as this will
# center the mouse in our 120 pixel image
self.newPos = self.rect.move((x, y))
self.rect.left = x - 12
self.rect.top = y - 12
# The main game class
class Game:
strings = {}
def __init__(self):
# Set up a clock for managing the frame rate.
self.clock = pygame.time.Clock()
self.paused = False
self.strings = loadDictionary('bl_english.txt')
def set_paused(self, paused):
self.paused = paused
# Called to save the state of the game to the Journal.
def write_file(self, file_path):
pass
# Called to load the state of the game from the Journal.
def read_file(self, file_path):
pass
# The main game loop.
def run(self, curMode, rng, dif, sub, name, cas):
pygame.mouse.set_visible(False)
isRan = 0
editMode = False
#print curMode
#self.rangee = rng
#print dif
#pseudo timer
loopCounter = 0
#puzzle counter
numRotateTotal = 0
if pygame.mixer and not pygame.mixer.get_init():
print('Warning, no sound')
pygame.mixer = None
# load a test sound
"""upSound = load_sound('up.ogg')
downSound = load_sound('down.ogg')"""
winstyle = 0 # |FULLSCREEN
bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
squares = load_image('square.png')
global background
background = load_image('background.png')
background = background.convert()
iconImg = load_image('blocku.png')
self.screen = pygame.display.set_mode((1200, 900))
# spriteBatch = pygame.sprite.RenderUpdates()
# Generate random number between 20 and 99 for the answer to equal
if rng == 1:
answer = random.randint(15, 40)
Block.rangeRender = 65
elif rng == 2:
answer = random.randint(30, 99)
Block.rangeRender = 65
elif rng == 3:
answer = random.randint(100, 999)
Block.rangeRender = 57
# load images here
# for gifs img = load_image('filename.gif')
# for bmps img = pygame.image.load('filename.bmp')
# but our function handles that for us
# a note for graphics blit means copy pixels from screen.blit()
# Check solution text
# cursor = mouseUpdate()
# spriteBatch.add(cursor)
# the test will need rects and positions i suggest
# make some kind of default
# this information can be held by each block as
# they are created but is made here
# load images to pipe to the sprite classes
# Block.images = allBlockImages
tempImages = [load_image('c1.png'),
load_image('c2.png'),
load_image('c3.png'),
load_image('c4.png'),
load_image('c5.png'),
load_image('c6.png'),
load_image('c7.png'),
load_image('c8.png'),
load_image('c9.png')]
Block.images = tempImages
Block.permImages = tempImages
gridImg1 = squares
#Board generation depending on mode selected
if not curMode == 3:
if sub == 0:
if dif == 1:
allBlocks = GenerateAddition(3, answer)
elif dif == 2:
allBlocks = GenerateAddition(4, answer)
elif dif == 3:
allBlocks = GenerateAddition(3, answer)
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
elif dif == 4:
allBlocks = GenerateAddition(4, answer)
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
else:
if dif == 1:
allBlocks = GenerateSubtraction(3, answer)
elif dif == 2:
allBlocks = GenerateSubtraction(4, answer)
elif dif == 3:
allBlocks = GenerateSubtraction(3, answer)
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
elif dif == 4:
allBlocks = GenerateSubtraction(4, answer)
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
else:
if name == 'boardMaker':
editMode = True
allBlocks = LoadBoard(name, 'data')
else:
allBlocks = LoadBoard(name)
gridpos = GenerateGrid(allBlocks)
if not editMode:
if curMode == 1 or curMode == 3:
Randomize(allBlocks)
if curMode == 3 and dif == 2:
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
elif curMode == 2:
for block in allBlocks:
for i in range(0, random.randint(1, 6)):
block.rotate()
numRotateTotal += 1
cursor = mouseUpdate(mouse.get_pos())
#in game text
if pygame.font:
objective = Text('', 253, 174, 'black', 46)
if sub == 0:
if curMode == 3:
if name == 'boardMaker':
objective.change(LastLine(name, 'data'))
else:
objective.change(LastLine(name))
elif curMode == 1 and dif < 3:
objective.change(
self.strings['arrangeAddition'] + str(answer))
elif curMode == 1 and dif > 2:
objective.change(
self.strings['arrangeAdditionRotate'] + str(answer))
elif curMode == 2:
objective.change(
self.strings['rotateAddition'] + str(answer))
else:
if curMode == 3:
if name == 'boardMaker':
objective.change(LastLine(name, 'data'))
else:
objective.change(LastLine(name))
elif curMode == 1 and dif < 3:
objective.change(
self.strings['arrangeSubtraction'] + str(answer))
elif curMode == 1 and dif > 2:
objective.change(
self.strings['arrangeSubtractionRotate'] + str(answer))
elif curMode == 2:
objective.change(
self.strings['rotateSubtraction'] + str(answer))
#Text for when solved
solved = Text('', 400, 240, 'red', 142)
#Text to display time elapsed
timeText = Text('', 375, 25, 'black', 89)
#Text for puzzle mode goal
puzGoal = Text('', 20, 242, 'black', 42)
font = pygame.font.Font(None, 42)
toMenu = font.render(
self.strings['mainMenu'], 1, (0, 0, 0))
if curMode == 2:
goal = font.render(
self.strings['tryToBeat'], 1, (0, 0, 0))
elif curMode == 1 or curMode == 3:
goal = font.render(
self.strings['recentTime'], 1, (0, 0, 0))
if not editMode:
background.blit(goal, [20, 200])
check = font.render(
self.strings['checkAnswer'], 1, (0, 0, 0))
else:
check = font.render(
self.strings['saveBoard'], 1, (0, 0, 0))
background.blit(toMenu, [30, 840])
background.blit(check, [978, 840])
pygame.display.flip()
highScores = []
#high scores
if not editMode:
if not curMode == 2:
if curMode == 1:
ff = open("scores" + os.sep + "timeRecent.txt", 'r')
else:
ff = open("scores" + os.sep + name + "Scores.txt", 'r')
for i in range(5):
highScores.append(ff.readline())
for i in range(len(highScores)):
highScores[i] = highScores[i].rstrip('\n')
highScores[i] = highScores[i][:-1]
rec = font.render(highScores[i], 1, (0, 0, 0))
background.blit(rec, [25, 240 + (40 * i)])
ff.close()
elif curMode == 2:
puzGoal.change(str(numRotateTotal) + self.strings['rotations'])
#highlight for visual cue
hi = Highlight()
#actually displays everything
allsprites = pygame.sprite.LayeredUpdates()
for block in allBlocks:
allsprites.add(block)
allsprites.add(hi)
allsprites.add((timeText, objective, puzGoal))
allsprites.add(solved)
allsprites.add(cursor)
#Blit a grid piece to each block before they get scrambled
for i in range(len(gridpos)):
background.blit(gridImg1, gridpos[i])
screen.blit(background, (0, 0))
pygame.display.flip()
#to set the icon up and to decorate the game window
icon = pygame.transform.scale(iconImg, (32, 32))
pygame.display.set_icon(icon)
pygame.display.set_caption('Blocku')
# it is important to note that like xna the origin is 0,0
# the top left of the current window
# print is trace in console
# and increases as you go down and to the right
# pygame has a collision detector under
#pygame.sprite.spritecollide(group,group,dokill)
# this will return a list of colliders,
#dokill will remove the colliders from the parrent group if true
mousePossible = True
completed = False
timer = 0
counter = 0
keyDown = False
mins = 0
numRotate = 0
nname = 'null'
#if goign against time, set up time limits
if cas == 0:
if dif == 1:
mins = 5
timer = 59
elif dif == 2:
mins = 11
timer = 59
elif dif == 3:
mins = 17
timer = 59
elif dif == 4:
mins = 23
timer = 59
origMin = mins
origSec = timer
#for block editing
n = 0
east = 0
s = 0
w = 0
failed = False
#for block saving
numBlocks = 0
blocksToWrite = []
blocksToWrite.append(["0"])
while 1:
#Ran out of time
if mins == 0 and timer == 0 and cas == 0:
completed = True
failed = True
loopCounter += 1
#timer code
#for the sake of a leading zero
emptyMin = ''
emptySec = ''
curTime = ''
if mins < 10:
emptyMin = '0'
if timer < 10:
emptySec = '0'
if not editMode:
if not curMode == 2 and cas == 1:
if not completed:
counter += 1
if counter > 30:
timer += 1
counter = 0
if timer > 59:
mins += 1
timer = 0
curTime = emptyMin + str(mins) + ':' + \
emptySec + str(timer)
timeText.change(self.strings['timeElapsed'] + curTime)
elif not curMode == 2 and cas == 0:
#dif 1 2 3 4
if not completed:
counter += 1
if counter > 30:
timer -= 1
counter = 0
if timer < 0:
mins -= 1
timer = 59
curTime = emptyMin + str(mins) + ':' + \
emptySec + str(timer)
if not completed:
timeText.change(
self.strings['timeRemaining'] + curTime)
elif curMode == 2:
timeText.change(
self.strings['numOfRotations'] + str(numRotate))
#clear the incomplete text after a moment
if loopCounter > 50:
loopCounter = 0
if not completed:
solved.change('')
#pygame.display.update(allBlocks)
#pygame.display.flip()
# Pump GTK messages.
while gtk and gtk.events_pending():
gtk.main_iteration()
keystate = pygame.key.get_pressed()
# Pump PyGame messages.
#x is 240
for e in event.get():
#hit escape to quit
if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
pygame.quit()
elif e.type == pygame.VIDEORESIZE:
pygame.display.set_mode(e.size, pygame.RESIZABLE)
#on click of the check answer button
if e.type == MOUSEBUTTONDOWN:
event.set_grab(1)
mousePossible = True
if not editMode:
if not completed:
#check answer button
if 1200 > cursor.rect.x > 954 and \
900 > cursor.rect.y > 809:
result = Solve(allBlocks)
if result == 'Solved!':
solved.change(self.strings['win'])
completed = True
else:
loopCounter = 0
solved.change(
self.strings['incomplete'])
#save custom created board
else:
#blocksToWrite.append["0"]
if 1200 > cursor.rect.x > 954 and \
900 > cursor.rect.y > 809:
for block in allBlocks:
if (not int(block.north) == 0) and \
(not int(block.east) == 0) and \
(not int(block.south) == 0) and \
(not int(block.west) == 0):
blocksToWrite.append(
str(block.rect.x) + " " +
str(block.rect.y) + " " +
str(block.north) + " " +
str(block.east) + " " +
str(block.south) + " " +
str(block.west))
numBlocks += 1
if numBlocks > 0:
#blocksToWrite.append["0"]
boardName = ask(self.screen,
self.strings['boardName'],
529, 10, 450, 30, 42, False,
10, False)
allsprites.update()
screen.blit(background, (0, 0))
allsprites.draw(screen)
pygame.display.flip()
objText = ask(self.screen,
self.strings['objectiveText'],
250, 10, 750, 30, 30, False, 60)
blocksToWrite[0] = str(numBlocks)
blocksToWrite.append(objText)
#add teh board to the list of available boards
temp = open("data" +
os.sep +
"boardList.txt", 'r')
self.tempList = (temp.read()).rsplit('\n')
self.tempList = self.tempList[:-1]
temp = file("data" +
os.sep +
"boardList.txt", 'w')
temp.write(boardName + '\n')
for line in self.tempList:
temp.write(line + '\n')
temp.close()
#write the actual board itself
f = open("boards" +
os.sep +
boardName + ".txt", 'w')
for line in blocksToWrite:
#print line
f.write(line + "\n")
f.close()
else:
timeText.change(self.strings['atLeastOne'])
#main menu button
if 240 > cursor.rect.x > 0 and 900 > cursor.rect.y > 809:
self.mainMenu = MainMenu()
elif e.type == MOUSEBUTTONUP:
event.set_grab(0)
if e.type == KEYDOWN:
if(e.key == K_SPACE) or (e.key == K_KP3):
event.set_grab(1)
#on click of the check answer button if done with keyboard
elif e.type == KEYUP:
if(e.key == K_SPACE) or (e.key == K_KP3):
event.set_grab(0)
if not editMode:
if not completed:
#check answer button
if 1200 > cursor.rect.x > 954 and \
900 > cursor.rect.y > 809:
result = Solve(allBlocks)
if result == 'Solved!':
solved.change(
self.strings['win'])
completed = True
else:
loopCounter = 0
solved.change(
self.strings['incomplete'])
#save custom created board
else:
#blocksToWrite.append["0"]
if 1200 > cursor.rect.x > 954 and \
900 > cursor.rect.y > 809:
for block in allBlocks:
if (not int(block.north) == 0) and \
(not int(block.east) == 0) and \
(not int(block.south) == 0) and \
(not int(block.west) == 0):
blocksToWrite.append(
str(block.rect.x) +
" " + str(block.rect.y) +
" " + str(block.north) +
" " + str(block.east) +
" " + str(block.south) +
" " + str(block.west))
numBlocks += 1
if numBlocks > 0:
#blocksToWrite.append["0"]
boardName = ask(self.screen,
self.strings['boardName'],
529, 10, 450,