def chooseVictim(self): opponents = self.findPossibleVictims() if opponents: victim = opponents[0] events.post('RobRequest', self, victim) else: events.post('SkipRobRequest', self)
def placeOnTile(self, tile): if self._tile: self._tile.robber = None self._tile = tile self._tile.robber = self print 'Robber placed:', tile events.post('RobberPlaced', self)
def run(self): self.lastTick = time.time() while self.keepGoing: now = time.time() delta = now - self.lastTick self.lastTick = now events.post("Tick", delta)
def __init__(self): pips = [Pip(i) for i in [5,2,6,3,8,10,9,12,11,4,8,10,9,4,5,6,3,11]] random.shuffle(terrainClasses) self.tiles = [] self.robber = Robber() mapmodel.build() for i, cls in enumerate(terrainClasses): tile = mapmodel.allTiles[Board.spiralWalk[i]-1] tile.graphicalPosition = Board.graphicalPositions[i] tile.terrain = cls() if cls == Desert: self.robber.placeOnTile(tile) else: tile.pip = pips.pop(0) self.tiles.append(tile) self.ports = [Port((None,3)), Port((None,3)), Port((None,3)), Port((None,3)), Port((Grain,2)), Port((Brick,2)), Port((Stone,2)), Port((Sheep,2)), Port((Wood,2))] random.shuffle(self.ports) self.layOutPorts() events.post('BoardCreated', self)
def _instakill(player, other): if 'instakill' in other: player.add_attributes(attributes.Dead) events.post(consts.ENTITY_DEATH, dead=player) events.post(consts.HEALTH_CHANGED, target=player, previous=player.health, new=0) player.health = 0
def onPlayVictoryCardRequest(self, player, victoryCardClass): if player != self or self != game.state.activePlayer: return foundCard = None for vcard in self.victoryCards: if isinstance(vcard, victoryCardClass): foundCard = vcard break if not foundCard: events.post('Error', 'Player does not have requested card.') return if not hasattr(foundCard, 'action'): events.post('Error', 'Card has no associated action.') return if self.victoryCardPlayedThisTurn: events.post('Error', 'Only one victory card per turn.') return if foundCard in self.victoryCardsBoughtThisTurn: events.post('Error', 'Victory card was bought this turn') return if (game.state.stage == Stages.preRoll and not victoryCardClass == Soldier): events.post('Error', 'Only soldier cards during pre-roll.') return self.victoryCardPlayedThisTurn = True self.victoryCards.remove(foundCard) self.playedVictoryCards.append(foundCard) foundCard.action(self)
def onMonopoly(self, player, cardClass): if player == self: return stolen = [card for card in self.cards if isinstance(card, cardClass)] for card in stolen: self.cards.remove(card) events.post('MonopolyGive', self, player, stolen)
def __call__(self, event): if 'user_controllable' not in self.entity: return if 'dead' in self.entity: return self.entity.amoeba_physics.damage(1, self.entity) if event.type == pygame.MOUSEBUTTONDOWN: self.start = event.pos self.circles = self.entity.circles if event.type == pygame.MOUSEBUTTONUP: if self.start is None: return v = Vector(*event.pos) - Vector(*self.start) cap = 150 v.magnitude = v.magnitude if v < cap else cap v.magnitude *= 0.01 for circle in self.circles: circle.acceleration -= v self.start = None events.post(consts.OBJECT_FLUNG, target=self.entity)
def handle_collision(event): player = None other = None if event.entity1.affiliation == 'player1': player, other = event.entity1, event.entity2 elif event.entity2.affiliation == 'player1': other, player = event.entity1, event.entity2 else: return # remove enemy from screen if other.affiliation == 'enemy': if len(player.circles) > len(other.circles): player.amoeba_physics.eat(player, other) other.add_attributes(attributes.RemoveMe) else: other.amoeba_physics.eat(other, player) player.add_attributes(attributes.RemoveMe) player.add_attributes(attributes.Dead) # events.post(consts.ENTITY_DEATH, dead=player) if 'instakill' in other: _instakill(player, other) elif 'size_increase_powerup' in other: _size_increase_powerup(player, other) elif 'increase_health' in other: _increase_health(player, other) elif 'inflicts_damage' in other: pass # _inflicts_damage(player, other) elif 'trigger' in other: events.post(consts.TRIGGER, origin=other, tag=other.trigger)
def onTick(self): # Handle Input Events for event in pygame.event.get(): ev = None if event.type == QUIT: ev = events.Quit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: # Hit Shift-ESC or Ctrl-ESC to go to the debugger # otherwise ESC will quit the game if event.mod and (event.mod & KMOD_SHIFT or event.mod & KMOD_CTRL): print "event mod", event.mod import pdb pdb.set_trace() else: ev = events.Quit() else: ev = ("KeyDown", event.key, event.unicode, event.mod) elif event.type == MOUSEBUTTONDOWN: if event.button == 1: events.post("MouseLeftDown", pos=event.pos) elif event.type == MOUSEBUTTONUP: if event.button == 1: events.post("MouseLeftUp", pos=event.pos) elif event.type == MOUSEMOTION: events.post("MouseMotion", pos=event.pos, buttons=event.buttons) if ev: if isinstance(ev, tuple): events.post(*ev) else: events.post(ev)
def onChooseTwoCardsRequest(self, player, cardClasses): if player == self.activePlayer: cards = [] for cls in cardClasses: card = cls() cards.append(card) player.cards.append(card) events.post('ChooseTwoCards', player, cards)
def onMouseLeftDown(self, pos): if self.hintlighted and self.collides(pos): # TODO: there is a bug here. # If the user interface sends two TileClicked events immediately # after another (such as if the user clicks on an overlap), the # event manager will get two of these and place the robber twice # consider making a special queue for UI events like clicks events.post("TileClicked", self.tile)
def run_saved_game(): import saved_game saved_game.load() spinner = pygameview.CPUSpinnerController() kbController = pygameview.KeyboardController() pygameView = pygameview.PygameView() pygameview.humanPlayer = catan.game.players[-1] events.post('RefreshState') spinner.run()
def __call__(self, event): if event.type == pygame.MOUSEMOTION: if self.is_within(event.pos): self.highlight_delta = 1 else: self.highlight_delta = -1 if event.type == pygame.MOUSEBUTTONDOWN: if self.is_within(event.pos): events.post(consts.CHANGE_FRAME, frame=self.next_frame, level=self.level)
def add(self, item): if isinstance(item, VictoryCard): self.victoryCards.append(item) self.victoryCardsBoughtThisTurn.append(item) events.post('PlayerDrewVictoryCard', self, item) else: item.owner = self self.items.append(item) self.activeItem = item events.post('PlayerPlacing', self, item)
def onMouseLeftDown(self, pos): if not self.rect.collidepoint(pos): return self.dirty = True innerPos = vect_diff(pos, self.topleft) for button in self.addButtons.values(): if button.rect.collidepoint(innerPos): button.click() if self.dButton.rect.collidepoint(innerPos): if self.dButton.hintlighted: events.post('MonopolyRequest', self.player, self._chosen)
def onRobRequest(self, thief, victim): if thief == self.activePlayer: if victim.cards: card = random.choice(victim.cards) victim.cards.remove(card) thief.cards.append(card) events.post('Rob', thief, victim, card) if self.stage == Stages.postRollChooseVictim: self.stage = Stages.playerTurn elif self.stage == Stages.preRollChooseVictim: self.stage = Stages.preRoll
def _inflicts_damage(player, other): if player.health <= 0: player.add_attributes(attributes.Dead) events.post(consts.ENTITY_DEATH, dead=player) else: events.post( consts.HEALTH_CHANGED, target=player, previous=player.health, new=player.health - other.inflicts_damage) player.health -= other.inflicts_damage
def onProposeTrade(self, player, toGive, toTake): if player == self: self.offer = [] for cls, howMany in toGive.items(): for card in self.cards: if card.__class__ == cls and card not in self.offer: self.offer.append(card) howMany -= 1 if howMany == 0: break if howMany != 0: events.post('Error', 'Player does not have enough cards') self.wants = toTake
def onMouseLeftDown(self, pos): if not self.rect.collidepoint(pos): return self.dirty = True innerPos = vect_diff(pos, self.topleft) for button in self.addButtons.values() + self.removeButtons.values(): #print 'button', button, button.rect if button.rect.collidepoint(innerPos): print 'button %s sees mouse inner' % button button.click() if self.dButton.rect.collidepoint(innerPos): if self.dButton.hintlighted: events.post('DiscardRequest', self.player, self._discards)
def onDiscardRequest(self, player, discards): if self != player: return print 'player %s discards %d from %d' %\ (self, len(discards), len(self.cards)) if not all([card in self.cards for card in discards]): print 'Player tried to discard cards that he did not own' return if not len(discards) == len(self.cards)/2: print 'Player tried to discard the wrong amout of cards' return for card in discards: self.cards.remove(card) events.post('Discard', self)
def _size_increase_powerup(player, other): events.post_delayed_event( consts.REMOVE_POWERUP, 10, player=player, original_health=player.health, increase = other.size_increase_powerup) events.post( consts.HEALTH_CHANGED, target=player, previous=player.health, new=player.health + other.size_increase_powerup) player.health += other.size_increase_powerup other.add_attributes(attributes.RemoveMe) other.size_increase_powerup = 0
def onDiceRollRequest(self, player): import random if debugRolls: a,b = debugRolls.pop(0) else: a = random.randrange(1,7) b = random.randrange(1,7) self.lastRoll = (a,b) if (player != game.state.activePlayer or game.state.stage not in [Stages.preRoll] ): print 'illegal dice roll request', player else: print 'Dice roll:', a, b events.post('DiceRoll', a, b)
def doPlacement(self): if isinstance(self.activeItem, Settlement): corners = self.findFreeCornersForSettlement() c = corners[0] c.add(self.activeItem) elif isinstance(self.activeItem, Road): edges = self.findFreeEdgesOfSettlement(self.latestItem) e = edges[0] e.add(self.activeItem) elif isinstance(self.activeItem, Robber): tiles = self.findFreeTilesForRobber() t = tiles[0] events.post('RobberPlaceRequest', self, t) self.latestItem = self.activeItem self.activeItem = None
def wrappedfn(*args): if not game: raise ValueError('Game must be initialized before a function' ' decorated with allowedDuring can be called') #print 'called ', fn #print 'supposed to be in', allowedStages if game.state.stage not in allowedStages: print 'EVENT NOT ALLOWED', fn.__name__, game.state.stage events.post('EventNotAllowedAtThisStage', fn.__name__, game.state.stage, allowedStages) return #raise EventNotAllowedAtThisStage(fn.__name__, # game.state.stage, # allowedStages) retval = fn(*args) return retval
def onStageChange(self, newStage): print self, 'sees new stage', newStage self.offer = [] self.wants = [] if catan.game.state.stage == Stages.sevenRolledDiscard: self.discard() if catan.game.state.activePlayer != self: return if catan.game.state.stage == Stages.preRoll: self.rollDice() if catan.game.state.stage == Stages.playerTurn: events.post('TurnFinishRequest', self) if catan.game.state.stage in [Stages.preRollChooseVictim, Stages.postRollChooseVictim]: self.chooseVictim()
def handle_removed_powerups(event): current_health = event.player.health if current_health < event.original_health: return prev = event.player.health event.player.health -= event.increase if event.player.health < event.original_health: event.player.health = event.original_health events.post( consts.HEALTH_CHANGED, target=event.player, previous=prev, new=event.player.health) print 'done', event.player.health
def parse(items, threshold): for item in items: if item['sentiment'][0] > 0: item['type'] = 'buy' item['confidence'] = item['sentiment'][0] * 100 if item['sentiment'][0] < 0: item['type'] = 'sell' item['confidence'] = item['sentiment'][0] * -100 if item['sentiment'][0] == 0: item['confidence'] = 0 print(item['timestamp'],item['source'],item['type'],item['confidence'],item['description']) if item['confidence'] > threshold: print('POSTED') #print(item['timestamp'],item['source'],item['type'],item['confidence'],item['description']) if LIVE: events.post(**item)
def onStageChange(self, newStage): if game.state.stage == Stages.setup: self.board = Board() if game.state.stage == Stages.cardHarvest: for tile in self.board.tiles: if tile.pip == None: continue if tile.pip.value == sum(self.dice.lastRoll): cardClass = tile.terrain.getCardClass() for corner in tile.corners: if not corner.settlement: continue owner = corner.settlement.owner if isinstance(corner.settlement, City): # Cities get 2 cards cards = [cardClass(), cardClass()] else: # Regular settlements get 1 card cards = [cardClass()] events.post('Harvest', cards, tile, owner) events.post('CardHarvestOver')
def main(): global humanPlayer spinner = CPUSpinnerController() kbController = KeyboardController() pygameView = PygameView() catan.init() from cpu_player_minimal import CPUPlayer events.post("PlayerJoin", CPUPlayer(1)) events.post("PlayerJoin", CPUPlayer(2)) events.post("PlayerJoin", CPUPlayer(3)) humanPlayer = catan.HumanPlayer(4) events.post("PlayerJoin", humanPlayer) spinner.run()