def update(self, time_passed): """Update methods does: 1) Check for mouse hover on the LevelExit area; if this is true, the sprite alpha value is changed and the area became a little visibile 2) Check for hero movement on the exit. If this is true then raise the LEVEL_CHANGE_EVENT event """ GameSprite.update(self, time_passed) if cblocals.global_controlsEnabled: # Mouse curson if self.physical_rect.collidepoint(pygame.mouse.get_pos()): if not self._focus: self.image.set_alpha(50) utils.changeMouseCursor(cblocals.IMAGE_CURSOR_CHANGELEVEL_TYPE) utils.drawCursor(cblocals.screen, pygame.mouse.get_pos()) self._focus = True else: if self._focus: self.image.set_alpha(0) if cblocals.global_mouseCursorType==cblocals.IMAGE_CURSOR_CHANGELEVEL_TYPE: utils.changeMouseCursor(None) self._focus = False # Change level if self.to_level and self.physical_rect.colliderect(self.currentLevel.hero.physical_rect) and \ self.currentLevel.timeIn > 5.: event = pygame.event.Event(cblocals.LEVEL_CHANGE_EVENT, {'exit':self, }) pygame.event.post(event)
def update(self, time_passed): """Update method of pygame Sprite class. A non playing character check his own AI here. """ GameSprite.update(self, time_passed) if self.brain: self.brain.think(time_passed)
def __init__(self, position, size, *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) srf = self.generateEmptySprite(size, alpha=0) if cblocals.DEBUG: srf.set_alpha(150) self.image = srf
def __init__(self, position, size, *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self.x, self.y = position self.rect.midbottom = position self._image = None self._timeCollected = 0 self._nextLightChange = randomTime() self._phase = 1
def update(self, time_passed): """The update must do 2 task: follow the character and disappear after a while. The text remains visible some times, based on text length. """ self.position = self.toLevelCoordinate() GameSprite.update(self, time_passed) self._time_left -= time_passed if self._time_left <= 0: self.endSpeech()
def kill(self, corpse=True): """Kill the character, removing it from all groups and draw a dead corpse. As far as the Character objects are also UniqueObject, we need also to unregister a killed sprite from the object_registry. @corpse: True (default) for generating the dead corpse; with False the Sprite simply disappear """ GameSprite.kill(self) cblocals.object_registry.unregister(self.UID()) if corpse: self.currentLevel.generateDeadSprite(self)
def __init__(self, position, size, *containers): """The position used is the lighting strike point of the ground (midbottom)""" GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self.x, self.y = position self.rect.midbottom = position self._image = None self._timeCollected = 0 self._nextLightChange = randomTime() self._phase = 1
def __init__(self, position, size, exit_to, start_position, firstNavPoint, topleft, *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self.image = self.generateEmptySprite(size, alpha=0, fillWith=(240,240,240)) self._focus = False # Exit data self.to_level = exit_to self.start_position = start_position self.firstNavPoint = firstNavPoint self.nextTopleft = topleft
def __init__(self, character, bkcolor=(255, 255, 255, 0), textcolor=(0, 0, 0, 0)): GameSprite.__init__(self) self._character = character self.bkcolor = bkcolor self.textcolor = textcolor self._text = "" self._text_queue = [] self._time_left = 0 self._last_charX = self._last_charY = None self._image = None
def __init__(self, level, text=None, type=LEVEL_TEXT_TYPE_NORMAL): GameSprite.__init__(self, level['level_text']) self._text = [] self._type = type self.level = level self._image = None self.rect = self._getRect() self.position = self.rect.midbottom if text: self.addText(text) self.colophon = False
def update(self, time_passed): """Update method of pygame Sprite class. check if the image must be changed here. """ GameSprite.update(self, time_passed) self._timeCollected-= time_passed if self._timeCollected<=0: self._timeCollected = self._nextRandomWaveTime() # More time for animation phase 0 if self._wave_phase==3: self._timeCollected*=3 self._image = None
def generateDeadSprite(self, corpse): """Using a character (commonly... very commonly... a DEAD ones!), generate a corpse. Corpse is added to a group called "dead". """ sprite = GameSprite() sprite.image = utils.getRandomImageFacingUp(corpse.images) curRect = corpse.rect newRect = pygame.Rect( curRect.topleft, sprite.image.get_rect().size ) newRect.midbottom = corpse.position sprite.rect = newRect self["dead"].add(sprite) sprite.addToGameLevel(self, corpse.position)
def __init__(self, position, size, fireOnCollistionWith=(), *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self.position = position srf = self.generateEmptySprite(size, alpha=0) if cblocals.DEBUG: srf.set_alpha(100) srf.fill( (255,255,255) ) self.image = srf # Other important trigger's members self.disableTriggerAfterFire = True self.fireOnCollistionWith = fireOnCollistionWith
def __init__(self, name, img, containers, realSize=cblocals.TILE_IMAGE_SIZE, speed=150., attackTime=0.5, afterAttackRestTime=0.2, weaponInAndOut=False, sightRange=200,): GameSprite.__init__(self, *containers) Stealth.__init__(self) Warrior.__init__(self, attackTime, afterAttackRestTime) self._x = self._y = 0 self.rect = pygame.Rect( (self.x, self.y), (cblocals.TILE_IMAGE_SIZE) ) self.name = name self.characterType = "Guy" self.experienceLevel = 1 self._brain = None self._presentationBrain = PresentationStateMachine(self) self._load_images(img, weaponInAndOut) self.lastUsedImage = 'head_south_1' self._stepTime = 0 self._mustChangeImage = False self.direction = self._lastUsedDirection = cblocals.DIRECTION_S self._isMoving = False self.maxSpeed = self._speed = speed self.sightRange = sightRange self.rest_time_needed = .3 self.side = 'Cheese Boys' self._enemyTarget = None self.navPoint = NavPoint(self) self.heading = None # From where a succesfull attack is coming self.damageHeading = None self.size = realSize self._heatRectData = (5, 5, 10, 15) self.hitPoints = self.hitPointsLeft = 20 self._baseAC = 1 self._th0 = None self._speech = SpeechCloud(self) # *** Pathfinding *** self.pathfinder = None # This is inited only after the call onto addToGameLevel self.afterInit()
def update(self, time_passed): """Update method of pygame Sprite class. Check if the image must be changed here. """ GameSprite.update(self, time_passed) self._timeCollected+= time_passed if self._timeCollected>=self._nextLightChange: self._timeCollected = 0 self._nextLightChange = randomTime() self._phase+=1 self._image = None if self._phase==3: self.kill()
def __init__(self, position, type, orientation, *containers): """Init the crate. You need specify the type of the crate, that will change the used image, and also the orientation (image can be rotated). @type: a integer number to be appended to the createXX.png filename. @orientation: an integer from 0 to 3, that rotate the image 90*value degree counterclockwise. """ GameSprite.__init__(self, *containers) image = utils.load_image("crate%s.png" % type, directory="miscellaneous") if orientation: image = pygame.transform.rotate(image, 90*orientation) self.image = image self.position = position self.rect = pygame.Rect(position, image.get_size()) self.rect.midbottom = position
def image(self): """Draw the flashing surfaces""" if self._image: # memoized image return self._image phase = self._phase if phase==1: self.currentLevel.shadow = False self._image = GameSprite.generateEmptySprite(self.rect.size, alpha=245, fillWith=(255,255,255)) return self._image if phase==2: self._image = GameSprite.generateEmptySprite(self.rect.size, alpha=245, fillWith=(0,0,0)) return self._image if phase==3: self._image = GameSprite.generateEmptySprite(self.rect.size, alpha=245, fillWith=(255,255,255)) return self._image
def update(self, time_passed): """TODO: open/close animation will be handled here""" GameSprite.update(self, time_passed) if cblocals.global_controlsEnabled: # Mouse curson if self.collide_rect.collidepoint(pygame.mouse.get_pos()): if not self._focus: self.image.set_alpha(200) utils.changeMouseCursor(cblocals.IMAGE_CURSOR_OPENDOOR_TYPE) utils.drawCursor(cblocals.screen, pygame.mouse.get_pos()) self._focus = True else: if self._focus: self.image.set_alpha(255) if cblocals.global_mouseCursorType==cblocals.IMAGE_CURSOR_OPENDOOR_TYPE: utils.changeMouseCursor(None) self._focus = False
def update(self, time_passed): """Update method of pygame Sprite class. Overrided the one in Character main class because we need to handle user controls here. """ GameSprite.update(self, time_passed) if cblocals.global_lastMouseLeftClickPosition or cblocals.global_lastMouseRightClickPosition: self.stopThinking() if self._brain.active_state and self._brain.active_state.name!="controlled": return Character.update(self, time_passed) pressed_keys = pygame.key.get_pressed() # update stealth level if pressed_keys[K_LSHIFT] and self.canStealthAgain() and not self.stealth: self.stealth = True elif not pressed_keys[K_LSHIFT] and self.stealth: self.stealth = False # Check for mouse actions setted if cblocals.global_lastMouseLeftClickPosition: self.navPoint.set(self.currentLevel.transformToLevelCoordinate(cblocals.global_lastMouseLeftClickPosition)) cblocals.global_lastMouseLeftClickPosition = () if cblocals.global_lastMouseRightClickPosition and not self.isAttacking(): attackHeading = Vector2.from_points(self.position, self.currentLevel.transformToLevelCoordinate(cblocals.global_lastMouseRightClickPosition)) attackHeading.normalize() cblocals.global_lastMouseRightClickPosition = () # Right click on a distant enemy will move the hero towards him... if self.seeking: # enable the hero brain enemy = self.seeking print "Seeking %s" % enemy.name self.enemyTarget = enemy self._brain.setState("hunting") # ...or attack (even if moving)... else: self.setAttackState(attackHeading) if pygame.key.get_pressed()[K_z] and not self.stealth: self._brain.setState("retreat") if self.navPoint: self.moveBasedOnNavPoint(time_passed) if self._attackDirection: self.updateAttackState(time_passed)
def update(self, time_passed): """Check if something is touching the trigger, and if the trigger must be fired. """ GameSprite.update(self, time_passed) collide_rect = self.collide_rect for member in self.fireOnCollistionWith: if member is self: continue if hasattr(member, 'sprites'): # is a group for sprite in member.sprites(): if sprite.collide_rect.colliderect(collide_rect): self.fireTrigger(sprite) return else: # is a sprite if member.collide_rect.colliderect(collide_rect): self.fireTrigger(member) return
def __init__(self, position, length, orientation, *containers): """Init the gate. Just give the length on the gate and the orientation. 0 for horizontal, 1 for vertical. To open the gate set the open_condition tuple attribute. The tuple contains an object (commonly a GameSprite) and an attribute name, that need to be tested on this object. The open_condition attribute must be evaluated to True, or must be a callable that return True. In any one of this case, the gate will open on collision with the hero. You can also use the open_condition_reverse_flag to negate the condition needed to open the gate (not True but False). """ GameSprite.__init__(self, *containers) self.length = self.total_length = length self.width = int(length/20) self.orientation = orientation self.position = position self._initGate() self.opened = False self.isOpen = False self._focus = False self.open_condition = () # Negate condition for opening self.open_condition_reverse_flag = False
def __init__(self, position, size, *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self.image = utils.load_image("codigoro-sign.png", "miscellaneous")
def __init__(self, position, size, *containers): GameSprite.__init__(self, *containers) self.x, self.y = position self.rect = pygame.Rect(position, size) self.image = utils.load_image("dark-large-stain.png", "miscellaneous")
def game(): clock = pygame.time.Clock() screen = cblocals.screen hero = character.PlayingCharacter("Boscolo", ("hero_sword1_vest1.png","hero_vest1.png"), (), realSize=(18,25), weaponInAndOut=True, sightRange=300) hero.setBrain(HeroStateMachine) hero.setCombatValues(2, 13) level = loadLevelByName("The South Bridge", hero) level.enablePresentation('funny-intro') pygame.display.set_caption("Cheese Boys (alpha release) %s - %s" % (cblocals.__version__, level.name)) console_area = pygame.Surface( cblocals.CONSOLE_SCREEN_SIZE, flags=SRCALPHA|HWSURFACE, depth=32 ) console_area.set_alpha(255) console_area.fill( (20,20,20) ) console_area.blit(cblocals.default_font_big.render("This will be the", True, (255, 255, 255)), (2,0) ) console_area.blit(cblocals.default_font_big.render("console/command", True, (255, 255, 255)), (2,20) ) console_area.blit(cblocals.default_font_big.render("area", True, (255, 255, 255)), (2,40) ) charas = level['charas'] enemies = level['enemies'] physical = level['physical'] tippable = level['tippable'] speech = level['speech'] while True: # ******* EVENTS LOOP BEGIN ******* for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) if event.type==KEYDOWN: pressed_keys = pygame.key.get_pressed() if not level.presentation and pressed_keys[K_0]: hero.shout("Hey!") # ******* DEBUG ******* if pressed_keys[K_d] and pressed_keys[K_LSHIFT]: import pdb;pdb.set_trace() elif pressed_keys[K_d]: level.computeGridMap() print "\n" print level.grid_map elif pressed_keys[K_c]: print str(hero.navPoint.compute_path()) # ******* END DEBUG ******* if level.presentation is not None: if pressed_keys[K_RIGHT]: cblocals.game_speed = cblocals.game_speed*2 logging.info("Game speed changed to %s" % cblocals.game_speed) elif pressed_keys[K_LEFT] and cblocals.game_speed>1.: cblocals.game_speed = cblocals.game_speed/2 logging.info("Game speed changed to %s" % cblocals.game_speed) if pressed_keys[K_F1]: cblocals.FULLSCREEN = not cblocals.FULLSCREEN screen = handleFullScreen() if pressed_keys[K_ESCAPE]: if level.presentation is not None: # TODO: the ESC key to exit presentation is ugly, just move to a "safe" next part in the presentation... cblocals.game_speed = 128. else: game_over() if cblocals.global_controlsEnabled: # No mouse control during presentations if event.type==MOUSEBUTTONDOWN or cblocals.global_leftButtonIsDown: mouse_pos = pygame.mouse.get_pos() if utils.checkPointIsInsideRectType(mouse_pos, ( (0,0),cblocals.GAME_SCREEN_SIZE ) ): logging.debug("Click on %s (%s on level)" % (mouse_pos, level.transformToLevelCoordinate(mouse_pos))) lb, cb, rb = pygame.mouse.get_pressed() if lb and not cblocals.global_leftButtonIsDown: cblocals.global_leftButtonIsDown = True if lb: cblocals.global_lastMouseLeftClickPosition = mouse_pos elif rb: cblocals.global_lastMouseRightClickPosition = mouse_pos if event.type==MOUSEBUTTONUP: cblocals.global_leftButtonIsDown = False if event.type==cblocals.ATTACK_OCCURRED_EVENT: print "Attack from %s" % event.character.name hit_list = charas.rectCollisionWithCharacterHeat(event.character, event.attack.rect) for hit in hit_list: attackRes = event.character.roll_for_hit(hit) if attackRes in module_th0.TH0_ALL_SUCCESSFUL: print " hit %s" % hit.name hit.generatePhysicalAttackEffect(attacker=event.character, criticity=attackRes) else: print " missed %s" % hit.name if event.type==cblocals.SHOUT_EVENT: logging.info('%s shouted "%s" from position %s.' % (event.character.name, event.text, event.position)) # Sprite collision event if event.type==cblocals.SPRITE_COLLISION_EVENT: GameSprite.manageCollisions(event.source, event.to) # Change current level if event.type==cblocals.LEVEL_CHANGE_EVENT: exit = event.exit level = loadLevelByName(exit.to_level, hero) level.topleft = exit.nextTopleft level.timeIn=0. hero.position = exit.start_position hero.navPoint.set(exit.firstNavPoint) utils.changeMouseCursor(None) charas = level['charas'] enemies = level['enemies'] physical = level['physical'] tippable = level['tippable'] speech = level['speech'] break # Trigger fired if event.type==cblocals.TRIGGER_FIRED_EVENT: trigger = event.trigger sprite_trigging = event.sprite trigger.getResult() # ******* EVENTS LOOP END ******* time_passed_mm = clock.tick() time_passed = time_passed_mm / 1000. * cblocals.game_speed cblocals.game_time = pygame.time.get_ticks() if pygame.key.get_pressed()[K_LCTRL]: time_passed = 0 else: cblocals.playing_time+= time_passed_mm # Level text overlay if level.update_text(time_passed): level.draw(screen) pygame.display.update(pygame.Rect( (0,0), cblocals.GAME_SCREEN_SIZE )) continue # Presentation if level.presentation is not None: commands = level.presentation.update(time_passed) if commands: for command in commands: exec command elif commands is None: logging.info("Presentation: presentation is ended") level.presentation = None level.update(time_passed) level.draw(screen) if cblocals.global_controlsEnabled: level.normalizeDrawPositionBasedOn(hero, time_passed) elif level.screenReferenceSprite: level.normalizeDrawPositionBasedOn(level.screenReferenceSprite, time_passed) if cblocals.DEBUG: physical.drawCollideRect(screen) physical.drawMainRect(screen) physical.drawPhysicalRect(screen) charas.drawNavPoint(screen) charas.drawAttacks(screen, time_passed) if cblocals.DEBUG: charas.drawHeatRect(screen) # points if cblocals.globals['points']: for displayable in [x for x in charas.sprites() if hero.can_see_list.get(x.UID(),False)]: displayable.drawPointsInfos(screen) # textTips if cblocals.globals['text_tips']: for displayable in [x for x in tippable.sprites() if x.getTip() and hero.can_see_list.get(x.UID(),False)]: level.displayTip(screen, displayable) # Mouse cursor hover an enemy # BBB: can I check this in the enemy update method? if cblocals.global_controlsEnabled: for enemy in enemies.sprites(): if enemy.physical_rect.collidepoint(pygame.mouse.get_pos()) and hero.can_see_list.get(enemy.UID(),False): hero.seeking = enemy utils.changeMouseCursor(cblocals.IMAGE_CURSOR_ATTACK_TYPE) break else: if cblocals.global_mouseCursorType==cblocals.IMAGE_CURSOR_ATTACK_TYPE: utils.changeMouseCursor(None) hero.seeking = None if cblocals.global_mouseCursorType: utils.drawCursor(screen, pygame.mouse.get_pos()) # darkness if cblocals.SHADOW: level.blitShadow(screen, hero) # speechs speech.draw(screen) screen.blit(console_area, (cblocals.GAME_SCREEN_SIZE[0],0) ) # fps: if cblocals.SHOW_FPS: utils.show_fps(screen, clock.get_fps()) pygame.display.update()
def __init__(self, position, size, *containers): GameSprite.__init__(self, *containers) self.rect = pygame.Rect(position, size) self._image = None self._wave_phase = cbrandom.choice([0,1,2,3]) self._timeCollected = self._nextRandomWaveTime()
def addToGameLevel(self, level, firstPosition): """Call the GameSprite.addToGameLevel but also init the pathfinder object""" GameSprite.addToGameLevel(self, level, firstPosition) self.pathfinder = PathFinder(self.currentLevel.grid_map_successors, self.currentLevel.grid_map_move_cost, self.currentLevel.grid_map_heuristic_to_goal)
def update(self, time_passed): """Do nothing, but kill me when SPACE is hit""" GameSprite.update(self, time_passed) if pygame.key.get_pressed()[K_SPACE]: self.kill()