def init(numplayers = 2): screen = pygame.display.get_surface() em = EventManager() bg = load.image("select-bg.png") move_snd = load.sound("select-move.wav") confirm_snd = load.sound("select-confirm.wav") confirm_snd.set_volume(0.4) sprites = RenderUpdates() portraits = [PortraitDisplay([20, 20]), PortraitDisplay([20, 320])] names = [NameDisplay([20, 220]), NameDisplay([20, 520])] drops = [DropDisplay([240, 20]), DropDisplay([240, 320])] stats = [StatDisplay([240, 150]), StatDisplay([240, 450])] descs = [DescDisplay([430, 20]), DescDisplay([430, 320])] char_sprites = zip(portraits, names, drops, stats, descs) idx = [0, 0] confirmed = [False, False] for i, sprs in enumerate(char_sprites): if i < numplayers: for spr in sprs: spr.set_char(Character.available[i]) sprites.add(sprs) idx[i] = i init_bg = bg.convert() sprites.update(pygame.time.get_ticks()) sprites.draw(init_bg) wipes.wipe_in(init_bg) init_bg = None # Let us GC it pygame.display.update() sprites.clear(screen, bg) while False in [(c.confirmed or i >= numplayers) for i, c in enumerate(portraits)]: for ev in em.wait(): if ev.type == PLAYER: if ev.key == LEFT: i = (idx[ev.player] - 1) % len(Character.available) idx[ev.player] = i elif ev.key == RIGHT: i = (idx[ev.player] + 1) % len(Character.available) idx[ev.player] = i elif ev.key in [ROT_CC, ROT_CW, CONFIRM]: confirm_snd.play() portraits[ev.player].confirmed = True if ev.key in [LEFT, RIGHT]: move_snd.play() for spr in char_sprites[ev.player]: spr.set_char(Character.available[idx[ev.player]]) portraits[ev.player].confirmed = False elif ev.type == QUIT: return None, None sprites.update(pygame.time.get_ticks()) pygame.display.update(sprites.draw(screen)) sprites.clear(screen, bg) return [Character.available[i] for i in idx]
def __init__(self, width, height, interactive_mode=False): self.width = width self.height = height self.start_height = height / 2 self.pipe_start_offset = 1000 self.pipe_distance = 300 self.pipe_space = 100 self.pipe_count = 5 self.horizontal_speed = 5 self.gravity = 0.5 self.interactive_mode = interactive_mode self.external_draw = None self.events = EventManager() if interactive_mode: # init pygame font print("Initializing font... This might take a while.") pygame.font.init() self.game_font = pygame.font.SysFont("Arial", 30) # init pygame clock self.game_clock = pygame.time.Clock() # init pygame display pygame.display.init() # set window dimensions self.game_screen = pygame.display.set_mode((width, height)) # set window title pygame.display.set_caption("FlappyAI") self.reset()
def do_test(n_data_packets, cc, add_events): """ The test has 2 hosts connected by a link, and one flow. """ em = EventManager(logging=False) host_1 = Host(em, 'H1', debug=False) host_2 = Host(em, 'H2', debug=False) sr = SeqNumberRecorder('S', host_2) l1_a = Link(em, 'L1_a', host_1, sr, DATA_PACKET_SIZE * 1000, 0.01, 5 * DATA_PACKET_SIZE, debug=False) l1_b = Link(em, 'L1_b', host_2, host_1, DATA_PACKET_SIZE * 1000, 0.01, 5 * DATA_PACKET_SIZE, debug=False) host_1.link = l1_a host_2.link = l1_b flow = Flow(em, 'F1', host_1, host_2, n_data_packets * DATA_PACKET_SIZE, 1, cc, debug=False) add_events(em, host_1, host_2, sr, l1_a, l1_b, flow) em.run() assert sr.seqs == set(range(n_data_packets + 1)) # print('Src send first unacked', flow.src.send_first_unacked, 'Src send next', flow.src.send_next, 'Dst receive next', flow.dst.receive_next) assert flow.src.last_seq_number == n_data_packets assert flow.src.send_first_unacked == n_data_packets + 1 assert flow.src.send_next == n_data_packets + 1 assert flow.dst.receive_next == n_data_packets + 1
def __init__(self): pygame.init() self.screen = pygame.display.set_mode(SCREENSIZE, 0, 32) self.background = None self.background_edit = None self.background_connection = None self.background_check = None self.setBackground() self.grid = [] #list of lines that define the grid self.setup() self.events = EventManager(self)
def _mouse_down(self, event): if event.button == InputManager.MOUSE_LEFT: self._mouse_left_is_down = True self._mouse_left_down_pos = event.pos click_event = self.lsclick if self._shift_pushed else self.lclick EventManager.post(click_event, pos=event.pos) elif event.button == InputManager.MOUSE_RIGHT: click_event = self.rsclick if self._shift_pushed else self.rclick EventManager.post(click_event, pos=event.pos)
def build(self): self.state_mgr = StateManager() self.window = Window() Clock.schedule_interval(self.update, 1.0 / 60.0) self.game_state = GameState('lvl/levels') self.state_mgr.push_state(self.game_state) self.state_mgr.push_state(GameCreatorState(self)) self.event_manager = EventManager() self.window.event_manager = self.event_manager return self.window
def __init__(self): self.inputMgr = InputManager.get_instance() self.eventMgr = EventManager() self.recorder = None self.state = self.ST_MENU self.rootMenu = None
def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(SCREENSIZE, 0, 32) self.background = pygame.surface.Surface(SCREENSIZE).convert() self.background.fill(BLACK) self.mousePosition = None self.bsp = None self.testvertexlist = [] self.segments = [ ] #make global for testing so we can see them dynamically self.events = EventManager(self) self.player = None self.WR3D = None self.mode3D = False print("SCREEN WIDTH = " + str(SCREENWIDTH))
def __init__(self, view_size): self.view_rect = Rect((0, 0), view_size) self.move_event = EventManager.new_event_code() self._moving = False self._move_vector = [0, 0] self._last_update = 0
def __init__(self, event_manager): event_manager.subscribe(pygame.KEYDOWN, self._key_down) event_manager.subscribe(pygame.KEYUP, self._key_up) event_manager.subscribe(pygame.MOUSEBUTTONDOWN, self._mouse_down) event_manager.subscribe(pygame.MOUSEBUTTONUP, self._mouse_up) event_manager.subscribe(pygame.MOUSEMOTION, self._mouse_moved) self._keybinds_down = {} self._keybinds_up = {} self._hot_area_ids = set() self._active_hotareas = set() self._hot_area_counter = 0 self._hot_area_rects = {} self._hot_area_actions = {} self._pushed_keys = set() self._mouse_left_is_down = False self._mouse_left_down_pos = None # events self.lclick = EventManager.new_event_code() self.lsclick = EventManager.new_event_code() self.rclick = EventManager.new_event_code() self.rsclick = EventManager.new_event_code() self.mouse_drag_start = EventManager.new_event_code() self.mouse_drag_end = EventManager.new_event_code() self.mouse_drag_update = EventManager.new_event_code() self.mouse_dragging = False self._mouse_drag_start = None
def __init__(self, server='', player='p1', idx=0): pygame.init() pygame.font.init() self.em = EventManager() self.em.add_event(Event("game-event")) self.config = load_config(CONFIG_FILE) self.menu_options = self.config['MENU'] self.idx = idx self.mode = "GAME" self.server = server self.player_name = player self.remote_game = None if self.server: self.remote_game = RemoteGame(self) self.window = pygame.display.set_mode((self.config['SCREENHEIGHT'], self.config['SCREENWIDTH'])) pygame.display.set_caption(self.config['TITLE']) self.screen = pygame.display.get_surface() self.clock = pygame.time.Clock() self.chat_surface = pygame.Surface((self.screen.get_width(), 50)) self.chat_surface.fill(pygame.Color(255, 255, 255)) self.chat_surface.set_alpha(130) self.menu_surface = pygame.Surface((self.screen.get_width(), self.screen.get_height() // 2)) self.menu_surface.fill(pygame.Color(255, 255, 255)) self.menu_surface.set_alpha(130) self.text = "" self.font = pygame.font.SysFont("Sans", 16) self.map = Map(1, 1) self.map.load_from_image(self.config['MAP']) self.map.scroll = [0, 14] self.guy1 = Guy(self.idx, self) self.guy1.set_name(self.player_name) self.guy1.set_pos(17, 0) self.guy2 = RemoteGuy(1, self) self.guy2.set_name("Cat girl") self.guy2.movement = "circular" self.guy2.set_pos(15, 0) tree1 = Tree(self, 0) tree2 = Tree(self, 1) tree3 = Tree(self, 1) tree4 = Tree(self, 2) tree2.set_pos(20, 0) tree1.set_pos(20, 1) tree3.set_pos(19, 2) tree4.set_pos(18, 3) self.events = {}
def register_event_handler(self, event_name, handler, run_on_main_loop=True, deregister_on_finish=False): sig = EventManager.instance().register_handler(event_name, handler, run_on_main_loop, self) if deregister_on_finish: self.registered_event_handlers.append(sig) return sig
def Main(): """main - main function calls all components and run the program.""" print("Base Application Running") evManager = EventManager() keybd = KeyboardController(evManager) spinner = CPUSpinnerController(evManager) pygameView = PygameView(evManager) game = Game(evManager) spinner.Run()
def __init__(self): """ When a mode is created, it only creates an event manager. The mode's components and clock are instantiated when the mode is activated. The mode manager/MSM has to register for transition or quit callbacks through set_X_callback. """ # hold instances of the mode's components when the mode is activated self.active_components = [] self.clock = None # instantiated by MSM self.em = EventManager() # each mode has its own EM
class SingletonApp (object): ## Instance of the singleton class __inst = None #----------------------------------------------------------------------------- ## Singleton constructor. Sets up logger and eventManager def __new__(cls): if not cls.__inst: cls.__inst = super(SingletonApp,cls).__new__(cls) ## Initialise log and send info message Log(level="DEBUG").info("SingletonApp instance created") cls.__inst._setup() return cls.__inst #----------------------------------------------------------------------------- ## Destructor def __del__(): Log().info("SingletonApp deleted") #----------------------------------------------------------------------------- ## Setup the eventManager and hook "singletonApp_setup" def _setup(self): ## An instance of events.eventManager.EventManager. Initialised in # SingletonApp._setup and deleted in SingletonApp.close self.eventManager = EventManager() Log().debug("SingletonApp setup") self.eventManager.hook("singletonApp_setup") #----------------------------------------------------------------------------- ## Safe shutdown and dereference of variables. # This stops circular references stopping the garbage collection def close(self): del self.eventManager Log().info("SingletonApp closed")
def __init__(self, min_cycle_time=10): self.min_cycle_time = min_cycle_time self._run = False self._last_update = 0 self._last_mouse_pos = None self._selecting = False self._select_start_pos = None self._selection_rect = None self._mouse_right_down = False pygame.init() screen_width, screen_height = screen_size = (1024, 768) self._screen = pygame.display.set_mode(screen_size, pygame.DOUBLEBUF) self._map = Map('default') self._camera = Camera(screen_size) self._renderer = Renderer(self._screen, self._camera) self._objects = ObjectManager(self._map.size) self._event_mgr = EventManager() self._event_mgr.subscribe(pygame.QUIT, self._handle_quit) self._event_mgr.subscribe(self._camera.move_event, self._camera_moved) self._input = InputManager(self._event_mgr) self._input.set_keybind(pygame.K_ESCAPE, self.stop) self._input.set_keybind(pygame.K_q, self.stop) self._input.set_hotarea((0, 0, screen_width, 2), self._camera.set_move, {'y': -1}) self._input.set_hotarea((0, screen_height - 2, screen_width, 2), self._camera.set_move, {'y': 1}) self._input.set_hotarea((0, 0, 2, screen_height - 2), self._camera.set_move, {'x': -1}) self._input.set_hotarea((screen_width - 2, 0, 2, screen_height), self._camera.set_move, {'x': 1}) self._input.set_hotarea((2, 2, screen_width - 4, screen_height - 4), self._camera.stop_moving) self._event_mgr.subscribe(self._input.mouse_drag_start, self._select_start) self._event_mgr.subscribe(self._input.mouse_drag_update, self._select_update) self._event_mgr.subscribe(self._input.mouse_drag_end, self._select_end) self._event_mgr.subscribe(self._input.lclick, self._leftclick) self._event_mgr.subscribe(self._input.rclick, self._rightclick) self._event_mgr.subscribe(self._input.rsclick, self._right_shiftclick)
def _mouse_moved(self, event): pos = event.pos if self._mouse_left_is_down: if self.mouse_dragging: EventManager.post(self.mouse_drag_update, pos=pos) elif InputManager.MOUSE_DRAG_THRESHOLD < \ util.point_dist(self._mouse_left_down_pos, pos): self._mouse_drag_start = pos self.mouse_dragging = True EventManager.post(self.mouse_drag_start, pos=pos) current_active_hotareas = set() for hotarea_id in self._hot_area_ids: if self._hot_area_rects[hotarea_id].collidepoint(pos): current_active_hotareas.add(hotarea_id) entered_hotareas = current_active_hotareas - self._active_hotareas #left_hotareas = self._active_hotareas - current_active_hotareas for hotarea_id in entered_hotareas: callback, args = self._hot_area_actions[hotarea_id] callback(**args)
def _mouse_up(self, event): if event.button == InputManager.MOUSE_LEFT: self._mouse_left_is_down = False if self.mouse_dragging: self.mouse_dragging = False EventManager.post(self.mouse_drag_end) #def _handle_input(self, time_passed): # pressed_keys = pygame.key.get_pressed() # # delta = 0.25 * time_passed # # # camera movement # if pressed_keys[pygame.K_w]: # self._camera.move(0, -delta) # if pressed_keys[pygame.K_s]: # self._camera.move(0, delta) # if pressed_keys[pygame.K_a]: # self._camera.move(-delta, 0) # if pressed_keys[pygame.K_d]: # self._camera.move(delta, 0) # self._camera_moved()
def main(screen): grid_manager = GridManager() player = Player(*grid_manager.random_move_through_tile()) event_manager = EventManager() player_mover = PlayerMover(event_manager, player, grid_manager) # noqa: F841 interaction_handler = InteractionHandler(event_manager, grid_manager) # noqa: F841 while True: grid_manager.print(screen) player.print(screen) screen.refresh() event = screen.get_event() if isinstance(event, KeyboardEvent): if event.key_code == Screen.KEY_UP: event_manager.publish(PlayerMoveEvent(PlayerMoveEvent.UP)) elif event.key_code == Screen.KEY_LEFT: event_manager.publish(PlayerMoveEvent(PlayerMoveEvent.LEFT)) elif event.key_code == Screen.KEY_DOWN: event_manager.publish(PlayerMoveEvent(PlayerMoveEvent.DOWN)) elif event.key_code == Screen.KEY_RIGHT: event_manager.publish(PlayerMoveEvent(PlayerMoveEvent.RIGHT))
def __init__(self, items): platforms = [Platform([400 + 260 * i, 390], s[0], i) for i, s in enumerate(items)] credits = Credits() self._score = TopScores() sprites = RenderUpdates([credits, self._score]) sprites.add(platforms) pos = 0 em = EventManager() em.clear() screen = pygame.display.get_surface() em.get() quit = False screen.blit(Menu.bg, [0, 0]) sprites.draw(screen) pygame.display.update() while not quit: for ev in em.get(): if ev.type == PLAYER: if ev.key == LEFT: if pos != 0: pos -= 1 for p in platforms: p.left() elif ev.key == RIGHT: if pos != len(items) - 1: pos += 1 for p in platforms: p.right() else: try: r = items[pos][1][ev.key](self, platforms[pos], pos, ev.key) if r: # If the callback returns true, then we # need to redraw the whole screen and # reread our scores. (If it returns false, # it probably means it just modified some # cart text). self._score.read_scores() screen.blit(Menu.bg, [0, 0]) pygame.display.update() except KeyError: pass elif ev.type == QUIT: quit = True sprites.update(pygame.time.get_ticks()) pygame.display.update(sprites.draw(screen)) sprites.clear(screen, Menu.bg) pygame.time.clock.tick(60)
def run(self): self.view = webkit.WebView() self.view.get_settings().set_property("enable-webgl", True) self.sw = gtk.ScrolledWindow() self.sw.add(self.view) self.win = gtk.Window(gtk.WINDOW_TOPLEVEL) try: self.win.resize(*[int(i) for i in self._options.window_size.split(',')]) except Exception as e: print(e) print('--size require 2 values : "x,y"') exit(0) self.em = EventManager() if self._options.replay: self.em.replay_events( self.win, self.view, self._options.filename, end = self.quit if self._options.exit_after_run else None ) elif self._options.record: self.view.connect( * self.em.get_callback("button_press_event") ) self.view.connect( * self.em.get_callback("key_press_event") ) self.view.open(self._options.url) vbox = gtk.VBox(False) menu = self.create_menu() vbox.pack_start(menu, False, False, 0) vbox.pack_start(self.sw, True, True, 0) self.win.add(vbox) vbox.show() self.win.show_all() try: gtk.main() except KeyboardInterrupt: if self._options.record: self.em.dump(self._options.filename)
def main(): pygame.init() pygame.display.set_caption("The 15 Puzzle") win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) clock = pygame.time.Clock() event_manager = EventManager() game_board = GameModel() game_view = GameView(win) spinner = CPUSpinnerController(event_manager, clock) game_controller = GameController(game_board, game_view) event_manager.registerListener(TickEvent(), game_controller) event_manager.registerListener(QuitEvent(), spinner) spinner.run() pygame.quit()
def prepare_events(ages, bathymetries, sea_levels, thicknesses, rock_types, rock_properties): """ Package inputs into an EventManager instance. """ events = [] for age, bathymetry, sea_level, thickness, rock_type in zip( ages[1:], bathymetries[1:], sea_levels[1:], thicknesses, rock_types): layer = Layer(present_thickness=thickness, porosity_function=athy_porosity) layer.set_rock_properties(rock_properties[rock_type]) event = Deposition(age=age, bathymetry=bathymetry, sea_level=sea_level, layer=layer) events.append(event) event_manager = EventManager(initial_age=ages[0], initial_sea_level=sea_levels[0], initial_bathymetry=bathymetries[0]) event_manager.add_events(events) event_manager.reconstruct_burial_history() return event_manager
class Mode: """ A mode has its own clock, event manager, and components. A mode is a state activated and deactivated by the mode state machine. """ def __repr__(self): return self.__class__.__name__ def __str__(self): return self.__repr__() def __init__(self): """ When a mode is created, it only creates an event manager. The mode's components and clock are instantiated when the mode is activated. The mode manager/MSM has to register for transition or quit callbacks through set_X_callback. """ # hold instances of the mode's components when the mode is activated self.active_components = [] self.clock = None # instantiated by MSM self.em = EventManager() # each mode has its own EM def set_transition_callback(self, trans_evt_classes, msm_transition_cb): """ Set the callback to the mode state machine when transition events are fired by the current mode. """ for ev_class in trans_evt_classes: self.em.subscribe(ev_class, msm_transition_cb) def set_quit_callback(self, msm_quit_cb): """ Set the MSM callback to call when the mode fires a QuitEvent. """ self.em.subscribe(QuitEvent, msm_quit_cb) def activate(self, ev): """ Instantiate the components and clock for the mode. The event passed in argument contains data sent by the previous mode. For example, the LevelTransitionMode sends a GameStart event containing the next level number to the GameMode. This way, the GameMode knows which level to instantiate. The GameMode sends a GameWon event containing the score to the LevelTransitionMode so that it can be displayed. Small drawback: to keep the code generic, ALL the components are given in argument the mode's EM and the event. Some components may not need the event, but we can't know in advance, so we pass it anyway. """ em = self.em self.active_components = [comp(em, ev) for comp in self.components] self.clock = Clock(em) self.clock.start() # returns when the clock is turned off, ie transition or quit self.em.clear() # this removes the clock and MSM from the EM subscribers self.active_components = [] # last ref to component instances is lost self.clock = None def deactivate(self): """ Tell the clock to stop. The mode's components will be garbage collected when the clock returns the hand back to the MSM. """ self.clock.stop()
class GameController(object): def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(SCREENSIZE, 0, 32) self.background = pygame.surface.Surface(SCREENSIZE).convert() self.background.fill(BLACK) self.mousePosition = None self.bsp = None self.testvertexlist = [] self.segments = [ ] #make global for testing so we can see them dynamically self.events = EventManager(self) self.player = None self.WR3D = None self.mode3D = False print("SCREEN WIDTH = " + str(SCREENWIDTH)) def update(self): '''Main game loop''' #dt = self.clock.tick(30) / 1000.0 x, y = pygame.mouse.get_pos() self.mouseposition = Vector2(x, y) self.events.update(self.mouseposition) self.render() def getTestSector(self): '''From the testsectors file. Press button 5''' L = testsectors.sector5() print(L) self.segments = [] for pair in L: v1 = Vector2(pair[0]) v2 = Vector2(pair[1]) self.segments.append(Segment(v1, v2, name=pair[2])) self.bsp = BSP(self.segments) self.bsp.createTree() def stepThroughTree(self): '''This just helps me step through the tree one iteration at a time to see what it is doing for debugging.''' self.bsp.traverseTree() def createPlayer(self): '''Create a player in the middle of the screen''' #self.getSegmentDrawingOrder(self.mouseposition) if self.player is None and self.bsp is not None: self.player = Player(SCREENWIDTH / 2, SCREENHEIGHT / 2) self.WR3D = WallRender3D(self.bsp.tree, self.player) def render(self): self.screen.blit(self.background, (0, 0)) if not self.mode3D: if len(self.segments) > 0: for seg in self.segments: seg.render(self.screen) if self.player is not None: if self.mode3D: self.WR3D.render(self.screen) else: self.player.render(self.screen) pygame.display.update()
def _setup(self): ## An instance of events.eventManager.EventManager. Initialised in # SingletonApp._setup and deleted in SingletonApp.close self.eventManager = EventManager() Log().debug("SingletonApp setup") self.eventManager.hook("singletonApp_setup")
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2011 ~ 2012 Hou Shaohui # # Author: Hou Shaohui <*****@*****.**> # Maintainer: Hou Shaohui <*****@*****.**> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from events import EventManager event_manager = EventManager(use_logger=False)
def init(*args): em = EventManager() screen = pygame.display.get_surface() move_snd = load.sound("select-move.wav") index = 0 # The format is up to three paragraphs per screen, displayed # left, right, left, texts = [ ["In Angry, Drunken Dwarves, you are an angry, drunken dwarf. Why " "are you so angry? Who knows. But you've decided to take your " "aggression out on other dwarves, by dropping gems on their " "heads.", "Multicolored gems will fall from the top of the screen. You " "should try to arrange them into groups by color. The arrow keys " "or a/d and j/l will move them left and right. s or k will make " "then fall faster, and q/e and u/o will rotate them.", "As gems reach the bottom, they will land and sit in place. If you " "put enough gems of the same color in a rectangle shape, they will " "merge and form a crystal." ], ["Less common are break gems. When you drop a break gem on a gem " "or crystal of the same color, it will destroy any gems of that " "color adjacent to it. Crystals are worth much more than an equal " "number of regular gems.", "When you destroy gems on your side, it will drop counter gems " "onto your opponent. These are harder to destroy, but turn into " "regular gems after a few turns. You can try to cancel an incoming " "attack by breaking gems yourself, but you'll need to break twice " "as many as are coming.", "Rarer is the diamond. When you drop a diamond onto something, " "it will destroy all gems of that color on your side, even " "counter gems! Be careful though, because a crystal " "destroyed by a diamond isn't worth any more than normal gems." ], ["Each dwarf has a drop gem pattern, and an attack strength. The drop " "pattern is a display of what kinds of gems will be dropped when " "you attack your opponent. Small attacks will drop the same " "row over and over, which will probably help them!", "The attack strength is a measurement of how strong your drop " "pattern is; drops with weirder patterns are harder to plan " "against. Before gems are dropped, they are multiplied by this " "attack strength, and so the damage is scaled up or down.", "For the most devestating results, try chaining attacks together, " "so breaking some gems results in even more breaking afterwards. " "Breaking many crystals in a chain can result in huge drops." ] ] drop = pygame.Surface([64, 64]) drop.blit(load.block("blue"), [0, 0]) drop.blit(load.block("yellow"), [0, 32]) drop.blit(load.block("green"), [32, 0]) drop.blit(load.block("red"), [32, 32]) crystal = load.gem("green", 4, 3) breaks = pygame.Surface([64, 64]) breaks.blit(load.block("red", "-crash"), [0, 0]) breaks.blit(load.block("green", "-crash"), [0, 32]) breaks.blit(load.block("yellow", "-crash"), [32, 0]) breaks.blit(load.block("blue", "-crash"), [32, 32]) counters = pygame.Surface([64, 64]) counters.blit(textfx.lettered_box("5", "green"), [0, 0]) counters.blit(textfx.lettered_box("4", "blue"), [32, 0]) counters.blit(textfx.lettered_box("3", "red"), [0, 32]) counters.blit(textfx.lettered_box("2", "yellow"), [32, 32]) chain = pygame.Surface([64, 96]) chain.blit(load.block("blue", "-crash"), [0, 64]) chain.blit(load.block("green"), [32, 64]) chain.blit(load.block("green", "-crash"), [32, 32]) chain.blit(load.block("blue"), [32, 0]) # Followed by up to three images per screen, right, left, right. images = [ [None, drop, crystal], [breaks, counters, load.block("diamond")], [Character.arcade[4].drop.render(), None, chain], ] if config.getboolean("unlock", "single"): texts.append([ "In single player mode, rather than competing against someone " "else, you're racing the clock. You have to clear a certain " "number of blocks in a certain number of turns, or the ones " "left get dumped on you.", "Your field is also twice as big. So it sounds easy, right? " "Well, to start with, you've got three new colors of gems to " "contend with: orange, purple, and cyan.", "If that wasn't bad enough, the number of gems you have to clear " "goes up much faster than the number of turns you have " "to do it, so build up those crystals early and save them." ]) newcols = pygame.Surface([64, 64]) newcols.blit(load.block("orange"), [16, 0]) newcols.blit(load.block("cyan"), [0, 32]) newcols.blit(load.block("purple"), [32, 32]) counts = pygame.Surface([130, 100]) box = Character.default.border([40, 40]) text1 = textfx.shadow("new:", 20) text2 = textfx.shadow("turns:", 20) num1 = textfx.shadow("122", 30) num2 = textfx.shadow("10", 30) counts.blit(box, [0, 20]) counts.blit(box, [70, 20]) counts.blit(text1, text1.get_rect(center = [30, 38])) counts.blit(text2, text2.get_rect(center = [100, 38])) counts.blit(num1, [12, 45]) counts.blit(num2, [87, 45]) images.append([None, newcols, counts]) if config.getboolean("unlock", "combat"): texts.append([ "Combat blocks look like normal gems with a special symbol " "in the middle. These gems don't form crystals, but otherwise " "break like normal colored gems. When you break one of these, " "you 'pick up' the special attack in it.", "To use the attack, press start (enter/2). There are five basic " "attacks; from left to right: make your opponent's field blink, " "clear your own field of all blocks,", "flip your opponent's screen upside down, disable the 'next' " "indicator, drop some gray blocks, or reverse your opponent's " "controls. Blink, flip, and reverse last for a few " "seconds. Scramble lasts 10 turns."]) blink = load.block("blue") clear = load.block("red") rev = load.block("yellow") flip = load.block("green") gray = load.block("red") scram = load.block("purple") blink.blit(SpecialSprite.load(BLINK), [6, 6]) flip.blit(SpecialSprite.load(FLIP), [6, 6]) clear.blit(SpecialSprite.load(CLEAR), [6, 6]) rev.blit(SpecialSprite.load(REVERSE), [6, 6]) gray.blit(SpecialSprite.load(GRAY), [6, 6]) scram.blit(SpecialSprite.load(SCRAMBLE), [6, 6]) img1 = pygame.Surface([64, 32]) img2 = pygame.Surface([64, 64]) img1.blit(blink, [0, 0]) img1.blit(clear, [32, 0]) img2.blit(flip, [0, 0]) img2.blit(scram, [32, 0]) img2.blit(gray, [0, 32]) img2.blit(rev, [32, 32]) images.append([None, img1, img2]) wipes.wipe_in(render_help_page(texts[index], images[index])) cont = True screen.blit(render_help_page(texts[index], images[index]), [0, 0]) img = textfx.shadow("Enter: Menu - Left/Right: Turn Page (%d/%d)" % (index + 1, len(images)), 18) screen.blit(img, [785 - img.get_width(), 10]) pygame.display.update() while cont: oldindex = index for ev in em.wait(): if ev.type == QUIT: cont = False elif ev.type == PLAYER: if ev.key == CONFIRM: cont = False elif ev.key == UP or ev.key == LEFT: index = (index - 1) % len(texts) move_snd.play() elif ev.key in [DOWN, RIGHT, ROT_CC, ROT_CW]: index = (index + 1) % len(texts) move_snd.play() if oldindex != index: screen.blit(render_help_page(texts[index], images[index]), [0, 0]) img = textfx.shadow("Enter: Menu - Left/Right: Turn Page (%d/%d)" % (index + 1, len(images)), 18) screen.blit(img, [785 - img.get_width(), 10]) pygame.display.update() return True
from events import EventManager from host import Host from link import Link from flow import Flow from packet import Packet, DATA_PACKET_SIZE, CONTROL_PACKET_SIZE class PacketRecorder: def __init__(self, next_component): self.next_component = next_component self.packets = [] def on_reception(self, t, p): self.packets.append(p) self.next_component.on_reception(t, p) em = EventManager(logging=False) host_1 = Host(em, 'H1', debug=True) p1 = PacketRecorder(host_1) host_2 = Host(em, 'H2', debug=True) p2 = PacketRecorder(host_2) l1_a = Link(em, 'L1_a', host_1, p2, 10485760, 0.01, 524288, debug=False) l1_b = Link(em, 'L1_b', host_2, p1, 10485760, 0.01, 524288, debug=False) host_1.link = l1_a host_2.link = l1_b flow = Flow(em, 'F1', host_1, host_2, DATA_PACKET_SIZE, 1, StopAndWait(), debug=True) em.run() # Packets sent by host 1 p2_expect = [ # SYN Packet('F11', flow, host_1, host_2, syn_flag = True, ack_flag = False,
class App(object): def __init__(self): self._options = None def run(self): self.view = webkit.WebView() self.view.get_settings().set_property("enable-webgl", True) self.sw = gtk.ScrolledWindow() self.sw.add(self.view) self.win = gtk.Window(gtk.WINDOW_TOPLEVEL) try: self.win.resize(*[int(i) for i in self._options.window_size.split(',')]) except Exception as e: print(e) print('--size require 2 values : "x,y"') exit(0) self.em = EventManager() if self._options.replay: self.em.replay_events( self.win, self.view, self._options.filename, end = self.quit if self._options.exit_after_run else None ) elif self._options.record: self.view.connect( * self.em.get_callback("button_press_event") ) self.view.connect( * self.em.get_callback("key_press_event") ) self.view.open(self._options.url) vbox = gtk.VBox(False) menu = self.create_menu() vbox.pack_start(menu, False, False, 0) vbox.pack_start(self.sw, True, True, 0) self.win.add(vbox) vbox.show() self.win.show_all() try: gtk.main() except KeyboardInterrupt: if self._options.record: self.em.dump(self._options.filename) def parse_args(self): parser = OptionParser() parser.add_option( "-p", action="store_true", dest="replay", default=False, help="replay a sequence of events." ) parser.add_option( "-r", action="store_true", dest="record", default=False, help="record a sequence of events." ) parser.add_option( "-f", "--file", dest="filename", default="events.pk", help="write/read events from [filename]." ) parser.add_option( "-u", "--url", dest="url", default="http://127.0.0.1:3000/", ) parser.add_option( "-s", "--size", action="store", dest="window_size", default="800,600", help="Window size." ) parser.add_option( "-e", "--exit", dest="exit_after_run", action='store_true', default=False, help="(Only for replay-mode) exit when finished." ) self._options, args = parser.parse_args() return (self._options, args) def save_session(self, *args): if self._options.record: self.em.dump( self._options.filename, window_size=[int(i) for i in self._options.window_size.split(',')] ) print("session saved!") return 0 def quit(self, *args): gtk.main_quit() return 0 def create_menu(self): """ UI Stuff, again from http://www.pygtk.org/pygtk2tutorial/ch-MenuWidget.html """ file_item = gtk.MenuItem("File") menu_bar = gtk.MenuBar() file_menu = gtk.Menu() quit_item = gtk.MenuItem("Quit") save_item = gtk.MenuItem("Save session") save_quit_item = gtk.MenuItem("Save session and quit...") file_menu.append(quit_item) quit_item.connect_object( "activate", self.quit, "quit_session" ) # recording options if self._options.record: file_menu.append(save_quit_item) file_menu.append(save_item) save_item.connect_object( "activate", self.save_session, "save" ) save_quit_item.connect_object( "activate", lambda x : self.save_session() + self.quit(), "quit" ) save_quit_item.show() save_item.show() quit_item.show() menu_bar.append(file_item) file_item.set_submenu(file_menu) menu_bar.show() return menu_bar
def deregister_event_handler(self, sig): EventManager.instance().remove_handler(sig) self.registered_event_handlers.remove(sig)
#!/usr/bin/env python #-*- coding:utf-8 -*- # Copyright (C) 2011 ~ 2013 Deepin, Inc. # 2011 ~ 2013 Zeng Zhi # # Author: Zeng Zhi <*****@*****.**> # Maintainer: Zeng Zhi <*****@*****.**> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #import gobject from events import EventManager nm_events = EventManager(use_logger=False) #print nm_events, "-lib"
for seq in sequences.itervalues(): try: seq.stop() except: pass sys.exit(0) signal.signal(signal.SIGINT, stop_threads) for seq in sequences.itervalues(): seq.start() current_sequence = None usb = serial.Serial('/dev/ttyACM0', 9600) event_manager = EventManager() while True: try: evt = int(usb.readline()) event_type = "CTRL_DOWN" if evt / 100 == 0 else "CTRL_UP" evt = evt % 100 event_manager.set_event(event_type, evt) except: pass evt_down = event_manager.get_event("CTRL_DOWN") evt_up = event_manager.get_event("CTRL_UP") if evt_down and evt_down in sequences: print "RAISE CTRL_DOWN", evt_down current_sequence = sequences[evt_down]
class Game: def __init__(self, server='', player='p1', idx=0): pygame.init() pygame.font.init() self.em = EventManager() self.em.add_event(Event("game-event")) self.config = load_config(CONFIG_FILE) self.menu_options = self.config['MENU'] self.idx = idx self.mode = "GAME" self.server = server self.player_name = player self.remote_game = None if self.server: self.remote_game = RemoteGame(self) self.window = pygame.display.set_mode((self.config['SCREENHEIGHT'], self.config['SCREENWIDTH'])) pygame.display.set_caption(self.config['TITLE']) self.screen = pygame.display.get_surface() self.clock = pygame.time.Clock() self.chat_surface = pygame.Surface((self.screen.get_width(), 50)) self.chat_surface.fill(pygame.Color(255, 255, 255)) self.chat_surface.set_alpha(130) self.menu_surface = pygame.Surface((self.screen.get_width(), self.screen.get_height() // 2)) self.menu_surface.fill(pygame.Color(255, 255, 255)) self.menu_surface.set_alpha(130) self.text = "" self.font = pygame.font.SysFont("Sans", 16) self.map = Map(1, 1) self.map.load_from_image(self.config['MAP']) self.map.scroll = [0, 14] self.guy1 = Guy(self.idx, self) self.guy1.set_name(self.player_name) self.guy1.set_pos(17, 0) self.guy2 = RemoteGuy(1, self) self.guy2.set_name("Cat girl") self.guy2.movement = "circular" self.guy2.set_pos(15, 0) tree1 = Tree(self, 0) tree2 = Tree(self, 1) tree3 = Tree(self, 1) tree4 = Tree(self, 2) tree2.set_pos(20, 0) tree1.set_pos(20, 1) tree3.set_pos(19, 2) tree4.set_pos(18, 3) self.events = {} def manage_game(self, event): if event.type == QUIT: self.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: self.exit() elif event.type == KEYDOWN: self.events[event.key] = True elif event.type == KEYUP: if event.key == K_c: self.mode = "CHAT" self.text = "" pygame.key.set_repeat(300, 10) if event.key == K_m: self.mode = "MENU" self.events[event.key] = False def manage_chat(self, event): if event.type == KEYDOWN and event.key == K_ESCAPE: self.mode = "GAME" pygame.key.set_repeat() if event.type == KEYDOWN and event.key == K_RETURN: self.guy1.set_text(self.text) self.em.signal('game-event', 'TALK %s %s' % (self.player_name, self.text)) self.mode = "GAME" pygame.key.set_repeat() if event.type == KEYDOWN: t = event.unicode if event.key == K_BACKSPACE: self.text = self.text[0:-1] t = '' elif event.key == K_TAB: t = " " if len(self.text) < 141: self.text += t def manage_menu(self, event): if event.type == KEYDOWN and event.key == K_ESCAPE: self.mode = "GAME" for option in self.menu_options: #print option pass def paint_chat(self): self.screen.blit(self.chat_surface, (0, self.screen.get_height() - self.chat_surface.get_height())) texts = wrap_text(self.font, self.text, self.screen.get_width() - 40) for i, t in enumerate(texts): font_surface = self.font.render(t, True, pygame.Color(0, 0, 0)) self.screen.blit(font_surface, (20, (i * 20) + self.screen.get_height() - self.chat_surface.get_height())) def main(self): while True: #print self.clock.get_fps() self.clock.tick(self.config['FPS']) self.screen.fill(pygame.Color(0, 0, 0, 1)) self.map.draw(self.screen) if self.mode == "CHAT": self.paint_chat() # managing events for event in pygame.event.get(): if self.mode == "GAME": self.manage_game(event) if self.mode == "CHAT": self.manage_chat(event) if self.mode == "MENU": self.manage_menu(event) self.map.update(self.events) # updating screen pygame.display.flip() def exit(self): if self.remote_game: self.remote_game.stop() sys.exit(0)
from events import EventManager from file_input import read_network from host import Host from link import Link from flow import Flow em = EventManager(logging=False) hosts, routers, links, flows = read_network('test_case_0_stopandwait.json', em) h1 = Host(em, 'H1', debug=False) h1.add_link(links['L1_a']) h2 = Host(em, 'H2', debug=False) h2.add_link(links['L1_b']) print(hosts) assert hosts == { 'H1': h1, 'H2': h2 } assert routers == {} assert links == { 'L1_a': Link(em, 'L1_a', hosts['H1'], hosts['H2'], 1.049e7, 10e-3, 5.24e5, debug=False), 'L1_b': Link(em, 'L1_b', hosts['H2'], hosts['H1'], 1.049e7, 10e-3, 5.24e5, debug=False) } # TODO check flows; it is a bit difficult
class FlappyGame: ''' Flappy Bird emulator ''' def __init__(self, width, height, interactive_mode=False): self.width = width self.height = height self.start_height = height / 2 self.pipe_start_offset = 1000 self.pipe_distance = 300 self.pipe_space = 100 self.pipe_count = 5 self.horizontal_speed = 5 self.gravity = 0.5 self.interactive_mode = interactive_mode self.external_draw = None self.events = EventManager() if interactive_mode: # init pygame font print("Initializing font... This might take a while.") pygame.font.init() self.game_font = pygame.font.SysFont("Arial", 30) # init pygame clock self.game_clock = pygame.time.Clock() # init pygame display pygame.display.init() # set window dimensions self.game_screen = pygame.display.set_mode((width, height)) # set window title pygame.display.set_caption("FlappyAI") self.reset() def reset(self): self.progress = 0 self.score = 0 self.next_pipe_x_location = self.pipe_start_offset + self.pipe_count * self.pipe_distance self.bird = Bird(self.height / 2, self.gravity) self.pipes = deque() self.bird_path = deque([(self.progress, self.bird.y)], camera_offset / self.horizontal_speed) # generate pipes for i in xrange(0, self.pipe_count): self.pipes.append(Pipe.generate_pipe(self.pipe_start_offset + i * self.pipe_distance, self.height)) def restart(self): self.events.trigger(FlappyGame.GAME_ENDED, { "final_score": self.score, "final_progress": self.progress }) self.reset() def add_new_pipe(self): self.pipes.append(Pipe.generate_pipe(self.next_pipe_x_location, self.height)) self.next_pipe_x_location += self.pipe_distance def step(self, action=0): if self.interactive_mode: for event in pygame.event.get(): if event.type == pygame.QUIT: return FlappyGame.QUIT if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: action = FlappyGame.JUMP # step forward self.bird.step(action) self.bird_path.append((self.progress, self.bird.y)) self.progress += self.horizontal_speed if self.bird.y < 0: self.bird.y = 0 if self.bird.y > self.height: self.bird.y = self.height # regenerate pipe if self.pipes[0].get_screen_x_location(self.progress) < 0: self.pipes.popleft() self.add_new_pipe() # render graphics if self.interactive_mode: self.render() self.game_clock.tick(60) # check collision if self.bird.y >= self.height or self.bird.y <= 0: # hit the ground self.restart() return FlappyGame.COLLIDED upcoming_pipe = self.get_next_pipe() if self.progress == upcoming_pipe.x: if abs(self.bird.y - upcoming_pipe.space_y) > self.pipe_space / 2: # collided self.restart() return FlappyGame.COLLIDED else: self.score += 1 # passed return FlappyGame.PASSED return FlappyGame.NORMAL def render(self): self.game_screen.fill((0, 0, 0)) # draw bird pygame.draw.circle(self.game_screen, (255, 255, 255), self.bird.get_screen_location(), 3, 1) # draw pipes for pipe in self.pipes: screen_x_location = pipe.get_screen_x_location(self.progress) pygame.draw.line( self.game_screen, (255, 255, 255), (screen_x_location, 0), (screen_x_location, pipe.space_y - self.pipe_space / 2) ) pygame.draw.line( self.game_screen, (255, 255, 255), (screen_x_location, pipe.space_y + self.pipe_space / 2), (screen_x_location, self.height) ) # draw bird path path = [(camera_offset - (self.progress - progress), y) for (progress, y) in self.bird_path] pygame.draw.lines( self.game_screen, (100, 100, 100), False, path ) # draw score score_text = self.game_font.render(str(self.score), False, (255, 255, 255)) score_text_width, score_text_height = self.game_font.size(str(self.score)) self.game_screen.blit(score_text, (self.width / 2 - score_text_width / 2, 5)) if self.external_draw != None: self.external_draw(self) pygame.display.flip() def get_next_pipe(self): for pipe in self.pipes: if pipe.x < self.progress: continue else: return pipe @staticmethod def get_actions(): return [FlappyGame.JUMP, FlappyGame.NONE] @staticmethod def get_events(): return [FlappyGame.GAME_ENDED] # step return status NORMAL, PASSED, COLLIDED, QUIT = range(4) # actions NONE, JUMP = range(2) # events GAME_ENDED = 0
for seq in sequences.itervalues(): try: seq.stop() except: pass sys.exit(0) signal.signal(signal.SIGINT, stop_threads) for seq in sequences.itervalues(): seq.start() current_sequence = None pygame.display.set_mode([200, 100]) event_manager = EventManager() while True: for event in pygame.event.get(pygame.KEYDOWN): event_manager.set_event("CTRL_DOWN", event.key) for event in pygame.event.get(pygame.KEYUP): event_manager.set_event("CTRL_UP", event.key) evt_down = event_manager.get_event("CTRL_DOWN") evt_up = event_manager.get_event("CTRL_UP") if evt_down and evt_down in sequences: print "RAISE CTRL_DOWN", evt_down current_sequence = sequences[evt_down] current_sequence.play() if evt_up and evt_up in sequences:
from events import EventManager from file_input import read_network from io import StringIO from contextlib import redirect_stdout if __name__ == '__main__': em = EventManager() read_network('test_case_1_reno.json', em) em.run() print(em.current_time)
def main(): value = input( 'You can type command: \n' '@{name} - to get events from provided category. Example: @update\n' '#{name} - to get events intended to some recipient. Example: #john\n' 'latest{N} - to get latest N events\n' '------------------------------------------\n') try: event_or_filter = InputParser.parse(value) except Exception as e: print(str(e)) print('----------------------------------') return main() if (isinstance(event_or_filter, Filter)): events = manager.get_by(event_or_filter) print('-----------------------------') print(events) print('-----------------------------') else: manager.append(event_or_filter) return main() if (__name__ == "__main__"): manager = EventManager() main()
def _post_move_event(self): EventManager.post(self.move_event, cam=self)
class GameApp(App): def build(self): self.state_mgr = StateManager() self.window = Window() Clock.schedule_interval(self.update, 1.0 / 60.0) self.game_state = GameState('lvl/levels') self.state_mgr.push_state(self.game_state) self.state_mgr.push_state(GameCreatorState(self)) self.event_manager = EventManager() self.window.event_manager = self.event_manager return self.window def start_new_game(self): next_lvl = self.game_state.advance_level() # if we finished all the levels restart_game = False if not next_lvl: self.game_state.reset() next_lvl = self.game_state.advance_level() restart_game = True # create new game game_logic = GameLogic() game_logic.game_state = self.game_state game_logic.event_manager = self.event_manager self.add_graphic_state(game_logic) game_logic.build_level(next_lvl) self.game_logic = game_logic # Display message at the begining of each level msg = 'Level %d' % self.game_state.current_level self.add_graphic_state(TemporaryMessage(msg)) if restart_game: self.add_graphic_state(StartMenu()) msg = 'Credit goes here' self.add_graphic_state(TemporaryMessage(msg)) else: self.add_graphic_state(EndLevel(True)) # # take screenshot # def take_screenshot(_, key): # if key == 's': # self.window.take_screenshot('screenshot.png') # self.window.event_manager.register_action('key down', take_screenshot) def update(self, dt): self.state_mgr.update(dt=dt) self.event_manager.update(dt) if self.game_logic.game_ended: # if this is the first time after the game has ended if not self.game_logic.stop_when_unpaused: display_msg = TemporaryMessage('GOOAAALL!!', duration=2) self.add_graphic_state(display_msg) self.game_logic.stop_when_unpaused = True def add_graphic_state(self, state): state_gfx = state.build_widget() self.window.add_widget(state_gfx) self.state_mgr.push_state(state) def on_quit(): self.window.remove_widget(state_gfx) state.on_quit = on_quit
class Game: # TODO: doc ST_MENU = "menu" ST_GAMEPLAY = "gameplay" ST_PAUSE = "pause" def __init__(self): self.inputMgr = InputManager.get_instance() self.eventMgr = EventManager() self.recorder = None self.state = self.ST_MENU self.rootMenu = None def join_human_player(self, name, keyLayout): """ Join a human player to the game. @name: Player name @keyLayout: If keyLayout is None, this will be an AIPlayer, otherwise use keyLayout as an argument to instantiate a HumanPlayer. """ player = HumanPlayer(name, self.inputMgr, keyLayout) self.join_player(player) def join_player(self, player): """ Join a player to the game. @player: A Player instance. """ playerCount = len(self.world.players) # build up a snake snakeData = self.snakeDatas[playerCount] snake = Snake(self.world, player) snake.gen_body(*snakeData) player.snake = snake # let the snake's name same as the player's name snake.name = player.name # add snake and player to the world self.world.snakes.append(snake) self.world.players.append(player) # emit a SNAKE_BORN event self.eventMgr.emit(events.SnakeBorn(snake)) # bind gameevent handlers def handler(event): snake = event.snake food = event.food if snake is player.snake: snake.player.score += food.score self.eventMgr.bind(EventTypes.SNAKE_EAT, handler) return player def setup_stage(self, configData, display): """ Setups the game stage. @configData: A dict containing: * world-size: (width, height) * snakes: a list, [SnakeData1, SnakeData2, ...] * rule: Optional. A tuple (Rule, args), where `Rule` is GameRule class, `args` is the arguments to instantiate this Rule. Rule defaluts to DeathModeRule. * n-food: Integer, how many food should the world have at a time. Default to 2. SnakeData: a tuple (headPos, direction, length) """ assert self.state in self.ST_MENU self.configData = configData world = World(*configData["world-size"], eventMgr=self.eventMgr) self.nFood = configData.get("n-food", config.DEFAULT_FOOD_NUM) self.snakeDatas = configData["snakes"] self.world = world # round count self.round = 0 # setup rule if "rule" in configData: Rule, args = configData["rule"] rule = Rule(self.world, self.eventMgr, *args) else: rule = DeathModeRule(self.world, self.eventMgr) self.rule = rule # setup display self.display = display # In display, the display should bind callbacks # to some game events. display.init(self) self._needReset = True def bind_event(self, eventType, callback): """ Bind the callback to events specified by `eventType` @eventType: The event type. @callback: A callable, accepting one argument, the event. """ self.eventMgr.bind(eventType, callback) def quit(self, *args): self._quit = True self.state = self.ST_MENU def pause(self, event): pause = self.world.pause = not self.world.pause if self.state == self.ST_GAMEPLAY: self.state = self.ST_PAUSE elif self.state == self.ST_PAUSE: self.state = self.ST_GAMEPLAY def start(self): assert self.state in self.ST_MENU for i in xrange(self.nFood): self.world.gen_food() self.end_prepare() def mainloop(self): self._quit = False timer = Clock() tickCount = 0 # frame per second FPS = config.FPS # update per second UPS = config.UPS # generate food while not self._quit: # handle input self.inputMgr.update() if self._quit: break if self.state == self.ST_GAMEPLAY: # update game state if tickCount % (FPS / UPS) == 0: dprint("before update\n" + str(self.world.field)) if self.recorder: self.recorder.update() self.rule.update() self.world.update(self.eventMgr) self.round += 1 elif self.state == self.ST_MENU: if self.rootMenu: self.rootMenu.game_update() # render using display self.display.render(self.world) timer.tick(FPS) tickCount += 1 # stop recorder if self.recorder: self.recorder.stop() self.recorder.quit() self.display.quit() dprint("quit normally") def end_prepare(self): assert self.state == self.ST_MENU self.state = self.ST_GAMEPLAY
class Game(object): """Manages other game modules.""" def __init__(self, min_cycle_time=10): self.min_cycle_time = min_cycle_time self._run = False self._last_update = 0 self._last_mouse_pos = None self._selecting = False self._select_start_pos = None self._selection_rect = None self._mouse_right_down = False pygame.init() screen_width, screen_height = screen_size = (1024, 768) self._screen = pygame.display.set_mode(screen_size, pygame.DOUBLEBUF) self._map = Map('default') self._camera = Camera(screen_size) self._renderer = Renderer(self._screen, self._camera) self._objects = ObjectManager(self._map.size) self._event_mgr = EventManager() self._event_mgr.subscribe(pygame.QUIT, self._handle_quit) self._event_mgr.subscribe(self._camera.move_event, self._camera_moved) self._input = InputManager(self._event_mgr) self._input.set_keybind(pygame.K_ESCAPE, self.stop) self._input.set_keybind(pygame.K_q, self.stop) self._input.set_hotarea((0, 0, screen_width, 2), self._camera.set_move, {'y': -1}) self._input.set_hotarea((0, screen_height - 2, screen_width, 2), self._camera.set_move, {'y': 1}) self._input.set_hotarea((0, 0, 2, screen_height - 2), self._camera.set_move, {'x': -1}) self._input.set_hotarea((screen_width - 2, 0, 2, screen_height), self._camera.set_move, {'x': 1}) self._input.set_hotarea((2, 2, screen_width - 4, screen_height - 4), self._camera.stop_moving) self._event_mgr.subscribe(self._input.mouse_drag_start, self._select_start) self._event_mgr.subscribe(self._input.mouse_drag_update, self._select_update) self._event_mgr.subscribe(self._input.mouse_drag_end, self._select_end) self._event_mgr.subscribe(self._input.lclick, self._leftclick) self._event_mgr.subscribe(self._input.rclick, self._rightclick) self._event_mgr.subscribe(self._input.rsclick, self._right_shiftclick) def run(self): """Run the main game loop.""" self._load() self._last_update = pygame.time.get_ticks() self._run = True while self._run: gametime = pygame.time.get_ticks() time_passed = gametime - self._last_update if time_passed < self.min_cycle_time: pygame.time.wait(1) # give other threads some cpu time continue self._update(gametime, time_passed) self._draw() self._shutdown() def _load(self): unit_tex = self._renderer.load_texture('cross.png') for x in range(0, 48, 16): unit_pos = (x, 16) unit_rect = Rect(unit_pos, self._renderer.texture_size(unit_tex)) unit_id = self._objects.create(Unit, unit_rect) self._renderer.assign_texture(unit_id, unit_tex) def _shutdown(self): pass def _update(self, gametime, time_passed): self._event_mgr.update() self._objects.update(gametime) self._camera.update(time_passed) self._last_update = gametime #noinspection PyUnusedLocal def _camera_moved(self, event): if self._selecting: self._update_selection_rectangle(self._last_mouse_pos) def _select_start(self, event): self._selecting = True self._select_start_pos = self._camera.point_to_map(event.pos) self._update_selection_rectangle(event.pos) #noinspection PyUnusedLocal def _select_end(self, event): self._selecting = False self._objects.select_area(self._selection_rect) def _select_update(self, event): self._last_mouse_pos = event.pos self._update_selection_rectangle(event.pos) def _update_selection_rectangle(self, pos): map_pos = self._camera.point_to_map(pos) self._selection_rect = Rect(min(self._select_start_pos[0], map_pos[0]), min(self._select_start_pos[1], map_pos[1]), abs(map_pos[0] - self._select_start_pos[0]), abs(map_pos[1] - self._select_start_pos[1])) def _leftclick(self, event): self._objects.select_at(self._camera.point_to_map(event.pos)) def _rightclick(self, event): self._objects.send_selected(self._camera.point_to_map(event.pos)) def _right_shiftclick(self, event): self._objects.send_selected(self._camera.point_to_map(event.pos), True) def _draw(self): self._renderer.frame_start() self._renderer.draw_map(self._map) objs = self._objects.query(self._camera.view_rect) self._renderer.draw_objects(objs) if self._selecting: self._renderer.draw_rectangle(self._selection_rect, (255, 0, 0)) self._renderer.frame_end() def _draw_objects(self, surface, area): pass #noinspection PyUnusedLocal def _handle_quit(self, event): self.stop() def stop(self): self._run = False
def init(*args): em = EventManager() disp = pygame.Surface([800, 600]) disp.fill([0, 0, 0]) font = textfx.WrapFont(30, 760) bg = Character.default.border([780, 100]).convert() bg.set_alpha(256) disp.blit(bg, [0, 0]) t = font.render( "Welcome to the unlock screen! As you do more in this " "game, new features will sometimes appear. By playing the " "game at least once, you've managed to unlock this unlock " "screen, for example. Keep practicing, and more things will " "appear..." ) disp.blit(t, t.get_rect(midleft=[20, 60])) if config.getboolean("unlock", "single"): bg.set_alpha(256) disp.blit(bg, [0, 120]) t = font.render( "Congratulations! By scoring over 20,000 points in a 2/3 versus " "match, you've unlocked single player mode. It's a lot " "harder, so you should practice your crystal building and " "combo setups." ) disp.blit(t, t.get_rect(midleft=[20, 180])) else: bg.set_alpha(127) disp.blit(bg, [0, 120]) if config.getboolean("unlock", "unixbros"): bg.set_alpha(256) disp.blit(bg, [0, 240]) t = font.render( "By breaking a crystal of over 16 gems, you've unlocked two more " "characters - The Yuniks brothers. Both encourage a very " "unique style of attacks. Go check them out." ) disp.blit(t, t.get_rect(midleft=[20, 300])) else: bg.set_alpha(127) disp.blit(bg, [0, 240]) if config.getboolean("unlock", "combat"): bg.set_alpha(256) disp.blit(bg, [0, 360]) t = font.render( "By getting at least a 4 chain, you've unlocked combat " "mode. If this is on, special attack rocks might appear in " "versus mode, that have strange effects on the other " "player. Enable it in the setup menu." ) disp.blit(t, t.get_rect(midleft=[20, 420])) else: bg.set_alpha(127) disp.blit(bg, [0, 360]) if config.getboolean("unlock", "cpuversus"): bg.set_alpha(256) disp.blit(bg, [0, 480]) t = font.render( "You've made it at least halfway through arcade mode! " "You can now practice against any dwarf, on any " "of the AI levels." ) disp.blit(t, t.get_rect(midleft=[20, 540])) else: bg.set_alpha(127) disp.blit(bg, [0, 480]) wipes.wipe_in(disp) pygame.display.update() quit = False while not quit: for ev in em.wait(): quit = quit or ev.type == QUIT or (ev.type == PLAYER and ev.key in [ROT_CC, ROT_CW, CONFIRM]) return True
class GameController(object): def __init__(self): pygame.init() self.screen = pygame.display.set_mode(SCREENSIZE, 0, 32) self.background = None self.background_edit = None self.background_connection = None self.background_check = None self.setBackground() self.grid = [] #list of lines that define the grid self.setup() self.events = EventManager(self) def setup(self): self.vertices = {} self.vertexShadow = None self.showVertices = True self.editMode = False #move vertices around self.connectionMode = False #connect vertices together self.checkMode = False #For checking the vertices properties by clicking on them self.probeMode = False #For testing. Create a probe point (vertex) self.drawGraphQuickMode = False self.hoverVertex = None #vertex the mouse is hovering over at any point in time self.vertex0 = None #vertex that connection line is coming from self.followMouse = False #If true then the hoverVertex will follow the mouse if it is not None self.drawConnectionLine = False self.connectionLine = None #The line that shows when you are drawing a line from one vertex to the next self.showGrid = False self.vertex_key_ctr = 0 self.bsp = None self.testvertexlist = [] self.clock = pygame.time.Clock() def setBackground(self): self.background = pygame.surface.Surface(SCREENSIZE).convert() self.background.fill(DARKGRAY) self.background_edit = pygame.surface.Surface(SCREENSIZE).convert() self.background_edit.fill(BACKGROUNDEDIT) self.background_connection = pygame.surface.Surface( SCREENSIZE).convert() self.background_connection.fill(CONNECTIONMODECOLOR) self.background_check = pygame.surface.Surface(SCREENSIZE).convert() self.background_check.fill(CHECKMODECOLOR) self.background_probe = pygame.surface.Surface(SCREENSIZE).convert() self.background_probe.fill(PROBEMODECOLOR) self.segments = [ ] #make global for testing so we can see them dynamically def defineGrid(self): '''Defines vertical and horizontal lines''' #Define vertical lines for i in range(NCOLS): self.grid.append( Line(Vector2(i * TILEWIDTH, 0), Vector2(i * TILEWIDTH, SCREENHEIGHT), GRAY)) #Define horizontal lines for i in range(NROWS): self.grid.append( Line(Vector2(0, i * TILEHEIGHT), Vector2(SCREENWIDTH, i * TILEHEIGHT), GRAY)) def update(self): '''Main game loop''' x, y = pygame.mouse.get_pos() mouseposition = Vector2(x, y) self.hoverVertex = None for vertex in self.vertices.values(): if vertex.inbounds(mouseposition): self.hoverVertex = vertex if self.editMode: if self.hoverVertex is not None: if self.followMouse: self.hoverVertex.position = mouseposition if self.probeMode: if self.probe is not None: if self.followMouse: self.probe.position = mouseposition if self.vertexShadow is not None: self.vertexShadow.update(mouseposition) if self.connectionLine is not None: self.connectionLine.vector1 = mouseposition self.events.update(mouseposition) self.render() def getVertex(self, position): '''Return the key to the vertex that matches the position. Return None if no matches.''' for key in self.vertices.keys(): if self.vertices[key].position == position: return key return None def getTestSector(self): '''From the testsectors file. ''' L = testsectors.sector1() print("Test sector set") def getAllSegments(self): '''Just returns a list of all of the segments. [(1,2), (2,3), (4,5), ...]. as SegmentDirected objects.''' segments = [] for key in self.vertices.keys(): for i in range(len(self.vertices[key].neighbors)): segments.append( Segment(self.vertices[key], self.vertices[key].neighbors[i])) return segments def createBinaryTree(self): '''Performs the steps necessary to split the segments into a space partitioned binary tree. PRESS B''' self.segments = self.getAllSegments() self.bsp = BSP(self.segments) self.bsp.createTree( ) #just for testing. Normally doesn't return anything self.segments = self.bsp.segmentList def stepThroughTree(self): '''This just helps me step through the tree one iteration at a time to see what it is doing for debugging.''' self.bsp.traverseTree() self.segments = self.bsp.segmentList def createVertex(self, position): '''Create a new vertex and add it to the dictionary''' vertex = Vertex(position, key=self.vertex_key_ctr) self.vertices[self.vertex_key_ctr] = vertex self.vertex_key_ctr += 1 self.vertexShadow = None def createVertexShadow(self, position): self.vertexShadow = VertexShadow(position) def createConnectionLine(self): '''The line that is shown when connecting two nodes together. vertex0 is where the line is anchored''' self.vertex0 = self.hoverVertex position = self.hoverVertex.position self.connectionLine = Line(position, position, RED) def connectVerticesDirected(self): '''Only vertex 1 knows about vertex 2''' self.vertex0.addNeighbor(self.hoverVertex) #def connectVerticesUndirected(self): # '''Connect two vertices together such that they are neighbors of each other''' # print("Undirected") # #print(str(self.vertex0.key) + " <==> " + str(self.hoverVertex.key)) # self.vertex0.addNeighbor(self.hoverVertex) # self.hoverVertex.addNeighbor(self.vertex0) def removeNeighbors(self): '''Remove all the neighbors from the vertices''' for vertex in self.vertices.values(): vertex.neighbors = [] def render(self): if self.editMode: self.screen.blit(self.background_edit, (0, 0)) elif self.connectionMode: self.screen.blit(self.background_connection, (0, 0)) elif self.checkMode: self.screen.blit(self.background_check, (0, 0)) elif self.probeMode: self.screen.blit(self.background_probe, (0, 0)) else: self.screen.blit(self.background, (0, 0)) if self.showGrid: for line in self.grid: line.render(self.screen) if self.connectionLine is not None: self.connectionLine.render(self.screen) for vertex in self.vertices.values(): vertex.renderConnections(self.screen) if self.showVertices: for vertex in self.vertices.values(): vertex.render(self.screen) if self.vertexShadow is not None: self.vertexShadow.render(self.screen) #This is just to show where the line splits will be made when doing bsp if len(self.testvertexlist) > 0: #self.testvertexlist.render(self.screen) for b in self.testvertexlist: b.render(self.screen) if len(self.segments) > 0: for seg in self.segments: seg.render(self.screen) pygame.display.update()
def __init__(self, event_manager: EventManager, player: Player, grid_manager: GridManager): self.event_manager = event_manager self.player = player self.grid_manager = grid_manager event_manager.subscribe(PlayerMoveEvent, self)
def __init__(self, i): self.i = i self.times = [] self.packets = [] def on_reception(self, t, p): self.times.append(t) self.packets.append(p) class MockFlow: def __init__(self, i): self.i = i em = EventManager(logging=False) h1 = MockHost('H1') h2 = MockHost('H2') f = MockFlow('F') # rate 1 pkt/sec, delay 10s l = Link(em, 'L', h1, h2, DATA_PACKET_SIZE, 10, DATA_PACKET_SIZE * 10, debug=False) l.on_packet_entry( 0, Packet('P1', f, h1, h2, False, False, False, 1, 0, DATA_PACKET_SIZE)) l.on_packet_entry(