Source

pdw / ProduceDefendWin.py

The default branch has multiple heads

Full commit
  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
# coding=UTF8
# Copyright © 2010 Rob Leachman
# Please see the file COPYING in this distribution for license information
## #! /usr/bin/env python
# ProduceDefendWin.py
#
# My first Python game, learned a lot and there's a ton I'd do differently
# but rather than spend more time here... get it out and move on. But I'm
# interested in any comments anyone would have. Reasonably satisified
# with how it turned out :)
#
# I've left a ton of crummy notes to myself in the code, here are a few:
#
# I used Stanti's Python Editor for this, good stuff.
# First thing, I added a shortcut to
# /applications/SPE.app/Contents/Resources/_spe/shortcuts/Macintosh.py
# Now it ends with:
#   'Run in terminal without arguments  exit'    : 'Ctrl+Shift+X',
# Fast interative development, SWEET!
#
#
#pygame.mouse.set_visible(0)  # interesting? hides mouse in window


import pygame
import sys
import random
import re # for pyconsole
import os.path
from pygame.mixer import *
from pygame.color import THECOLORS
from pygame.locals import *

from Third_Party_Sources import pyconsole
from Third_Party_Sources import pyconsole_syntax, \
    re_add, console_add, re_function, console_func
from pyconsole_functions import *

import enviro # my global game environment
import Noise # the noise module, all the music and effects stuff go here

from YourStuff import *
from AttackerStuff import *
from Fighter import Fighter
from FloatingSprite import FloatingSprite
from Harvester import Harvester
from MotherShip import MotherShip
from GasFactory import GasFactory
from Laser import Laser
from Shields import Shields
from Source import Bomb
from DeadMother import DeadMother
from Generator import Generator

import Title
import mainline

