def main_loop(self): """Process events, update, and render.""" dt = sdl.getTicks() / 1000. fps = 0 fps_reported = 0 while not self.done: self.event_loop() self.update(dt) self.camera.render(self.player, self.game_map) ticks = sdl.getTicks() dt = (ticks / 1000.) - dt renderer.renderPresent() renderer.setRenderDrawColor(0, 0, 0, 255) renderer.renderClear() fps += 1 if ticks - fps_reported > 1000: # report once a second self.display_fps(fps) fps = 0 fps_reported = ticks
def main_loop(self): """Process events, update, and render.""" dt = sdl.getTicks() / 1000. fps = 0 fps_reported = 0 while not self.done: self.event_loop() self.update(dt) self.camera.render(self.player, self.game_map) ticks = sdl.getTicks() dt = (ticks / 1000.) - dt renderer.renderPresent() renderer.setRenderDrawColor(0,0,0,255) renderer.renderClear() fps += 1 if ticks - fps_reported > 1000: # report once a second self.display_fps(fps) fps = 0 fps_reported = ticks
def run(self): running = True currentTime = 0 lastTime = 0 time = 0 event = sdl.Event() textureW, textureH = game.textureSize(full) textureRect = game.centeredRect(game.width, game.height, textureW, textureH) sdl.setTextureBlendMode(full, sdl.BLENDMODE_ADD) while running: currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt lastTime = currentTime if time <= 3000: sdl.renderClear(driver.renderer) alpha = int(round((time / 3000.0) * 255)) if alpha > 255: time += 3000 alpha = 255 sdl.renderCopy(driver.renderer, fade, None, textureRect) sdl.setTextureAlphaMod(full, alpha) sdl.renderCopy(driver.renderer, full, None, textureRect) while sdl.pollEvent(event): if event.type == sdl.KEYDOWN: time += 3000 elif event.type == sdl.MOUSEBUTTONDOWN: time += 3000 if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() else: sdl.renderCopy(driver.renderer, fade, None, textureRect) sdl.renderCopy(driver.renderer, full, None, textureRect) while sdl.pollEvent(event): if event.type == sdl.MOUSEBUTTONDOWN: running = False self.next = "menu" if event.type == sdl.KEYDOWN: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() else: running = False self.next = "menu" sdl.renderPresent(driver.renderer)
def run(self): running = True currentTime = 0 lastTime = 0 time = 0 pressed = False event = sdl.Event() while running: currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt lastTime = currentTime textureW, textureH = game.textureSize(winTexture) goRect = game.centeredRect(game.width, game.height, textureW, textureH) if time <= 3000: sdl.renderClear(driver.renderer) alpha = int(round((time / 3000.0) * 255)) sdl.setTextureAlphaMod(winTexture, alpha) sdl.renderCopy(driver.renderer, winTexture, None, goRect) while sdl.pollEvent(event): if event.type == sdl.KEYDOWN: time += 3000 if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() else: sdl.renderClear(driver.renderer) sdl.renderCopy(driver.renderer, winTexture, None, goRect) while sdl.pollEvent(event): if event.type == sdl.KEYDOWN: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() elif event.key.keysym.sym in [ sdl.K_SPACE, sdl.K_RETURN ]: running = False self.next = "highScore" sdl.renderPresent(driver.renderer)
def run(self): cursor1 = MC.Chef(220, 190, 50, 80, 'none', 0, 0, 0, 0.001, 0.001, cursorTexture, True, 0, 0, 100, True, 1) cursor2 = MC.Chef(535, 190, 50, 80, 'none', 0, 0, 0, 0.001, 0.001, cursorTexture, True, 0, 0, 100, True, 1) running = True currentTime = 0 lastTime = 0 time = 0 cursorPos = 0 brightnessPos = 10 volumePos = round((driver.volume - 8) / 12) event = sdl.Event() textureW, textureH = game.textureSize(optionsTexture) textureRect = game.centeredRect(game.width, game.height, textureW, textureH) sdl.renderClear(driver.renderer) sdl.renderCopy(driver.renderer, optionsTexture, None, textureRect) # render cursor in time1 = ((int(time / 125)) % 4) time2 = ((int(time / 500)) % 4) # the rectangle that defines which sprite part the sprites spriteFrame = sdl.Rect((time1 * 48, 0, 48, 80)) spriteFrame2 = sdl.Rect((time2 * 48, 0, 48, 80)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor1.getRect(0, 0)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor2.getRect(0, 0)) #render in brightness indicators for i in range(brightnessPos): spot = sdl.Rect((280 + 25 * i, 357, 18, 18)) sdl.renderCopy(driver.renderer, indTexture, None, spot) #render in volume indicators for i in range(volumePos): spot = sdl.Rect((280 + 25 * i, 242, 18, 18)) sdl.renderCopy(driver.renderer, indTexture, None, spot) sdl.renderPresent(driver.renderer) while running: hover = None clicked = None #### TIME MANAGEMENT #### currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt lastTime = currentTime #### TEXTURE MEASUREMENTS #### textureW, textureH = game.textureSize(optionsTexture) textureRect = game.centeredRect(game.width, game.height, textureW, textureH) #### HANDLE INPUT #### while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False game.turnOff() elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() elif event.type == sdl.MOUSEBUTTONDOWN: if event.button.button == sdl.BUTTON_LEFT: for i in range(len(boxes)): if clicked is None: sdl.mixer.playChannel(0, selectSound, 0) clicked = boxes[i].checkEvent( event.motion.x, event.motion.y) for i in range(len(volumeBoxes)): here = volumeBoxes[i].checkEvent( event.motion.x, event.motion.y) if here is not None: volumePos = here elif event.type == sdl.MOUSEMOTION: for i in range(len(boxes)): if (boxes[i].checkMotion(event.motion.x, event.motion.y)): hover = boxes[i].cursorPos if event.type == sdl.KEYDOWN: if event.key.keysym.sym == sdl.K_UP: sdl.mixer.playChannel(1, scrollSound, 0) cursorPos -= 1 if cursorPos <= -1: cursorPos = 2 elif event.key.keysym.sym == sdl.K_DOWN: sdl.mixer.playChannel(1, scrollSound, 0) cursorPos = (cursorPos + 1) % 3 elif event.key.keysym.sym == sdl.K_RIGHT: sdl.mixer.playChannel(1, scrollSound, 0) if cursorPos is 1: if sdl.getWindowBrightness(driver.window) < 1: brightnessPos += 1 sdl.setWindowBrightness( driver.window, sdl.getWindowBrightness(driver.window) + 0.05) elif cursorPos is 0: if volumePos < 10: volumePos += 1 sdl.mixer.volume(-1, volumePos * 12) driver.volume = volumePos * 12 elif event.key.keysym.sym == sdl.K_LEFT: sdl.mixer.playChannel(1, scrollSound, 0) if cursorPos is 1: if sdl.getWindowBrightness(driver.window) > .5: brightnessPos -= 1 sdl.setWindowBrightness( driver.window, sdl.getWindowBrightness(driver.window) - 0.05) elif cursorPos is 0: if volumePos > 1: volumePos -= 1 sdl.mixer.volume(-1, volumePos * 12) driver.volume = volumePos * 12 elif event.key.keysym.sym == sdl.K_RETURN: if (cursorPos == 0): # Call to play game sdl.mixer.playChannel(1, scrollSound, 0) elif (cursorPos == 1): #ADD IN OPTIONS sdl.mixer.playChannel(1, scrollSound, 0) elif (cursorPos == 2): #Call to controls screen sdl.mixer.playChannel(0, selectSound, 0) running = False self.next = "menu" while (sdl.getTicks() - currentTime < 300): pass if (hover is not None): cursorPos = hover if clicked is not None: if cursorPos is 2: sdl.mixer.playChannel(0, selectSound, 0) running = False self.next = "menu" cursor1.updateY(190 + 115 * cursorPos) cursor2.updateY(190 + 115 * cursorPos) #### RENDER #### sdl.renderClear(driver.renderer) sdl.renderCopy(driver.renderer, optionsTexture, None, textureRect) # render cursor in time1 = ((int(time / 125)) % 4) time2 = ((int(time / 500)) % 4) # the rectangle that defines which sprite part the sprites spriteFrame = sdl.Rect((time1 * 48, 0, 48, 80)) spriteFrame2 = sdl.Rect((time2 * 48, 0, 48, 80)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor1.getRect(0, 0)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor2.getRect(0, 0)) for i in range(brightnessPos): spot = sdl.Rect((280 + 25 * i, 357, 18, 18)) sdl.renderCopy(driver.renderer, indTexture, None, spot) for i in range(volumePos): spot = sdl.Rect((280 + 25 * i, 242, 18, 18)) sdl.renderCopy(driver.renderer, indTexture, None, spot) sdl.renderPresent(driver.renderer)
def load(self): time = sdl.getTicks() # driver.loading.load() global music global ratDyingSound, getOut, hitGeneric, woosh global hit global ladleHit global story1, story2 story1 = Story(1) story2 = Story(2) story1.load() story2.load() story1.run() # driver.loading.run() # assigning music channels sdl.mixer.allocateChannels(5) music = sdl.mixer.loadMUS('music/songs/level1music.xm') ratDyingSound = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/rat_death.mp3' , 'rw'), 0) getOut = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/get_out_you_dirty_rats.wav' , 'rw'), 0) hit = [] for i in range(3): hit.append( sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/hit' + str(i) + '.wav', 'rw'), 0)) ladleHit = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/ladle_hit.wav', 'rw'), 0) hitGeneric = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/hit.wav', 'rw'), 0) woosh = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/woosh.wav', 'rw'), 0) ratImages = [ sdl.image.load('graphics/sprites/rat_hurt.png'), #0 sdl.image.load('graphics/sprites/rat_up.png'), sdl.image.load('graphics/sprites/rat_right.png'), #2 sdl.image.load('graphics/sprites/rat_down.png'), sdl.image.load('graphics/sprites/rat_left.png'), #4 sdl.image.load('graphics/sprites/rat_attack_up.png'), sdl.image.load('graphics/sprites/rat_attack_right.png'), #6 sdl.image.load('graphics/sprites/rat_attack_down.png'), sdl.image.load('graphics/sprites/rat_attack_left.png'), #8 sdl.image.load('graphics/items/cheese.png'), sdl.image.load('graphics/ui/light.png'), #10 ] # array of tiles used throughout the map mapImages = [] for x in range(1, 32): mapImages.append(sdl.image.load('graphics/map/' + str(x) + '.png')) objectImages = [] objectImages.append( sdl.image.load('graphics/items/pizza_animation.png')) objectImages.append( sdl.image.load('graphics/items/heart_animation.png')) objectImages.append( sdl.image.load('graphics/items/carrot_animation.png')) objectImages.append(sdl.image.load('graphics/items/key_animation.png')) weaponImages = [] weaponImages.append(sdl.image.load('graphics/items/ladles.png')) weaponImages.append(sdl.image.load('graphics/items/graters.png')) pantryImages = [ sdl.image.load('graphics/items/open_pantry.png'), sdl.image.load('graphics/items/pantry_open.png'), sdl.image.load('graphics/messages/press_open.png'), sdl.image.load('graphics/items/open_pantry_key.png'), sdl.image.load('graphics/messages/found_key.png'), sdl.image.load('graphics/messages/basement_locked.png'), ] pantryTextures = [] for x in range(len(pantryImages)): pantryTextures.append( driver.renderer.createTextureFromSurface(pantryImages[x])) sdl.freeSurface(pantryImages[x]) # creates an array of arrays of integrets that represents our map's floor global map map = [] with open('data/map.txt') as f: for line in f: currentLine = [] split = line.split() for value in line.split(): currentLine.append(int(value)) map.append(currentLine) # fill up the objects array which contains the objects that can be collided with global structures structures = [] count = 0 for j in range(len(map)): for i in range(len(map[j])): value = map[j][i] if value is 27: if count is 0: struct = Structure( value, i, j, pantryTextures, True, 'pantry', ) count += 1 else: struct = Structure( value, i, j, pantryTextures, False, 'pantry', ) structures.append(struct) elif value is (2 or 3): structures.append( Structure( value, i, j, pantryTextures, False, 'stairs', )) elif value is not 1: structures.append( Structure( value, i, j, None, False, None, )) #a graph of every tile mapped to every one of its neighbors self.navGraph = navGraph.navGraph(map, {1}, 1) # for now just stuff that's dropped by the rats global objects objects = [] global objectTextures objectTextures = [] for x in range(len(objectImages)): objectTextures.append( driver.renderer.createTextureFromSurface(objectImages[x])) sdl.freeSurface(objectImages[x]) for x in range(len(weaponImages)): objectTextures.append( driver.renderer.createTextureFromSurface(weaponImages[x])) sdl.freeSurface(weaponImages[x]) global ratTextures ratTextures = [] for x in range(len(ratImages)): ratTextures.append( driver.renderer.createTextureFromSurface(ratImages[x])) sdl.freeSurface(ratImages[x]) global mapTextures mapTextures = [] for x in range(len(mapImages)): mapTextures.append( driver.renderer.createTextureFromSurface(mapImages[x])) sdl.freeSurface(mapImages[x]) driver.scoreBoard.clearScore() driver.scoreBoard.updateScore(100000)
def run(self): driver.chef.resetChef() sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) sdl.mixer.playMusic(music, -1) running = True accumulator = 0.0 # clockwise starting at 12 o'clock directions = [ 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', ] # Boolean key directions up = False down = False left = False right = False # space = attack space = False # r = release the rats r = False # use = use interactible structure use = False # paused = whether or not the game is paused paused = False # list of enemies enemies = [] # list of emitters emitters = [] explosionLife = 500 event = sdl.Event() # add the carrot objects.append(Object( 1500, 600, 50, 50, 'carrot', objectTextures[2], )) # add the ladle bject objects.append(Object( 500, 650, 50, 50, 'ladles', objectTextures[4], )) time = 0 lastTime = sdl.getTicks() camera = Camera(driver.chef, None, map, mapTextures, objects, enemies, emitters, game.width, game.height, ratTextures, structures, 1, None, None) pauseMenu = Pause(camera) instructionScreen = Instruct(camera) instr = False global item # create 5 randomly placed enemies moving in a random direction at enemySpeed #self.chefNode = self.navGraph.getNode(driver.chef.xPos//50, driver.chef.yPos//50) self.chefNode = driver.chef.getNode(self.navGraph) currentTime = sdl.getTicks() for i in range(3): enemies.append(self.createRandomRat(directions, currentTime)) sdl.renderPresent(driver.renderer) frames = 0 keyPress = False sdl.mixer.playChannel(2, getOut, 0) while running: currentTime = sdl.getTicks() framerate = 3000 / 60.0 dt = currentTime - lastTime time += dt lastTime = currentTime accumulator += dt # the time at which the player can be hit by enemies while accumulator >= framerate: if paused: pauseMenu.load() running = pauseMenu.run() pauseMenu.cleanup paused = False lastTime = sdl.getTicks() sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) elif instr: instructionScreen.run(item) instr = False lastTime = sdl.getTicks() sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) up = False down = False left = False right = False space = False use = False z = False else: if driver.chef.dead: running = False self.next = 'gameOver' while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False game.turnOff() elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() if event.key.keysym.sym == sdl.K_UP: up = False elif event.key.keysym.sym == sdl.K_DOWN: down = False elif event.key.keysym.sym == sdl.K_LEFT: left = False elif event.key.keysym.sym == sdl.K_RIGHT: right = False elif event.key.keysym.sym == sdl.K_SPACE: space = False elif event.key.keysym.sym == sdl.K_RETURN: if driver.chef.yPos <= 50 and driver.chef.xPos \ >= len(map[0]) * 50 - 150 and driver.chef.xPos \ <= len(map[0]) * 50 - 100 and 'key' \ in driver.chef.items and len(enemies) is 0: running = False driver.chef.items.remove('key') driver.chef.score = driver.scoreBoard.getScore( ) self.next = 'levelTwo' story2.run() return use = False elif event.key.keysym.sym == sdl.K_z: z = False if event.type == sdl.KEYDOWN: if event.key.keysym.sym == sdl.K_UP: up = True elif event.key.keysym.sym == sdl.K_DOWN: down = True elif event.key.keysym.sym == sdl.K_LEFT: left = True elif event.key.keysym.sym == sdl.K_RIGHT: right = True elif event.key.keysym.sym == sdl.K_SPACE: space = True elif event.key.keysym.sym == sdl.K_r: r = True elif event.key.keysym.sym == sdl.K_RETURN: use = True elif event.key.keysym.sym == sdl.K_h: # Debug: add 100 health driver.chef.setCanBeHit(False) driver.chef.setDizzy(True) driver.chef.setCanBeHitTime(currentTime + 3000) driver.chef.setDizzyTime(currentTime + 750) driver.chef.updateHealth(8) elif event.key.keysym.sym == sdl.K_l: enemies.append( self.createRandomRat(directions, time)) elif event.key.keysym.sym == sdl.K_m: running = False self.next = 'menu' # Debug: go to level 2 elif event.key.keysym.sym == sdl.K_2: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = \ driver.scoreBoard.getScore() self.next = 'levelTwo' story2.run() return # Debug: go to level 3 elif event.key.keysym.sym == sdl.K_3: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = \ driver.scoreBoard.getScore() self.next = 'levelThree' story2.run() return # Debug: go to level 4 elif event.key.keysym.sym == sdl.K_4: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = \ driver.scoreBoard.getScore() self.next = 'levelFour' story2.run() # Debug: go to level 5 elif event.key.keysym.sym == sdl.K_5: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = \ driver.scoreBoard.getScore() self.next = 'levelFive' story2.run() # Debug: go to pvp level elif event.key.keysym.sym == sdl.K_6: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = \ driver.scoreBoard.getScore() self.next = 'pvp' story2.run() # Debug: toggle the carrot item elif event.key.keysym.sym == sdl.K_w: if 'carrot' not in driver.chef.items: driver.chef.addItem('carrot') else: driver.chef.removeItem('carrot') # Debug: toggle the key item elif event.key.keysym.sym == sdl.K_k: if 'key' not in driver.chef.items: driver.chef.addItem('key') else: driver.chef.removeItem('key') elif event.key.keysym.sym == sdl.K_e: tsum = currentTime + explosionLife emit = self.addEmitter( driver.chef.xPos + driver.chef.getWidth() // 2, driver.chef.yPos + driver.chef.getHeight() // 2, tsum, 'explosion') emit.emit() emitters.append(emit) elif event.key.keysym.sym == sdl.K_p: paused = True keyPress = left or right or up or down # based on the keys pressed down set the driver.chef's direction if keyPress is True: driver.chef.updateDirection(up, down, left, right) # pressing space on keydown will place the player into attacking state if space and currentTime > driver.chef.getAttackingTime() \ and len(driver.chef.weapons) is not 0: if driver.chef.getEnergy() > 0: driver.chef.setAttacking(True) driver.chef.setAttackingTime( currentTime + 300) # attacking animation with be 1s driver.chef.updateEnergy(-1) sdl.mixer.playChannel(-1, woosh, 0) else: # If you try to attack when you're out of energy, become dizzy for .5s driver.chef.setDizzy(True) driver.chef.setDizzyTime(currentTime + 500) # if the player presses "space" the driver.chef will go into attacking mode # which overrides other animations except getting hit if currentTime > driver.chef.getAttackingTime() \ or driver.chef.getDizzy(): driver.chef.setAttacking(False) else: driver.chef.setAttacking(True) driver.chef.setEnergyRegenTime(currentTime + 1000) # if the player is not attacking, and less than 8 pizza slices, and not dizzy, and 3s from last time attacked, give energy if not space and driver.chef.getEnergy() < 8 \ and not driver.chef.getDizzy() and currentTime \ > driver.chef.getEnergyRegenTime(): driver.chef.updateEnergy(1) driver.chef.setEnergyRegenTime(currentTime + 1000) # if driver.chef not attacking or dizzy, and on same tile as object, pick it up if currentTime > driver.chef.getAttackingTime() \ and not driver.chef.getDizzy(): for obj in objects: if self.intersects(driver.chef, obj): if obj.getTitle() == 'pizza' \ and driver.chef.getEnergy() < 8: driver.chef.updateEnergy(1) objects.remove(obj) if not driver.chef.inGottenItems('pizza'): instr = True driver.chef.setGottenItems('pizza') item = 'pizza' if obj.getTitle() == 'heart' \ and driver.chef.getHealth() <= 8: driver.chef.updateHealth(1) objects.remove(obj) if not driver.chef.inGottenItems('tomato'): instr = True driver.chef.setGottenItems('tomato') item = 'tomato' if obj.getTitle() == 'carrot': driver.chef.addItem('carrot') objects.remove(obj) if not driver.chef.inGottenItems('carrot'): instr = True driver.chef.setGottenItems('carrot') item = 'carrot' if obj.getTitle() == 'ladles': driver.chef.addWeapon('ladles') objects.remove(obj) if not driver.chef.inGottenItems('ladles'): instr = True driver.chef.setGottenItems('ladles') item = 'ladles' if obj.getTitle() == 'graters': driver.chef.addWeapon('graters') objects.remove(obj) if not driver.chef.inGottenItems( 'graters'): instr = True driver.chef.setGottenItems('graters') item = 'graters' # make sure the rats aren't invulnable after a set time for enemy in enemies: if currentTime > enemy.getHurtTime(): enemy.setHurt(False) enemy.resetDamageChange() for pantry in structures: if pantry.identity is 'pantry' \ and pantry.triggered is False: pantry.xPos *= 50 pantry.yPos *= 50 pantry.yPos += 20 if self.intersects(driver.chef, pantry): if pantry.visible is False: pantry.changeVisibility() else: if pantry.visible: pantry.changeVisibility() pantry.xPos /= 50 pantry.yPos -= 20 pantry.yPos /= 50 if pantry.visible: if use is True: pantry.triggerAction() if pantry.hasKey is True: driver.chef.items.append('key') instr = True driver.chef.setGottenItems('key') item = 'key' else: # randomly give either pizza or hearts randNum = random.randint(1, 10) if randNum is 1: objects.append( Object( enemy.xPos + enemy.getWidth() // 2, enemy.yPos + enemy.getHeight() // 2, 50, 50, 'heart', objectTextures[1], )) elif randNum > 1 and randNum <= 4: objects.append( Object( pantry.xPos * 50, pantry.yPos * 50 + 50, 50, 50, 'pizza', objectTextures[0], )) elif pantry.identity is 'stairs': if 'key' not in driver.chef.items: pantry.xPos *= 50 pantry.xPos -= 50 pantry.yPos *= 50 if self.intersects(driver.chef, pantry): if pantry.visible is False: pantry.changeVisibility() else: if pantry.visible is True: pantry.changeVisibility() pantry.xPos += 50 pantry.xPos /= 50 pantry.yPos /= 50 # make sure the rats aren't attacking after a set time for enemy in enemies: if currentTime > enemy.getAttackingTime(): enemy.setAttacking(0) # if the invulnability expired set hit back to true if currentTime > driver.chef.getCanBeHitTime(): driver.chef.setCanBeHit(True) # if the dizzyness expired, set dizzy back to false if currentTime > driver.chef.getDizzyTime(): driver.chef.setDizzy(False) driver.chef.resetDamageChange() # checking whether rats are hitting the driver.chef for enemy in enemies: if self.intersects(driver.chef, enemy): # if sdl.hasIntersection(enemy.getRect(), driver.chef.getRect()): # if intersection different things happend depending on if your attacking if driver.chef.getAttacking(): if not enemy.getHurt( ): # if the rat can take damage enemy.updateHealth(-1) enemy.goOppositeDirection(currentTime) enemy.setHurt(True) enemy.setHurtTime(currentTime + 1000) enemy.bump( driver.chef.getAttackingDirection( enemy)) self.genericHit() sdl.mixer.playChannel(-1, ladleHit, 0) camera.activateShake( currentTime, 200, 3, 3) else: if driver.chef.getCanBeHit(): if not enemy.getHurt( ): # hurt rats can't damage us driver.chef.setCanBeHit(False) driver.chef.setDizzy(True) driver.chef.setCanBeHitTime( currentTime + 3000) driver.chef.setDizzyTime(currentTime + 750) driver.chef.bump( enemy.getAttackingDirection( driver.chef)) enemy.setAttackingTime(currentTime + 500) self.playHitSound() driver.chef.updateHealth(-1) camera.activateShake( currentTime, 300, 5, 5) enemy.goOppositeDirection(currentTime) # if rat gets hit five times by bumping, it dies for enemy in enemies: if enemy.health <= 0: int = random.randint(1, 6) if int is 1: objects.append( Object( enemy.xPos + enemy.getWidth() // 2, enemy.yPos + enemy.getHeight() // 2, 50, 50, 'heart', objectTextures[1], )) elif int > 1 and int <= 3: objects.append( Object( enemy.xPos, enemy.yPos, 50, 50, 'pizza', objectTextures[0], )) tsum = currentTime + explosionLife emit = self.addEmitter( enemy.xPos + enemy.getWidth() // 2, enemy.yPos + enemy.getHeight() // 2, tsum, 'rat') emit.emit() emitters.append(emit) enemies.remove(enemy) sdl.mixer.playChannel(-1, ratDyingSound, 0) driver.scoreBoard.updateScore(5000) # score goes down at a set rate, encourages speed driver.scoreBoard.updateScore(-1 * dt) # update driver.chef position based on what keys are being pressed # down if keys are pressed down and he is not off the screen # also based on if driver.chef collides into stuff driver.chef.updatePosition(accumulator, map, keyPress) self.chefNode = driver.chef.getNode(self.navGraph) #x, y = self.chefNode.getPos() #print ("CHEFNODE = ", x,", ",y) # update enemy positions based on direction # if currentTime >= 10000: # if r is True: for enemy in enemies: enemy.updatePosition(accumulator, map, self.navGraph, self.chefNode, currentTime) accumulator -= framerate camera.display(currentTime, dt, keyPress, time) sdl.renderPresent(driver.renderer)
def run(): running = True lastTime = 0 time = 0 up = False down = False left = False right = False event = sdl.Event() xPos = 100 yPos = 100 size = 200 while running: currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt / 1000.0 lastTime = currentTime textureW, textureH = textureSize(texture) textureRect = centeredRect(width, height, textureW, textureH) #Figure out what keys are being pressed while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False if event.key.keysym.sym == sdl.K_UP: up = False elif event.key.keysym.sym == sdl.K_DOWN: down = False elif event.key.keysym.sym == sdl.K_LEFT: left = False elif event.key.keysym.sym == sdl.K_RIGHT: right = False if event.type == sdl.KEYDOWN: if event.key.keysym.sym == sdl.K_UP: up = True elif event.key.keysym.sym == sdl.K_DOWN: down = True elif event.key.keysym.sym == sdl.K_LEFT: left = True elif event.key.keysym.sym == sdl.K_RIGHT: right = True #movement based on what keys are being pressed down if up and left: yPos -= 10 xPos -= 10 elif up and right: yPos -= 10 xPos += 10 elif down and left: yPos += 10 xPos -= 10 elif down and right: yPos += 10 xPos += 10 elif up: yPos -= 10 elif down: yPos += 10 elif left: xPos -= 10 elif right: xPos += 10 testRect = sdl.Rect((xPos, yPos, size, size)) sdl.renderClear(renderer) sdl.renderCopy(renderer, texture, None, textureRect) sdl.renderCopy(renderer, chefTexture, None, testRect) testRect = sdl.Rect((xPos, yPos, 250, 250)) sdl.renderClear(renderer) sdl.renderCopy(renderer, texture, None, textureRect) sdl.renderCopy(renderer, chefTexture, None, testRect) sdl.renderPresent(renderer)
def run(self): sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) cursor1 = MC.Chef(240, 160, 50, 80, 'none', 0, 0, 0, 0.001, 0.001, cursorTexture, True, 0, 0, 100, True, 1) cursor2 = MC.Chef(515, 160, 50, 80, 'none', 0, 0, 0, 0.001, 0.001, cursorTexture, True, 0, 0, 100, True, 1) running = True currentTime = 0 lastTime = 0 time = 0 cursorPos = 0 keepOnPlaying = True event = sdl.Event() controls = Controls() options = Options() while running: hover = None clicked = None #### TIME MANAGEMENT #### currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt lastTime = currentTime #### TEXTURE MEASUREMENTS #### textureW, textureH = game.textureSize(pauseTexture) textureRect = game.centeredRect(game.width, game.height, textureW, textureH) #### HANDLE INPUT #### while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False game.turnOff() keepOnPlaying = False elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() keepOnPlaying = False elif event.type == sdl.MOUSEBUTTONDOWN: if event.button.button == sdl.BUTTON_LEFT: for i in range(len(boxes)): if clicked is None: sdl.mixer.playChannel(0, selectSound, 0) clicked = boxes[i].checkEvent( event.motion.x, event.motion.y) elif event.type == sdl.MOUSEMOTION: for i in range(len(boxes)): if (boxes[i].checkMotion(event.motion.x, event.motion.y)): hover = boxes[i].cursorPos elif event.type == sdl.KEYDOWN: if event.key.keysym.sym == sdl.K_UP: sdl.mixer.playChannel(1, scrollSound, 0) cursorPos -= 1 if cursorPos <= -1: cursorPos = 3 elif event.key.keysym.sym == sdl.K_DOWN: sdl.mixer.playChannel(1, scrollSound, 0) cursorPos = (cursorPos + 1) % 4 elif event.key.keysym.sym == sdl.K_p: sdl.mixer.playChannel(0, selectSound, 0) running = False keepOnPlaying = True elif event.key.keysym.sym == sdl.K_RETURN: if (cursorPos == 0): # Call to play game sdl.mixer.playChannel(0, selectSound, 0) running = False keepOnPlaying = True elif (cursorPos == 1): #ADD IN OPTIONS sdl.mixer.playChannel(0, selectSound, 0) options.load() options.run() options.cleanup() elif (cursorPos == 2): #Call to controls screen sdl.mixer.playChannel(0, selectSound, 0) controls.load() controls.run() controls.cleanup() elif (cursorPos == 3): # Call to quit sdl.mixer.playChannel(0, selectSound, 0) running = False game.turnOff() keepOnPlaying = False while (sdl.getTicks() - currentTime < 300): pass #### RENDER #### if (clicked is not None): if clicked is 'quit': running = False game.turnOff() keepOnPlaying = False elif clicked is "controls": controls.load() controls.run() controls.cleanup() elif clicked is "options": options.load() options.run() options.cleanup() elif clicked is "resume": running = False keepOnPlaying = True if (hover is not None): cursorPos = hover cursor1.updateY(220 + 60 * cursorPos) cursor2.updateY(220 + 60 * cursorPos) sdl.renderClear(driver.renderer) self.camera.display(time, dt, False, None) sdl.renderCopy(driver.renderer, pauseTexture, None, textureRect) # render cursor in time1 = ((int(time / 125)) % 4) time2 = ((int(time / 500)) % 4) # the rectangle that defines which sprite part the sprites spriteFrame = sdl.Rect((time1 * 48, 0, 48, 80)) spriteFrame2 = sdl.Rect((time2 * 48, 0, 48, 80)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor1.getRect(0, 0)) sdl.renderCopy(driver.renderer, cursorTexture, spriteFrame2, cursor2.getRect(0, 0)) sdl.renderPresent(driver.renderer) if not running: return keepOnPlaying
def run(self, itemName): sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) running = True currentTime = 0 lastTime = 0 time = 0 keepOnPlaying = True event = sdl.Event() sdl.mixer.allocateChannels(2) selectSound = sdl.mixer.loadWAV_RW( sdl.RWFromFile("music//chunks/menu_select.wav", 'rw'), 0) cur = 0 if itemName is "bsv": cur = 0 elif itemName is "key": cur = 1 elif itemName is "ladles": cur = 2 elif itemName is "graters": cur = 3 elif itemName is "carrot": cur = 4 elif itemName is "pizza": cur = 5 elif itemName is "tomato": cur = 6 elif itemName is "knives": cur = 7 while running: #### TIME MANAGEMENT #### currentTime = sdl.getTicks() dt = currentTime - lastTime time += dt lastTime = currentTime #### TEXTURE MEASUREMENTS #### textureW, textureH = game.textureSize(driver.chef.textures[3][cur]) textureRect = game.centeredRect(game.width, game.height, textureW, textureH) sdl.renderClear(driver.renderer) self.camera.display(time, dt, False, None) sdl.renderCopy(driver.renderer, driver.chef.textures[3][cur], None, textureRect) sdl.renderPresent(driver.renderer) #### HANDLE INPUT #### while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False game.turnOff() keepOnPlaying = False elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() keepOnPlaying = False if event.type == sdl.KEYDOWN: if event.key.keysym.sym is sdl.K_SPACE: sdl.mixer.playChannel(0, selectSound, 0) running = False keepOnPlaying = True #### RENDER #### if not running: return keepOnPlaying sdl.renderClear(driver.renderer) if selectSound is not None: sdl.mixer.freeChunk(selectSound)
def load(self): time = sdl.getTicks() # driver.loading.load() global music global hit global ladleHit, graterHit, hitGeneric global explosionSound global ratDyingSound, woosh global haveCarrot, needCarrot # driver.loading.run() story = Story(3) story.load() story.run() sdl.mixer.allocateChannels(4) music = sdl.mixer.loadMUS('music/songs/2.mod') hit = [] for i in range(3): hit.append( sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/hit' + str(i) + '.wav', 'rw'), 0)) explosionSound = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/explosion.wav' , 'rw'), 0) ratDyingSound = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/rat_death.mp3' , 'rw'), 0) haveCarrot = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/carrot_lets_me_see.wav' , 'rw'), 0) needCarrot = \ sdl.mixer.loadWAV_RW(sdl.RWFromFile('music/chunks/need_a_carrot.wav' , 'rw'), 0) ladleHit = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/ladle_hit.wav', 'rw'), 0) graterHit = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/grater_hit.wav', 'rw'), 0) hitGeneric = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/hit.wav', 'rw'), 0) woosh = sdl.mixer.loadWAV_RW( sdl.RWFromFile('music/chunks/woosh.wav', 'rw'), 0) ratImages = [ sdl.image.load('graphics/sprites/rat_hurt.png'), sdl.image.load('graphics/sprites/rat_up.png'), sdl.image.load('graphics/sprites/rat_right.png'), sdl.image.load('graphics/sprites/rat_down.png'), sdl.image.load('graphics/sprites/rat_left.png'), sdl.image.load('graphics/sprites/rat_attack_up.png'), sdl.image.load('graphics/sprites/rat_attack_right.png'), sdl.image.load('graphics/sprites/rat_attack_down.png'), sdl.image.load('graphics/sprites/rat_attack_left.png'), sdl.image.load('graphics/items/cheese.png'), ] # array of tiles used throughout the map mapImages = [] for x in range(1, 32): mapImages.append( sdl.image.load('graphics/map/level_2/' + str(x) + '.png')) objectImages = [] objectImages.append( sdl.image.load('graphics/items/pizza_animation.png')) objectImages.append( sdl.image.load('graphics/items/heart_animation.png')) objectImages.append( sdl.image.load('graphics/items/carrot_animation.png')) objectImages.append(sdl.image.load('graphics/items/key_animation.png')) objectImages.append( sdl.image.load('graphics/items/bomb_animation.png')) pantryImages = [ sdl.image.load('graphics/items/lvl2_open_pantry.png'), sdl.image.load('graphics/items/lvl2_pantry_open.png'), sdl.image.load('graphics/messages/press_open.png'), sdl.image.load('graphics/items/open_pantry_key.png'), sdl.image.load('graphics/messages/found_key.png'), sdl.image.load('graphics/messages/basement_locked.png'), sdl.image.load('graphics/messages/found_graters.png'), ] weaponImages = [] weaponImages.append(sdl.image.load('graphics/items/ladles.png')) weaponImages.append(sdl.image.load('graphics/items/graters.png')) pantryTextures = [] for x in range(len(pantryImages)): pantryTextures.append( driver.renderer.createTextureFromSurface(pantryImages[x])) sdl.freeSurface(pantryImages[x]) # creates an array of arrays of integrets that represents our map's floor global map map = [] with open('data/level2.txt') as f: for line in f: currentLine = [] split = line.split() for value in line.split(): currentLine.append(int(value)) map.append(currentLine) # fill up the objects array which contains the objects that can be collided with global structures structures = [] global exit for j in range(len(map)): for i in range(len(map[j])): value = map[j][i] if value is 31: struct = Structure( value, i, j, pantryTextures, False, 'pantry', ) structures.append(struct) if value is 1: exit = Structure( value, i, j, None, False, 'exit', ) self.navGraph = navGraph.navGraph(map, {3}, 2) # for now just stuff that's dropped by the rats + the carrot global objects objects = [] global objectTextures objectTextures = [] for x in range(len(objectImages)): objectTextures.append( driver.renderer.createTextureFromSurface(objectImages[x])) sdl.freeSurface(objectImages[x]) for x in range(len(weaponImages)): objectTextures.append( driver.renderer.createTextureFromSurface(weaponImages[x])) sdl.freeSurface(weaponImages[x]) global ratTextures ratTextures = [] for x in range(len(ratImages)): ratTextures.append( driver.renderer.createTextureFromSurface(ratImages[x])) sdl.freeSurface(ratImages[x]) global mapTextures limitedVisionTexture1 = \ driver.renderer.createTextureFromSurface(sdl.image.load('graphics/ui/limited_vision1.png' )) limitedVisionTexture2 = \ driver.renderer.createTextureFromSurface(sdl.image.load('graphics/ui/limited_vision2.png' )) mapTextures = [] for x in range(len(mapImages)): mapTextures.append( driver.renderer.createTextureFromSurface(mapImages[x])) sdl.freeSurface(mapImages[x]) mapTextures.append(limitedVisionTexture1) mapTextures.append(limitedVisionTexture2) # set the current score to waht it was plus 100000 driver.scoreBoard.setScore(driver.chef.score + 100000) story.cleanup()
def run(self): sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) sdl.mixer.playMusic(music, -1) running = True accumulator = 0.0 # clockwise starting at 12 o'clock directions = [ 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', ] # Boolean key directions up = False down = False left = False right = False # space = attack space = False # z - place bomb z = False # x - blow that shit up x = False # r = release the rats r = False # use = use interactible structure use = False # add the graters object objects.append( Object( 1630, 200, 50, 50, 'graters', driver.chef.textures[1][4], )) # list of enemies enemies = [] # list of emitters emitters = [] explosionLife = 500 event = sdl.Event() driver.chef.velX = 0 driver.chef.velY = 0 driver.chef.xPos = 500 driver.chef.yPos = 350 driver.chef.direction = 'none' driver.chef.floorTile = [3] driver.chef.attacking = False driver.chef.attackingTime = 0 time = 0 lastTime = sdl.getTicks() camera = Camera(driver.chef, None, map, mapTextures, objects, enemies, emitters, game.width, game.height, ratTextures, structures, 2, None, None) camera.updateChefX(driver.chef.xPos) camera.updateChefY(driver.chef.yPos) pauseMenu = Pause(camera) paused = False instructionScreen = Instruct(camera) instr = False global item # create 5 randomly placed enemies moving in a random direction at enemySpeed self.chefNode = self.navGraph.getNode(driver.chef.xPos // 50, driver.chef.yPos // 50) currentTime = sdl.getTicks() for i in range(4): enemies.append(self.createRandomRat(directions, currentTime)) sdl.renderPresent(driver.renderer) frames = 0 keyPress = False hasCarrot = False for x in range(len(driver.chef.items)): if driver.chef.items[x] is 'carrot': hasCarrot = True if hasCarrot: sdl.mixer.playChannel(3, haveCarrot, 0) else: sdl.mixer.playChannel(3, needCarrot, 0) while running: currentTime = sdl.getTicks() framerate = 3000 / 60.0 dt = currentTime - lastTime time += dt lastTime = currentTime accumulator += dt # the time at which the player can be hit by enemies while accumulator >= framerate: if paused: pauseMenu.load() running = pauseMenu.run() pauseMenu.cleanup paused = False lastTime = sdl.getTicks() sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) elif instr: instructionScreen.run(item) instr = False lastTime = sdl.getTicks() sdl.mixer.volume(-1, driver.volume) sdl.mixer.volumeMusic(driver.volume) up = False down = False left = False right = False space = False use = False z = False else: if driver.chef.dead: running = False self.next = 'gameOver' elif len(enemies) is 0: exit.xPos *= 50 exit.yPos *= 50 exit.yPos += 20 if self.intersects(driver.chef, exit) and use \ is True: running = False self.next = 'levelThree' exit.xPos /= 50 exit.yPos -= 20 exit.yPos /= 50 # elif (driver.chef.yPos <= 50 and driver.chef.xPos >= len(map[0]) * 50 - 150 and # driver.chef.xPos <= len(map[0]) * 50 - 100 and # driver.chef.hasKey is True and len(enemies) is 0): # running = False # self.next = "levelTwo" while sdl.pollEvent(event): if event.type == sdl.QUIT: running = False game.turnOff() elif event.type == sdl.KEYUP: if event.key.keysym.sym in [sdl.K_q, sdl.K_ESCAPE]: running = False game.turnOff() if event.key.keysym.sym == sdl.K_UP: up = False elif event.key.keysym.sym == sdl.K_DOWN: down = False elif event.key.keysym.sym == sdl.K_LEFT: left = False elif event.key.keysym.sym == sdl.K_RIGHT: right = False elif event.key.keysym.sym == sdl.K_SPACE: space = False elif event.key.keysym.sym == sdl.K_RETURN: use = False elif event.key.keysym.sym == sdl.K_z: z = False if event.type == sdl.KEYDOWN: if event.key.keysym.sym == sdl.K_UP: up = True elif event.key.keysym.sym == sdl.K_DOWN: down = True elif event.key.keysym.sym == sdl.K_LEFT: left = True elif event.key.keysym.sym == sdl.K_RIGHT: right = True elif event.key.keysym.sym == sdl.K_SPACE: space = True elif event.key.keysym.sym == sdl.K_r: r = True elif event.key.keysym.sym == sdl.K_RETURN: use = True elif event.key.keysym.sym == sdl.K_h: # debug option to add 8 health driver.chef.setCanBeHit(False) driver.chef.setDizzy(True) driver.chef.setCanBeHitTime(currentTime + 3000) driver.chef.setDizzyTime(currentTime + 750) driver.chef.updateHealth(8) elif event.key.keysym.sym == sdl.K_l: enemies.append( self.createRandomRat(directions, time)) elif event.key.keysym.sym == sdl.K_m: running = False self.next = 'menu' elif event.key.keysym.sym == sdl.K_3: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = driver.scoreBoard.getScore( ) self.next = 'levelThree' return elif event.key.keysym.sym == sdl.K_4: running = False if 'key' in driver.chef.items: driver.chef.items.remove('key') driver.chef.score = driver.scoreBoard.getScore( ) self.next = 'levelFour' elif event.key.keysym.sym == sdl.K_w: # Debug: add a carrot item if 'carrot' not in driver.chef.items: driver.chef.addItem('carrot') else: driver.chef.removeItem('carrot') elif event.key.keysym.sym == sdl.K_z: # place a bomb if 'bomb' in driver.chef.weapons and not driver.chef.placingBomb: driver.chef.setPlacingBomb(True) objects.append( Object( driver.chef.xPos - 75, driver.chef.yPos - 25, 200, 200, 'bomb', driver.chef.textures[2][10], )) driver.chef.weapons.remove('bomb') elif event.key.keysym.sym == sdl.K_x: sound = False for x in range(len(objects) - 1, -1, -1): if objects[x].getTitle() == 'bomb': sound = True tsum = currentTime \ + explosionLife emit = \ self.addEmitter(objects[x].xPos + objects[x].width // 2, objects[x].yPos + objects[x].height // 2, tsum, 'explosion') emit.emit() emitters.append(emit) camera.activateShake( currentTime, 300, 20, 20) for enemy in enemies: if self.withinRange( objects[x], enemy, 100): enemy.updateHealth(-4) enemy.setHurt(True) enemy.setHurtTime(currentTime + 1000) enemy.bump( objects[x]. getAttackingDirection( enemy)) camera.activateShake( currentTime, 200, 3, 3) if self.withinRange( objects[x], driver.chef, 100): driver.chef.updateHealth(-10) driver.chef.bump( objects[x]. getAttackingDirection( driver.chef)) objects.append( Object( objects[x].xPos, objects[x].yPos, 200, 200, 'explosion', driver.chef.textures[2][12], )) objects.remove(objects[x]) if sound: sdl.mixer.playChannel(1, explosionSound, 0) elif event.key.keysym.sym == sdl.K_e: tsum = currentTime + explosionLife emit = self.addEmitter( driver.chef.xPos + driver.chef.getWidth() // 2, driver.chef.yPos + driver.chef.getHeight() // 2, tsum, 'explosion') emit.emit() emitters.append(emit) elif event.key.keysym.sym == sdl.K_b: driver.chef.addWeapon('bomb') elif event.key.keysym.sym == sdl.K_p: paused = True keyPress = left or right or up or down # based on the keys pressed down set the driver.chef's direction if keyPress is True: driver.chef.updateDirection(up, down, left, right) # if items are "used" aka past their onscreen time, remove them for x in range(len(objects) - 1, -1, -1): if objects[x].used is True: objects.remove(objects[x]) # if bombs are planted, make sure to chef for enemies inside for x in range(len(objects)): if objects[x].title == 'bomb': if self.objectsWithinRange(objects[x], driver.chef, enemies, 100): objects[x].texture = \ driver.chef.textures[2][11] else: objects[x].texture = \ driver.chef.textures[2][10] # pressing space on keydown will place the player into attacking state if space and currentTime > driver.chef.getAttackingTime(): if driver.chef.getEnergy() > 0: driver.chef.setAttacking(True) driver.chef.setAttackingTime( currentTime + 300) # attacking animation with be 1s driver.chef.updateEnergy(-1) sdl.mixer.playChannel(-1, woosh, 0) else: # If you try to attack when you're out of energy, become dizzy for .5s driver.chef.setDizzy(True) driver.chef.setDizzyTime(currentTime + 500) # if the player presses "space" the driver.chef will go into attacking mode # which overrides other animations except getting hit if currentTime > driver.chef.getAttackingTime() \ or driver.chef.getDizzy(): driver.chef.setAttacking(False) else: driver.chef.setAttacking(True) driver.chef.setEnergyRegenTime(currentTime + 1000) # if the player is not attacking, and less than 8 pizza slices, and not dizzy, and 3s from last time attacked, give energy if not space and driver.chef.getEnergy() < 8 \ and not driver.chef.getDizzy() and currentTime \ > driver.chef.getEnergyRegenTime(): driver.chef.updateEnergy(1) driver.chef.setEnergyRegenTime(currentTime + 1000) # if driver.chef not attacking or dizzy, and on same tile as object, pick it up if currentTime > driver.chef.getAttackingTime() \ and not driver.chef.getDizzy(): for obj in objects: if self.intersects(driver.chef, obj): if obj.getTitle() == 'pizza' \ and driver.chef.getEnergy() < 8: driver.chef.updateEnergy(1) objects.remove(obj) if not driver.chef.inGottenItems('pizza'): instr = True driver.chef.setGottenItems('pizza') item = 'pizza' if obj.getTitle() == 'heart' \ and driver.chef.getHealth() <= 8: driver.chef.updateHealth(1) objects.remove(obj) if not driver.chef.inGottenItems('tomato'): instr = True driver.chef.setGottenItems('tomato') item = 'tomato' if obj.getTitle() == 'carrot': driver.chef.addItem('carrot') objects.remove(obj) if not driver.chef.inGottenItems('carrot'): instr = True driver.chef.setGottenItems('carrot') item = 'carrot' if obj.getTitle() == 'ladles': driver.chef.addWeapon('ladles') objects.remove(obj) if not driver.chef.inGottenItems('ladles'): instr = True driver.chef.setGottenItems('ladles') item = 'ladles' if obj.getTitle() == 'graters': driver.chef.addWeapon('graters') if 'ladles' in driver.chef.weapons: driver.chef.weapons.remove('ladles') if not driver.chef.inGottenItems( 'graters'): instr = True driver.chef.setGottenItems('graters') item = 'graters' objects.remove(obj) if obj.getTitle() == 'bombObject' \ and driver.chef.getNumBombs() <= 5: driver.chef.addWeapon('bomb') objects.remove(obj) if not driver.chef.inGottenItems('bsv'): instr = True driver.chef.setGottenItems('bsv') item = 'bsv' # make sure the rats aren't invulnable after a set time for enemy in enemies: if currentTime > enemy.getHurtTime(): enemy.setHurt(False) enemy.resetDamageChange() # handling structure interactions for structure in structures: if structure.identity is 'pantry' \ and structure.triggered is False: structure.xPos *= 50 structure.yPos *= 50 structure.yPos += 20 if self.intersects(driver.chef, structure): if structure.visible is False: structure.changeVisibility() else: if structure.visible: structure.changeVisibility() structure.xPos /= 50 structure.yPos -= 20 structure.yPos /= 50 if structure.visible: if use is True: structure.triggerAction() if structure.hasKey is True: driver.chef.hasKey = True else: randNum = random.randint(1, 10) if randNum is 1: objects.append( Object( structure.xPos * 50, structure.yPos * 50 + 50, 50, 50, 'heart', objectTextures[1], )) elif randNum > 1 and randNum <= 4: objects.append( Object( structure.xPos * 50, structure.yPos * 50 + 50, 50, 50, 'pizza', objectTextures[0], )) # make sure the rats aren't attacking after a set time for enemy in enemies: if currentTime > enemy.getAttackingTime(): enemy.setAttacking(0) # if the invulnability expired set hit back to true if currentTime > driver.chef.getCanBeHitTime(): driver.chef.setCanBeHit(True) # if the dizzyness expired, set dizzy back to false if currentTime > driver.chef.getDizzyTime(): driver.chef.setDizzy(False) driver.chef.resetDamageChange() # checking whether rats are hitting the driver.chef for enemy in enemies: if self.intersects(driver.chef, enemy): # if sdl.hasIntersection(enemy.getRect(), driver.chef.getRect()): # if intersection different things happend depending on if your attacking if driver.chef.getAttacking(): if not enemy.getHurt( ): # if the rat can take damage if 'graters' in driver.chef.weapons: enemy.updateHealth(-2) self.genericHit() sdl.mixer.playChannel(-1, graterHit, 0) else: enemy.updateHealth(-1) self.genericHit() sdl.mixer.playChannel(-1, ladleHit, 0) enemy.goOppositeDirection(currentTime) enemy.setHurt(True) enemy.setHurtTime(currentTime + 1000) enemy.bump( driver.chef.getAttackingDirection( enemy)) else: if driver.chef.getCanBeHit(): if not enemy.getHurt( ): # hurt rats can't damage us driver.chef.setCanBeHit(False) driver.chef.setDizzy(True) driver.chef.setCanBeHitTime( currentTime + 3000) driver.chef.setDizzyTime(currentTime + 750) driver.chef.bump( enemy.getAttackingDirection( driver.chef) ) # finds out what direction the rats should attack from enemy.setAttackingTime(currentTime + 500) self.playHitSound() driver.chef.updateHealth(-1) camera.activateShake( currentTime, 300, 5, 5) enemy.goOppositeDirection(currentTime) # if rat gets hit five times by bumping, it dies for enemy in enemies: if enemy.health <= 0: int = random.randint(1, 6) if int is 1: objects.append( Object( enemy.xPos + enemy.getWidth() // 2, enemy.yPos + enemy.getHeight() // 2, 50, 50, 'heart', objectTextures[1], )) elif int > 1 and int <= 3: objects.append( Object( enemy.xPos, enemy.yPos, 50, 50, 'pizza', objectTextures[0], )) elif int > 3 and int <= 6: objects.append( Object( enemy.xPos, enemy.yPos, 50, 50, 'bombObject', objectTextures[4], )) tsum = currentTime + explosionLife emit = self.addEmitter( enemy.xPos + enemy.getWidth() // 2, enemy.yPos + enemy.getHeight() // 2, tsum, 'rat') emit.emit() emitters.append(emit) enemies.remove(enemy) sdl.mixer.playChannel(-1, ratDyingSound, 0) driver.scoreBoard.updateScore(5000) # score goes down at a set rate, encourages speed driver.scoreBoard.updateScore(-1 * dt) # update driver.chef position based on what keys are being pressed # down if keys are pressed down and he is not off the screen # also based on if driver.chef collides into stuff driver.chef.updatePosition(accumulator, map, keyPress) self.chefNode = driver.chef.getNode(self.navGraph) # boing sound if the driver.chef hits the wall # if self.checkCollisions(driver.chef, objects): # sdl.mixer.playMusic(boingSound, 1) # update enemy positions based on direction # if currentTime >= 10000: # if r is True: for enemy in enemies: enemy.updatePosition(accumulator, map, self.navGraph, self.chefNode, currentTime) accumulator -= framerate camera.display(currentTime, dt, keyPress, currentTime) sdl.renderPresent(driver.renderer)
def getSeconds(): return sdl.getTicks() / 1000.
def main(): event = sdl.Event() sdl.init(sdl.INIT_VIDEO) # Initialize test framework # state = SDLTest_CommonCreateState(argv, sdl.INIT_VIDEO) # if not state: # return 1 # for (i = 1; i < argc;) { # # consumed = SDLTest_CommonArg(state, i) # if consumed == 0: # sdl.Log("Usage: %s %s\n" % (argv[0], SDLTest_CommonUsage(state))) # return 1 # i += consumed # if not SDLTest_CommonInit(state): # quit(2) drawstates = [DrawState()] for i in range(len(drawstates)): drawstate = drawstates[i] drawstate.window = sdl.createWindow("Scale %d" % i, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, sdl.WINDOW_SHOWN) drawstate.renderer = sdl.createRenderer(drawstate.window, -1, 0) drawstate.sprite = LoadTexture(drawstate.renderer, "icon.bmp", True) drawstate.background = LoadTexture(drawstate.renderer, "sample.bmp", False) if not drawstate.sprite or not drawstate.background: quit(2) rc, format, access, w, h = sdl.queryTexture(drawstate.sprite) drawstate.sprite_rect.w = w drawstate.sprite_rect.h = h drawstate.scale_direction = 1 # Main render loop frames = 0 then = sdl.getTicks() done = 0 while not done: # Check for events frames += 1 while sdl.pollEvent(event): if event.type == sdl.QUIT: done = 1 for i in range(len(drawstates)): if not drawstates[i].window: continue Draw(drawstates[i]) # Print out some timing information now = sdl.getTicks() if now > then: fps = (frames * 1000) / (now - then) sys.stderr.write("%2.2f frames per second\n" % (fps)) # TODO for x in drawstates: free stuff quit(0) return 0
def run(): frames = 0 last_ticks = 0 sdl.init(sdl.INIT_VIDEO) window = sdl.createWindow( "TMX Render Example", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 1280, # ignored for fs desktop 720, # ignored for fs desktop sdl.WINDOW_SHOWN) renderer = sdl.createRenderer(window, -1, flags=0) window = sdl.Window(window) width, height = window.getWindowSize() # Logical size: width = width // 2 height = height // 2 renderer.renderSetLogicalSize(width, height) try: map = tmxrender.TMXRender(sys.argv[1]) except: sys.stderr.write("Pass the path of a .tmx map as the first argument.") raise # Load the map's image data map.load(renderer) pos = [0, 0] k_up, k_down, k_left, k_right = (sdl.SCANCODE_UP, sdl.SCANCODE_DOWN, sdl.SCANCODE_LEFT, sdl.SCANCODE_RIGHT) class Hero(object): def __init__(self): self.x = 0 self.y = 0 hero = Hero() event = sdl.Event() running = True while running: renderer.setRenderDrawColor(0, 0, 0, 255) renderer.renderClear() while event.pollEvent(): if event.type == sdl.QUIT: running = False break elif event.type == sdl.KEYDOWN: keysym = event.key.keysym if (event.key.keysym.scancode == sdl.SCANCODE_ESCAPE or event.key.keysym.sym == sdl.K_q): running = False break # Movement with arrow keys keystate, keystate_length = sdl.getKeyboardState() hero.x += (-1 * keystate[k_left]) + (1 * keystate[k_right]) hero.y += (-1 * keystate[k_up]) + (1 * keystate[k_down]) # Draw the map under the centered hero position pos[0] = int(hero.x - width / 2) pos[1] = int(hero.y - height / 2) map.render(renderer, pos) renderer.renderPresent() # Keep track of frame rate frames += 1 ticks = sdl.getTicks() if ticks - last_ticks > 1000: last_ticks = ticks print("Frames: %s" % frames) frames = 0