/
main.py
executable file
·496 lines (361 loc) · 19.4 KB
/
main.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
"""
UpChomp - A momentum game staring Chompy
Copyright (C) 2011 Nathan Ogden
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import pygame, math, menu, chompy, sound, gamemap, dialog, hud, transition, sys, os, iniget, traceback, zipfile, shutil, time, hashlib
if hasattr(sys, 'frozen'):
app_path = os.path.dirname(sys.executable)
elif __file__:
app_path = os.path.dirname(__file__)
app_path = app_path.replace('\\', '/') + "/"
try:
import android, android_mixer
print "[OS] Running on Android."
except ImportError:
print "[OS] Running on PC."
android = None
settings = iniget.iniGet(app_path + "settings.ini")
error_log = open(app_path + 'error.log', 'w')
class Game(object):
def __init__(self):
"""Inits the game."""
pygame.init()
# Set size here so Android can overwrite it.
size=[640,480]
# Do some android stuff
if android:
android.init()
# Map back key to to escape
android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
# Get display size and set game size to it
disp_info = pygame.display.Info()
size = [disp_info.current_w, disp_info.current_h]
# Activate accelerometer
if settings.getBool("android","accelerometer_enable"): android.accelerometer_enable(1)
# Screen/Dialog stuff
self.screen=pygame.display.set_mode(size, pygame.RESIZABLE)
pygame.display.set_caption("UpChomp")
# Used to manage how fast the screen updates
self.clock=pygame.time.Clock()
# Game Save
self.save = iniget.iniGet(app_path + "game.sav")
# Sprites
self.all_sprites_list = pygame.sprite.RenderPlain()
# Initalize Sound
self.sound = sound.Sound()
# Init da Chomp
self.chomp = chompy.Chompy(self.screen, self.sound)
self.all_sprites_list.add(self.chomp)
# Init Menu
self.menu = menu.Menu(self.screen, self.sound, self.clock, self.save)
# Make a dialog object.
self.dlogbox = dialog.Dialog(self.screen, self.sound)
# Setup Hud
self.hud = hud.Hud(self.screen, self.sound)
# Setup Transition
self.transition = transition.Transition()
# Game State: 0-Playing, 1-Main Menu, 2-Pack Select, 3 - Load New Level
self.state = 1
# Init Game Map
self.level = gamemap.Gamemap(self.sound, self.save)
# Frame rate
self.frames = 1
# Set Current Map
self.map_file = []
# Opening a map... install it.
if len(sys.argv) > 1:
size = self.screen.get_size()
# Unzip Map
if not zipfile.is_zipfile(sys.argv[1]):
self.gameLoop()
return None
# Make Temporary Storage Directory
if os.path.exists(app_path + "temp"):
shutil.rmtree(app_path +"temp")
time.sleep(.25)
os.mkdir(app_path + "temp")
zip_file = zipfile.ZipFile(sys.argv[1])
zip_file.extract("maps", app_path + "temp/")
zip_file.close()
mappack = iniget.iniGet(app_path + "temp/maps")
# Get map hash (Used in save file)
maphash = hashlib.sha224(open(sys.argv[1]).read()).hexdigest()
if mappack.get("pack","name") and mappack.get("pack", "order"):
oldmaphash = ""
if os.path.isfile(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm"):
oldmaphash = hashlib.sha224(open(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm").read()).hexdigest()
if maphash == oldmaphash:
print "Failed to install new map pack."
self.dlogbox.setMessageBox(size, "The map you are trying to install appears to already be installed.", "Already Installed!", [['OK',self.menu.dialog.closeMessageBox]] )
else:
shutil.copy (sys.argv[1], app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm")
if os.path.isfile(app_path + "maps/" + mappack.get("pack","name").replace(" ", "_") + ".ucm"):
print "Installed map pack '"+ str(mappack.get("pack","name").replace(" ", "_")) + ".ucm'."
self.dlogbox.setMessageBox(size, "New map pack has been installed!", "New Map Pack!", [['OK',self.menu.dialog.closeMessageBox]] )
else:
print "Failed to install new map pack."
self.dlogbox.setMessageBox(size, "Unable to install map pack.", "Error", [['OK',self.menu.dialog.closeMessageBox]] )
events = pygame.event.get()
while self.dlogbox.drawBox(size, events):
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: # If user clicked close
pygame.quit()
sys.exit()
elif event.type == pygame.VIDEORESIZE:
size = event.size
# Android events
if android:
if android.check_pause():
android.wait_for_resume()
pygame.display.flip()
# Enter game loop
self.gameLoop()
def gameLoop(self):
""" Main game loop. """
# Options for each game state
options = {
0: self.startLevel, # Playing
1: self.displayMenu, # Main Menu
2: self.mapSelect # Map Pack Select
}
done = False
while not done:
# State -1 means quit.
if self.state == -1: done = True
# State 3 is just reloading state 0.
if self.state == 3: self.state = 0
# Stop all sounds
self.sound.stopAllSfx(1, 1)
# Try to load a function for the current state
try: options[self.state]()
# If unable to find a function quit with an error.
except KeyError:
#print "[ERROR] Not a valid game state. Exiting..."
done = True
# Exit Game
pygame.quit()
def displayMenu(self):
""" Sets game state to title screen. """
self.state = self.menu.titleScreen()
def mapSelect(self):
""" Sets game state to map pack select. """
self.level.current_map = 0
self.level.displayDialog = 1
self.map_file = self.menu.mapSelect()
if self.map_file[0] == 0: self.setState(1)
elif self.map_file[0] == -1: self.setState(-1)
else: self.setState(0)
def nextLevel(self):
""" Loads the next level in a map pack. """
self.map_file[1] = -1
self.level.current_map += 1
self.level.displayDialog = 1
self.levelTransition()
def levelTransition(self):
""" Initates a level transition. """
size = self.screen.get_size()
self.transition.verticalSwipe(size)
self.dlogbox.closeMessageBox()
def setState(self, state = 2):
"""
Sets the game state.
@param int state - The state to set the game to, described in a comment above.
"""
self.state = state
def startLevel(self):
"""Loads a level and begins gameplay."""
# Reset Chompy
self.chomp.reset()
# Screen size
size = self.screen.get_size()
# Stop all sounds
self.sound.stopAllSfx(1, 1)
# Load Level
if self.level.packMaps and self.level.current_map > len(self.level.packMaps) - 1:
self.menu.dialog.setMessageBox(size, "You've completed " + self.level.parser.get("pack", "name") + "!", "Complete!", [['OK',self.menu.dialog.closeMessageBox]] )
self.state = 2
return 0
try:
self.level.loadLevel(self.map_file[0], self.map_file[1])
self.level.state = 0
except:
traceback.print_exc(5, error_log)
self.menu.dialog.setMessageBox(size, "There was an error with loading this map.", "Error", [['OK',self.menu.dialog.closeMessageBox]] )
self.state = 2
return 0
# Resize Chompy
chomp_size = size[0]
if size[1] > chomp_size: chomp_size = screensize[1]
self.chomp.resize( math.ceil(chomp_size / 16) )
# Place character in level
pos = self.level.parser.get(self.level.packMaps[self.level.current_map],"startpos").split(",")
self.chomp.pos[0] = int(pos[0]) * self.level.tilesize[0]
self.chomp.pos[1] = int(pos[1]) * self.level.tilesize[1]
self.chomp.colliderect.x = self.chomp.pos[0]
self.chomp.colliderect.y = self.chomp.pos[1]
scroll = [(size[0] / 2) - self.chomp.pos[0] , (size[1] / 2) - self.chomp.pos[1] ]
# If player is moving...
move = 0
# Level time
start_time = pygame.time.get_ticks()
time = 0
self.hud.ready_time = pygame.time.get_ticks()
# Load skills into the Hud
self.hud.loadSkills(size, self.level.parser.get(self.level.packMaps[self.level.current_map],"skills").split(","))
# Load Dialog box
if self.level.displayDialog:
self.dlogbox.setMessageBox(size, self.level.parser.get(self.level.packMaps[self.level.current_map],"desc"), self.level.parser.get(self.level.packMaps[self.level.current_map],"name"), [['Play!',self.dlogbox.closeMessageBox],['Map Select', self.setState]] )
self.level.displayDialog = 0
no_dialog = 0
else:
transition_status = 0
no_dialog = 1
pygame.event.set_allowed((pygame.KEYDOWN, pygame.QUIT, pygame.MOUSEMOTION, pygame.VIDEORESIZE, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP))
# -------- Main Program Loop -----------
while self.state == 0:
# Set frame rate to 30.
self.clock.tick(30)
# Plus one frame
self.frames += 1
events = pygame.event.get()
for event in events: # User did something
if event.type == pygame.QUIT: # If user clicked close
self.setState(-1) # Set game state to -1(Quit)
elif event.type == pygame.MOUSEBUTTONDOWN:
move = (event.pos[0] - (size[0] / 2.0)) / (size[0] / 8.0)
elif event.type == pygame.MOUSEBUTTONUP:
move = 0
elif event.type == pygame.MOUSEMOTION and move:
move = (event.pos[0] - (size[0] / 2.0)) / (size[0] / 8.0)
elif event.type == pygame.KEYDOWN:
# Move with keyboard
if event.key == pygame.K_LEFT: move = -2.5
elif event.key == pygame.K_RIGHT: move = 2.5
# Toogle Fullscreen
elif event.key == 292: pygame.display.toggle_fullscreen()
# Retry Level
elif event.key == pygame.K_TAB:
self.level.state = 2
self.levelTransition()
elif event.type == pygame.KEYUP:
# Move with keyboard
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: move = 0
elif event.type == pygame.VIDEORESIZE:
self.screen=pygame.display.set_mode(event.size, pygame.RESIZABLE)
size = event.size
self.hud.loadSkills(size)
new_tile_size = size[0]
if size[1] > new_tile_size: new_tile_size = screensize[1]
self.chomp.resize( math.ceil(new_tile_size / 16) )
self.level.resizeTiles( math.ceil(new_tile_size / 16))
# Android events
if android:
if android.check_pause():
android.wait_for_resume()
accel = android.accelerometer_reading()
if abs(accel[1]) > .5:
move = accel[1] * 1.4
lscroll = scroll
scroll = [(size[0] / 2) - self.chomp.pos[0] , (size[1] / 2) - self.chomp.pos[1] ]
# Lock scrolling to edge of level
if scroll[1] < size[1] - (self.level.mapheight * self.level.tilesize[1]): scroll[1] = size[1] - (self.level.mapheight * self.level.tilesize[1])
if scroll[0] > 0: scroll[0] = 0
if scroll[0] < size[0] - (self.level.mapwidth * self.level.tilesize[0]): scroll[0] = size[0] - (self.level.mapwidth * self.level.tilesize[0])
# Draw the background
self.level.drawBackground(self.screen, scroll, size)
# Draw tiles and handle tile collision with player
self.level.updateTiles(self.screen, scroll, size, self.chomp, self.sound)
# Update time
time = pygame.time.get_ticks() - start_time
# Android Sound Loops
if android: self.sound.update()
# If a dialog box isn't up.
dbox = self.dlogbox.drawBox(size, events)
if not dbox:
# If the game has displayed the "Get Ready!" - "Go!" message.
if not transition_status or no_dialog:
getready = self.hud.getReady(size)
else:
getready = 0
if not getready:
# Update Chomp Movement...only when level is playable(i.e. not beaten or lost)
if not self.level.state: self.chomp.update(scroll, move, size)
# Draw Sprites
self.all_sprites_list.draw(self.screen)
# If Chompy can't move it's game over...
if not self.chomp.moveok and self.chomp.speed == 0:
if self.chomp.stopclock < 0: self.chomp.stopclock = 30
else: self.chomp.stopclock = -1
if self.chomp.stopclock == 0:
self.level.state = 2
# If Chompy falls below the level...
if self.chomp.colliderect.y > self.level.mapheight * self.level.tilesize[1]:
self.level.state = 2
# Game over level state...
if self.level.state == 2:
self.chomp.speed = .1
self.chomp.falling = .1
self.chomp.moveok = 1
if self.transition.type == 0:
self.dlogbox.setMessageBox(size,"Chompy didn't make it...", "Oh No!!", [['Retry',self.levelTransition],['Map Select', self.setState]] )
# Update Hud
self.hud.update(size,time)
self.hud.checkSkillActivation(events, size, self.chomp)
# Check level state
if self.level.state == 1:
self.chomp.speed = 0
self.chomp.falling = 0
if self.transition.type == 0:
gametime = round( time / 1000.0,2 )
aranktime = float(self.level.parser.get(self.level.packMaps[self.level.current_map], "arank"))
# Save Progress
progress = self.save.getInt(self.level.maphash, "progress")
besttime = self.save.getFloat(self.level.maphash, self.level.packMaps[self.level.current_map] )
if not besttime: besttime = 9999.99
if progress < self.level.current_map + 1:
self.save.set(self.level.maphash, "progress", self.level.current_map + 1)
if besttime and gametime < besttime:
self.save.set(self.level.maphash, self.level.packMaps[self.level.current_map], gametime)
newrecord = " - New Record!"
else: newrecord = ""
self.save.parser.read(app_path + "game.sav")
if aranktime and gametime <= aranktime:
self.dlogbox.setMessageBox(size,"A+! - TIME: " + str(round( time / 1000.0,2 )) + newrecord , "Pwned!!!", [['Retry',self.levelTransition],['Next Level',self.nextLevel]] )
else:
self.dlogbox.setMessageBox(size,"TIME: " + str(round( time / 1000.0,2 )) + newrecord , "Winner!", [['Retry',self.levelTransition],['Next Level',self.nextLevel]] )
# If get ready message still up reset timers.
else:
start_time = pygame.time.get_ticks()
time = 0
# If closed by clicking X return to map select.
elif dbox == -1:
self.setState(2)
# Reset time as long as dialog box is up
else:
start_time = pygame.time.get_ticks()
time = 0
self.hud.ready_time = pygame.time.get_ticks() # As long as dialog box is up reset "Get Ready!" - "Go!" message.
# If there is a transition playing
transition_status = self.transition.update(self.screen)
if transition_status:
if transition_status < 1:
self.transition.type = 0
if transition_status and transition_status < 2 and self.level.state: self.setState(3)
# If the back button was clicked in the hud...
if self.hud.doMapSelect:
self.setState(2)
self.hud.doMapSelect = 0
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
Game()