def main(continuing, firstRun):
    
    if firstRun:
        if enviro.testEntryScreenSkip <> 1:
            Title.run("myTitle.png", False)
            Noise.playMusic('JMICKEL_Allmyownworkv2.mp3')
            pygame.mixer.music.set_volume(enviro.INIT_MUSIC/100.0)            
            Title.run("instructions.png", True)
        else:
            Noise.playMusic('JMICKEL_Allmyownworkv2.mp3')
            pygame.mixer.music.set_volume(enviro.INIT_MUSIC/100.0)             
    else:
        Noise.playMusic('JMICKEL_Allmyownworkv2.mp3')          
    
    if not continuing:
        enviro.credits = 0
        enviro.shields.upgrades = 1
        enviro.laser.upgrades = 1
        enviro.gasFactoryIsBuilt = False
        enviro.botFactoryIsBuilt = False
        enviro.BOMB_POWER = 500
        
        # Difficulty menu
        if enviro.testMenuSkip <> 1:
            difficulty = mainline.menu()
        else:
            difficulty = "Normal"
        enviro.difficultyForContinue = difficulty        
    else:
        difficulty = enviro.difficultyForContinue
        
    if enviro.test == 1:
        enviro.credits = 20000
        

    # Draw the pads, the base, get me a you, create some gas, all that stuff...
    enviro.start(difficulty)
    #mainline.varInfo(enviro)

    if enviro.gasFactoryIsBuilt:
        enviro.gasFactory.build()
    else:
        enviro.gasFactory.built = 0 # seems we need this for restart
    
    if enviro.botFactoryIsBuilt:
        enviro.factory.build()
    else:
        enviro.factory.built = 0
        
    mainline.writeInstructions(difficulty)
    enviro.writeCredits(enviro.credits)

    shieldPower = enviro.START_SHIELD_POWER
    maxFighters = enviro.fleetMax

    # The first one's free...
    newGen = Generator(5,enviro.gasGauges, "generator0.png")
    newGen.refill(enviro.gasGauges)
    enviro.generators.append(newGen)

    dramaBackground = pygame.image.load("dramaBackground.png")
    
    # Yes, I could have made even more of these
    demoStep = 0
    motherBecameActive = False
    fightersActive = 1
    frustration = 0
    shooter = False
    paused = False
    shooting = False
    theKillerBomb = None
    deadMother = DeadMother("motherDead-")
    sheDied = False 
    sheIsDead = False
    musicVolumeControllerMouseHeldDown = False
    effectsVolumeControllerMouseHeldDown = False
    linePainted = False
    needHint = True
    
    console = pyconsole.Console(
        enviro.screen, # my screen
        (401,0,328,449), # the drama area - gets refreshed every cycle, required for console
        functions={"FPS":fps,"cheat":cheat,"credits":credits, "line":line}, # functions for the console
        key_calls={"d":sys.exit}, # ctrl+d calls sys.exit()
        syntax={re_add:console_add, re_function:console_func}
        )
    
    mousePos = [0,0]
    bombList = pygame.sprite.Group()
    
    # Steven learned about the word "bailout" today so that's on my mind
    # as I wrestle with what to do if somebody gets cute... be cute right back!
    # It's a little buggy but that's what happens with bailouts.
    # Works well enough I shouldn't get thrown out of office, or something.
    bailoutCount = 0

    alive = 1        
    while alive == 1:
        
        releasedButton = False

        console.process_input()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == K_w and pygame.key.get_mods() & KMOD_CTRL:
                    console.set_active()
                #elif event.key == K_q and pygame.key.get_mods() & KMOD_CTRL: 
                elif event.key == K_1 and (pygame.key.get_mods() == 64 or pygame.key.get_mods() == 128): 
                    # "Just a little hack so you can play with both pyconsole and python"
                    # Hit ctrl w to hide pyconsole, then ctrl 1 to switch modes, then ctrl w again to show the console
                    console.setvar("python_mode", not console.getvar("python_mode"))
                    console.set_interpreter() 
                elif event.key == pygame.K_ESCAPE or event.key == pygame.K_p:
                    if paused:
                        enviro.writePaused(False)
                        paused = False
                    else:
                        enviro.writePaused(True)
                        paused = True
                        enviro.musicVolumeController.paintControl() 
                        enviro.effectsVolumeController.paintControl()
                        enviro.screen.blit(pygame.image.load("effectsIcon.png"), [10,570])
                        enviro.screen.blit(pygame.image.load("musicIcon.png"), [170,570]) 
                elif (pygame.key.get_mods() == 1024): # command key
                    if (event.key == 113):   # q  -- so Apple-Q quits like other programs on OS X
                        sys.exit()
                elif event.key == K_q and (pygame.key.get_mods() == 64 or pygame.key.get_mods() == 128): # ctrl-q like most games
                    sys.exit()
                    
                if enviro.cheatKeys:
                    if event.key == pygame.K_h and pygame.key.get_mods() & KMOD_CTRL:
                        print "HARVESTER DEBUG"
                        for harvester in enviro.harvesters:
                            print harvester
                    elif event.key == pygame.K_t:
                        enviro.theBase.stashStuff()
                    elif event.key == pygame.K_n:
                        print "NUKE"
                        alive = 0
                    elif event.key == pygame.K_u:
                        print "WIN"
                        alive = 0
                        enviro.credits = 1000000
                    elif event.key in enviro.genKeys:
                        mainline.cheatKeys(event.key)                               
                    
                if paused:
                    #print pygame.key.name(109) # the name of a key code
                    break # no actions will be processed until unpause
                
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:        
                    enviro.you.aimLeft(enviro.pads)
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    enviro.you.aimRight(enviro.pads)
                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    enviro.you.aimUp(enviro.pads)
                if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    enviro.you.aimDown(enviro.pads)
                if event.key == pygame.K_SPACE:
                    action = enviro.you.interact(enviro.generators, 
                                                 enviro.shields, 
                                                 enviro.theBase, 
                                                 enviro.laser)
                    if action[0] > -1 and action[1] == 1:
                        # build a generator
                        enviro.doAction(enviro.you, 
                                        action, 
                                        enviro.gasGauges)                       
                        
            elif event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                # There's too much code here... next time!
                mousePos = event.pos
                if musicVolumeControllerMouseHeldDown:
                    enviro.musicVolumeController.setLevel(mousePos)
                    pygame.mixer.music.set_volume(enviro.musicVolumeController.setting/100.0)  
                if effectsVolumeControllerMouseHeldDown:
                    enviro.effectsVolumeController.setLevel(mousePos)
                    for effect in enviro.soundEffect:
                        effect.set_volume(enviro.effectsVolumeController.setting/100.0)                                

                newCursor = event.pos
                if (enviro.combatStarted and 
                   (newCursor[0] > 400 and 
                    newCursor[0] < 730 and 
                    newCursor[1]<430)):
                    pygame.mouse.set_cursor(*enviro.LASER_POINTER)
                    shooter = True
                else:
                    pygame.mouse.set_cursor(*pygame.cursors.arrow)
                    shooter = False
                    shooting = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                
                musicVolumeControllerMouseHeldDown = \
                  enviro.musicVolumeController.mouseOnControl(mousePos)
                effectsVolumeControllerMouseHeldDown = \
                  enviro.effectsVolumeController.mouseOnControl(mousePos)
                
                if shooter and not paused:
                    shooting = True

            elif event.type == pygame.MOUSEBUTTONUP:
                
                if musicVolumeControllerMouseHeldDown == False:
                    enviro.musicVolumeController.setLevelByClick(mousePos)
                    pygame.mixer.music.set_volume(enviro.musicVolumeController.setting/100.0)
                musicVolumeControllerMouseHeldDown = False
                if effectsVolumeControllerMouseHeldDown == False:
                    if enviro.effectsVolumeController.setLevelByClick(mousePos):
                        for effect in enviro.soundEffect:
                            effect.set_volume(enviro.effectsVolumeController.setting/100.0)
                effectsVolumeControllerMouseHeldDown = False                                 
                
                releasedButton = True
                
            #print pygame.key.get_mods()  # show modifier keys
            #if (event.type == KEYUP) or (event.type == KEYDOWN): # show key
            #    print "DEBUG KEY:", event
                            
        """ now do all the stuff that happens each frame: """
 
        enviro.musicVolumeController.paintControl() 
        enviro.effectsVolumeController.paintControl()
        
        if paused and enviro.combatStarted == False and demoStep == 10: 
            demoStep += 1

        if not paused:
            if enviro.combatStarted == False and demoStep > 10:
                mainline.startCombat()
                
            enviro.paintRoadTiles()
                    
            if enviro.combatStarted:
                enviro.screen.blit(dramaBackground, [400,0,330,449])
            else:
                [demoStep, bailoutCount, alive] = mainline.demoMode(demoStep, bailoutCount, alive)
                #print bailoutCount
                    
            for generator in enviro.generators:
                generator.produce(enviro.gasGauges)
            if enviro.combatStarted:
                shieldPower = enviro.shields.powerUp(shieldPower, enviro.fuelPile)
                shieldSprite = enviro.shields.paintShield(shieldPower)

                frustration += 1
                if frustration > enviro.MOTHER_FLEET_INCREASE_WAITTIME:
                    frustration = 0
                    fightersActive += 1
                    if fightersActive > maxFighters:
                       fightersActive = maxFighters            

                # paint her progress, and get any emitted bombs
                theMother = enviro.mother.paint(bombList, fightersActive) 
                bombList = theMother[0]
                drama = theMother[1]
                herState = theMother[2]
                
                if sheIsDead:
                    deadMother.setLocation(enviro.mother.diedAt,0)
                    sheDied = True
                    sheIsDead = False
                
                if not herState == "Waiting":
                    if not motherBecameActive:
                        motherBecameActive = True
                        if pygame.mixer:
                            Noise.playMusic('JMICKEL_ViperFantastic.mp3')
                            
                if drama == 1:
                    shieldPower = shieldPower - enviro.BOMB_POWER
                    if shieldPower < 0:
                        shieldPower = 0
                    enviro.shields.hitShield(shieldPower)
                    enviro.shields.paintShield(shieldPower)
                    enviro.soundEffect[Noise.SHIELD_HIT].play()
                    if needHint and (difficulty == "Easy" or difficulty == "Normal"):
                        linePainted = mainline.writeHelpfulHintLine(linePainted)
                    
                if len(bombList) > 0:
                    for bomb in bombList:
                        if bomb.move() == 0 and bomb.rect.top == 430:
                            if theKillerBomb == None:
                                theKillerBomb = bomb
                                channel = pygame.mixer.find_channel(True)
                                if channel:
                                    #print "got channel"
                                    channel.play(enviro.soundEffect[Noise.MOTHER_HIT])
                                else:
                                    print "no channel for mother kill sound, will try to use main"
                                    enviro.soundEffect[Noise.MOTHER_HIT].play()                            
                                
                        if shieldPower > 0:
                            bomb.test(shieldSprite, "caught")                            
                                
                    if not theKillerBomb == None:
                        if not theKillerBomb.nuked:
                            theKillerBomb.paint()
                            theKillerBomb.nuke()
                        else:
                            alive = 0
                    
            for harvester in enviro.harvesters:
                harvester.getNextState(enviro.shields, 
                   enviro.theBase, enviro.generators, enviro.laser)
                
            for pad in enviro.padArray:
                pad.clearNeeds()

            next = enviro.you.moveYou(enviro.pads)
            if next == "up":
                enviro.you.aimUp(enviro.pads)
            elif next == "down":
                enviro.you.aimDown(enviro.pads)
            elif next == "right":
                enviro.you.aimRight(enviro.pads)
            elif next == "left":
                enviro.you.aimLeft(enviro.pads)
            elif next == "act":
                action = enviro.you.interact(enviro.generators, 
                           enviro.shields, enviro.theBase, enviro.laser)
                if action[0] > -1 and action[1] == 1:
                    enviro.doAction(enviro.you, action, enviro.gasGauges)

            autoTarget = False
            if not shooting:
                target = enviro.laser.autoTarget(bombList)            
                if target[0] > 0:
                    newCursor = target
                    shooting = True
                    autoTarget = True
            else:
                needHint = False
            if shooting:
                shooting = enviro.laser.shoot(bombList, newCursor, 
                                             releasedButton, autoTarget)
                if enviro.mother.state == "Hit":
                    sheIsDead = True

                    if pygame.mixer:
                        Noise.playMusic('JMICKEL_Allmyownworkv2.mp3')
                        motherBecameActive = False
                        
            if sheDied:
                sheDied = deadMother.paint()
                            
        if enviro.credits > 49999:
            alive=0
                    
        myClock.tick(30)
        
        if not paused:
            mainline.writeFPSandDifficulty(myClock, difficulty)

        console.draw()

        pygame.display.flip()
    
    pygame.mixer.music.fadeout(1000)    
    if enviro.credits > 49999:
        mainline.winner(difficulty)
    else:
        mainline.loser(bailoutCount)
        
        
        
if __name__ == '__main__':
    # Init the screen and sound and everything... 
    pygame.init()
    Noise.initMixer()
    myClock = pygame.time.Clock()
    enviro.screen = pygame.display.set_mode([800,600])
            
    pygame.display.set_caption('Produce, Defend, Win!')
    enviro.init()
    
    # Do the game until it is over...
    
    #import profile
    #profile.run('main(False, True)')
    main(False, True)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()            

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    main(True, False)
                if event.key == pygame.K_r:
                    main(False, False)
                if event.key == pygame.K_q:
                    sys.exit()
                    
            if event.type == pygame.KEYDOWN:
                if (pygame.key.get_mods() == 1024): # command key
                    if (event.key == 113):   # q
                        sys.exit()