def setPlayerSelectionScreen(self): self.currentScreenInstance = self.playerScreen playerScreenBackButton = Button(50, 50, 50, 50, "<-", 40) playerScreenBackButton.setCallBack(self.setStartScreen) self.playerScreen.add(playerScreenBackButton) self.changeScreen(5)
def __init__(self): super(Zone, self).__init__() w, h = director.get_window_size() self.mode = model.INDUSTRY self.zone_images = { model.INDUSTRY: pyglet.resource.image('industry.png'), model.LOGISTICS: pyglet.resource.image('logistics.png'), model.MILITARY: pyglet.resource.image('military.png') } self.icons = { ('privileged', False): pyglet.resource.image('icon-priv_off.png'), ('privileged', True): pyglet.resource.image('icon-priv_on.png'), } w, h = director.get_window_size() self.active = Sprite(self.zone_images[model.INDUSTRY], anchor=((-(w-550), -(h-605))) ) self.add(self.active, z=-1) self.add(Button('but-ind_off.png', (self.zone1_x, self.y), 'industry', self.switch_zone_to), name=model.INDUSTRY) self.add(Button('but-log_off.png', (self.zone2_x, self.y), 'logistics', self.switch_zone_to), name=model.LOGISTICS) self.add(Button('but-mil_off.png', (self.zone3_x, self.y), 'military', self.switch_zone_to), name=model.MILITARY)
def __init__(self, display): MainScreen.__init__(self, display) self.btn_main_menu = Button(lang.data["main menu"], [ 240, 50], [340, 530], 38) self.slider = Slider() image_rool = pygame.image.load(os.path.join('images/rools.png')) self.image_rool = pygame.transform.scale( image_rool, (800, image_rool.get_height() * 800 // image_rool.get_width()))
def first_screen(self): # Preenchendo background self.screen.fill(self.black) # Posição de referência self.first_screen_y = 200 self.first_screen_x = 150 # Desenhando "Escolha o oponente" self.screen.blit(self.font.render("Escolha o nível", True, self.white), (self.first_screen_y + 40, self.first_screen_x - 50)) # Criando botões self.buttons.append( Button(self.first_screen_y, self.first_screen_x, H1())) self.buttons.append( Button(self.first_screen_y, self.first_screen_x + 50, H2())) self.buttons.append( Button(self.first_screen_y, self.first_screen_x + 100, KNN())) while True: # 30 FPS self.clock.tick(30) # Armazenando a posição do mouse self.mouse = pg.mouse.get_pos() self.screen.blit(self.images.load_piece(1), self.buttons[0].pos) self.screen.blit( self.font.render("H1", True, self.white), (self.buttons[0].pos[0] + 50, self.buttons[0].pos[1] + 7)) self.screen.blit(self.images.load_piece(2), self.buttons[1].pos) self.screen.blit( self.font.render("H2", True, self.white), (self.buttons[1].pos[0] + 50, self.buttons[1].pos[1] + 7)) self.screen.blit(self.images.load_piece(3), self.buttons[2].pos) self.screen.blit( self.font.render("KNN", True, self.white), (self.buttons[2].pos[0] + 50, self.buttons[2].pos[1] + 7)) # Desenhando os botões for button in self.buttons: button.verify(self.mouse) if button.rect.collidepoint(self.mouse): if pg.mouse.get_pressed()[0] == 1: #self.player2 = button.computer self.page = 2 return for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() exit(0) # Atualizando a tela pg.display.update()
def __init__(self, display, size_of_board, side, client): MainScreen.__init__(self, display) self.side = side self.client = client self.go_board = Board(size_of_board) self.btn_pass = Button(lang.data["pass"], [150, 70], [700, 300]) self.btn_resign = Button(lang.data["resign"], [150, 70], [700, 425]) self.show_err_msg = False self.request_for_pass = False
def _init_choice_buttons(self): self.button_frame = RelativeWidget(parent = self.window, left = 0, right = 0, top=0, height = 50) increment = 1 / len(self.button_text) for index, t in enumerate(self.button_text): left = index * increment right = 1 - left - increment button_holder = RelativeWidget(parent = self.button_frame, left = left, right = right, top=0, bottom=0) button = Button(parent=button_holder, text=t, text_padding = 3) button.push_handlers(on_press = self._button_cb)
def __init__(self, experiment): SceneBase.__init__(self) # data to keep track of the experiment's progress self.experiment = experiment self.experiment_running = False self.total = experiment.iterations # constants defining where stuff can be drawn self.MARGIN = 96 self.TITLE_SIZE = 56 self.LABEL_SIZE = 48 self.INFO_BOX = pygame.Rect(self.MARGIN, self.MARGIN * 1.5, 1920 - self.MARGIN * 2, 1080 * 0.66 - 2 * self.MARGIN) self.PROGRESS_BAR_WIDTH = 1920 - 2 * self.MARGIN self.PROGRESS_BAR_HEIGHT = 100 self.PROGRESS_BAR_X = self.MARGIN self.PROGRESS_BAR_Y = self.INFO_BOX.y + self.INFO_BOX.height + 0.5 * self.PROGRESS_BAR_HEIGHT self.PROGRESS_BORDER = pygame.Rect(self.PROGRESS_BAR_X, self.PROGRESS_BAR_Y, self.PROGRESS_BAR_WIDTH, self.PROGRESS_BAR_HEIGHT) self.PROGRESS_BG = pygame.Rect(self.PROGRESS_BAR_X + 4, self.PROGRESS_BAR_Y + 4, self.PROGRESS_BAR_WIDTH - 8, self.PROGRESS_BAR_HEIGHT - 8) self.title_font = FontService.get_regular_font(self.TITLE_SIZE) self.label_font = FontService.get_regular_font(self.LABEL_SIZE) font_color = Settings.theme['font'] self.heading_surface = self.title_font.render( "%s vs %s" % (self.experiment.p1.name, self.experiment.p2.name), False, font_color) self.heading_size = self.title_font.size( "%s vs %s" % (self.experiment.p1.name, self.experiment.p2.name)) self.heading_location = (self.INFO_BOX.centerx - 0.5 * self.heading_size[0], self.INFO_BOX.top - 1.5 * self.heading_size[1]) self.insertion_msg_surface = self.label_font.render( "Saving results... (This may take some time)", False, font_color) self.insertion_msg_size = self.title_font.size( "Saving results... (This may take some time)") self.insertion_msg_location = (self.INFO_BOX.centerx - 0.5 * self.insertion_msg_size[0], self.PROGRESS_BG.bottom + 12) # "Done" button def back_to_mm(): SceneManager.go_to_main_menu(self) self.done_btn = Button(1920 * 0.5 - 150, self.PROGRESS_BG.bottom + 24, 300, 100, "Done", back_to_mm)
def __init__(self, parent=None): super().__init__(parent) self.screen_width, self.screen_height = get_screen_res(screen) self.screen_res: str = f'{self.screen_width}x{self.screen_height}' self.payload: Dict[str, str] = { 'sorting': 'random', 'categories': '100', 'atleast': self.screen_res } self.sw = StackedWidget() self.progressbar = ProgressBar() self.progressbar.hide() self.prev_btn = Button('angle-left.svg', key='left') self.next_btn = Button('angle-right.svg', key='right') self.update_btn = Button('sync-alt.svg', ' Update', key='r') self.apply_btn = Button('check.svg', 'Apply') self.save_btn = Button('save.svg', 'Save') self.prev_btn.clicked.connect(self.prev) self.next_btn.clicked.connect(self.next) self.apply_btn.clicked.connect(self.apply) self.update_btn.clicked.connect(self.update_) self.save_btn.clicked.connect(self.save) self.saved_msg = QLabel('Saved') self.image_count = QLabel() self.image_res = QLabel() self.saved_msg.setStyleSheet(f'color: {INFO_COLOR}') self.image_count.setStyleSheet(f'color: {INFO_COLOR}') self.image_res.setStyleSheet(f'color: {INFO_COLOR}') self.info_layout = QHBoxLayout() self.info_layout.addWidget(self.progressbar) self.info_layout.addStretch() self.info_layout.addWidget(self.image_count) self.info_layout.addWidget(self.image_res) button_layout = QHBoxLayout() button_layout.addWidget(self.prev_btn) button_layout.addWidget(self.next_btn) button_layout.addWidget(self.update_btn) button_layout.addWidget(self.apply_btn) button_layout.addWidget(self.save_btn) self.main_layout = QVBoxLayout() self.main_layout.addLayout(self.info_layout) self.main_layout.addWidget(self.sw) self.main_layout.addLayout(button_layout) self.setLayout(self.main_layout) self.sw.added.connect(self.change_image_count)
def save_new_subtopic(self): if self.selected_subtopic.cget('text') != self.new_subtopic_label_text: return self.subtopic_dialog = Toplevel(self.root) self.subtopic_dialog.title('New Note: Subtopic Input Dialog') headlab = LabelH3(self.subtopic_dialog, text='Unique subtopic name for new note:') self.subtopic_input = Entry(self.subtopic_dialog, width=64) self.subtopic_input.focus_set() buttonbox = Frame(self.subtopic_dialog) self.subtopic_dialog.grid_columnconfigure(0, weight=1) new_note_ok = Button(buttonbox, text='Submit Note and Subtitle', command=self.submit_new_note) new_note_cancel = Button(buttonbox, text='Cancel', command=self.close_subtopic_dialog) headlab.grid(column=0, row=0, pady=(24, 0), columnspan=2) self.subtopic_input.grid(column=0, row=1, padx=24, pady=24, columnspan=2) buttonbox.grid(column=1, row=2, sticky='we', padx=24, pady=24) new_note_ok.grid(column=0, row=0, sticky='e', padx=12) new_note_cancel.grid(column=1, row=0, sticky='e', padx=12) self.subtopic_dialog.bind('<Escape>', self.close_subtopic_dialog) self.subtopic_dialog.protocol('WM_DELETE_WINDOW', self.close_subtopic_dialog)
def setEndScreen(self): self.endScreen.gamePieceGroup = pygame.sprite.Group() score = self.gameScreen.timer self.currentScreenInstance = self.endScreen self.endScreen.add(TextDisplay(self.width // 2, self.height // 4 + 100, \ 100, 50, "You lasted: " + str(score / 100) + "s", 40)) self.endScreen.add( TextDisplay(self.width // 2, self.height // 4, 100, 50, "Game Over!!", 40)) submitScoreButton = Button(self.width // 2, self.height // 4 + 50, 100, 50, "Return to Main Screen!!", 40) submitScoreButton.setCallBack(self.setStartScreen) self.endScreen.add(submitScoreButton) self.changeScreen(2)
def __init__(self, render_surface, surface_size): Screen.__init__(self, render_surface, surface_size) self.widgets = { "heading_kanjioptionsscreen": Heading(self.render_surface, (0, 0, 1920, 100), "Kanji Options").set_themed(), "button_back": Button(self.render_surface, (10, 10, 230, 80), "Back").set_themed(), } self.checkboxes = { "kanji_show_kun": Checkbox(self.render_surface, (600, 400, 720, 100), "Show 'kun' reading").set_themed(), "kanji_show_on": Checkbox(self.render_surface, (600, 550, 720, 100), "Show 'on' reading").set_themed(), "kanji_show_dutch": Checkbox(self.render_surface, (600, 700, 720, 100), "Show Dutch").set_themed(), } # set the 'selected' property of the checkboxes for checkbox_id, checkbox in self.checkboxes.items(): checkbox.selected = Settings.get(checkbox_id)
def show_order(self, order, cta_title, cta_closure): widgets = [] widgets += [urwid.Divider()] # Order Items for item in order.menu_items: quantity = str(item.cart_quantity) columns = urwid.Columns([ ("fixed", 2, urwid.Text(quantity, align="right")), ("fixed", 1, urwid.Divider()), ("weight", 1, ColoredText(item.title, colors.ITEM_MEAL)), ]) widgets += [columns] # Driver name if order.driver_name: driver_name = "Driver's name: %s" % order.driver_name driver_phone = "Driver's phone: %s" % order.driver_phone_number if order.status == Order.STATUS_UNRATED: eta_tpl = "Delivered: %s" else: eta_tpl = "Estimated Time: %s" ETA = eta_tpl % pretty_date(order.customer_eta * 60) widgets += [urwid.Divider()] widgets += [ColoredText(driver_name, colors.LOW)] widgets += [ColoredText(driver_phone, colors.LOW)] widgets += [ColoredText(ETA, colors.LOW)] # Address address = [(colors.DELIVER_LABEL, "Delivering to ")] address += [(colors.DELIVER_ADDRESS, order.address.street_address)] widgets += [urwid.Divider()] widgets += [urwid.Text(address)] # Track driver button cta = Button(cta_title, cta_closure) if order.driver_location and cta: columns = urwid.Columns([ ("weight", 0.2, urwid.Divider()), ("weight", 0.6, cta), ("weight", 0.2, urwid.Divider()), ]) widgets += [urwid.Divider()] widgets += [columns] else: widgets += [urwid.Divider()] widgets += [urwid.Text("Waiting for driver...", align="center")] pile = urwid.Pile(widgets) pile = urwid.Padding(pile, left=2, right=2) pile = urwid.Columns([ ("weight", 0.2, urwid.Divider()), ("weight", 0.6, ColoredLineBox(pile, title="Food on your way!")), ("weight", 0.2, urwid.Divider()), ]) self.body = pile
def createCloseButton(self, parent): """ Create a button for closing the window, setting the proper label and icon. """ return Button(parent, Message.LABEL_BUTTON_CLOSE, Icon.ACTION_CLOSE, command=self.close)
def _fillButtonsFrame(self, frame): """ Add button to the bottom frame if the selectMode is distinct from SELECT_NONE. """ Button(frame, "Close", Icon.BUTTON_CLOSE, command=self._close).grid(row=0, column=0, padx=(0,5)) if self.selectButton: HotButton(frame, self.selectButton, Icon.BUTTON_SELECT, command=self._select).grid(row=0, column=1)
def third_screen(self): # Preenchendo background self.screen.fill(self.black) # Posição de referência self.third_screen_y = self.height / 2 self.third_screen_x = self.width / 2 # Desenhando se venceu ou perdeu self.screen.blit( self.font.render("Você " + self.result, True, self.white), (self.third_screen_x - 75, self.third_screen_y - 150)) # Criando botões button = Button(self.third_screen_x - 130, self.third_screen_y) while True: # 30 FPS self.clock.tick(30) # Desenhando o botão pg.draw.rect(self.screen, button.color, button.rect, 2) self.screen.blit(self.font.render('Novo Jogo', True, button.color), button.pos) # Armazenando a posição do mouse self.mouse = pg.mouse.get_pos() # Verificando a posição do mouse button.verify(self.mouse) if button.rect.collidepoint(self.mouse): if pg.mouse.get_pressed()[0] == 1: self.page = 1 return for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() exit(0) # Atualizando a tela pg.display.update()
def __init__(self, display, mode): MainScreen.__init__(self, display) sizes = [5, 6, 7, 8, 9, 11, 13, 15, 19] self.btn_sizes = [] for i in range(len(sizes)): self.btn_sizes.append( Button('%dx%d' % (sizes[i], sizes[i]), [120, 120], [150 * (i % 3) + 200, 150 * (i // 3) + 100])) self.show = True self.mode = mode
class Rools(MainScreen): def __init__(self, display): MainScreen.__init__(self, display) self.btn_main_menu = Button(lang.data["main menu"], [ 240, 50], [340, 530], 38) self.slider = Slider() image_rool = pygame.image.load(os.path.join('images/rools.png')) self.image_rool = pygame.transform.scale( image_rool, (800, image_rool.get_height() * 800 // image_rool.get_width())) def update_screen(self): image = pygame.transform.chop( self.image_rool, (0, 0, 0, (self.slider.value / 100) * (self.image_rool.get_height() - 500))) image = pygame.transform.chop( image, (0, 500, 0, image.get_height() - 500)) self.display.blit(image, (20, 20)) self.btn_main_menu.draw(self.display) self.slider.draw(self.display) if self.btn_main_menu.active: self.show = False
def _create_button_helper(self, info, callback): button = Button(); #Images. button.load_images(info["normal_image"], info["pressed_image"]); #Position. button.set_position(info["position"]); #Callback. button.set_click_callback(callback); #Add to scene. self.add(button, layer = PostPhotoScene._LAYER_INDEX_BUTTONS); return button;
def _init_buttons(self): #Initialize the button. self._take_photo_button = Button(); #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_TAKEPHOTO_BUTTON); #Set the button properties. self._take_photo_button.load_images(info["normal_image"], info["pressed_image"]); self._take_photo_button.set_position(info["position"]); self._take_photo_button.set_click_callback(self._on_take_photo_button_pressed); #Add to scene. self.add(self._take_photo_button, layer = CameraScene._LAYER_INDEX_PHOTO_BUTTON);
def __init__(self, screen): self.screen = screen self.stopped = False self.targetfps = 60 self.black = 0, 0, 0 self.musicenabled = True self.looping = LoopingCall(self.tick) # Network config input fields self.addressfield = InputField('Server Address:',Rect(235,540,500,25),text='localhost') self.portfield = InputField('Server Port:',Rect(235,570,500,25),text='40100',numeric=True) self.errorlabel = TextLabel('',(235, 600),25,fgcolor=(255, 0, 0)) # Enable/disable the background music self.musicbutton = Button('Music Enabled',Rect(335,630,300,40),self.toggleMusic) # Start a game or quit self.hostbutton = Button('Host a Game',Rect(40,710,270,50),self.host) self.joinbutton = Button('Join a Game',Rect(350,710,270,50),self.join) self.quitbutton = Button('Quit',Rect(660,710,270,50),self.stop) # Widgets and focus route (for tabbing through the elements) self.widgets = { self.addressfield: self.portfield, self.portfield: self.musicbutton, self.errorlabel: None, self.musicbutton: self.hostbutton, self.hostbutton: self.joinbutton, self.joinbutton: self.quitbutton, self.quitbutton: self.addressfield } self.focus(self.addressfield)
def __init__(self): pygame.init() pygame.display.set_caption('Alt-Land-Is') pygame.event.set_blocked(pygame.MOUSEMOTION) self.screen = pygame.display.set_mode(self.SIZE) self.game = game_logic.Game('Fenriz', 1) self.eventManager = EventManager() self.drawables = [] # List of objects to be drawn to the screen on every cycle self.updateables = {} # Dict of object, that can have their data updated playerSprite = Sprite( self.screen, (self.VIEWRANGE * TILE_SIZE + self.MAP_MARGIN, self.VIEWRANGE * TILE_SIZE + self.MAP_MARGIN), self.CHAR_IMG) charStatusBox = CharactorStatusBox(self.screen, pygame.Rect(750, 20, 200, 120), pygame.Color('gray25'), self.BORDER_COLORS) statusBox = StatusBox(5, self.screen, pygame.Rect(50, 650, 450, 100)) bActivate = Button(self.screen, pygame.Rect(760, 250, 40, 40), 'images/gui/b_activate.png') bActivate.bind(EVT_LEFT_CLICK, self._activateButtonHandler) coordBox = TextBox(self.screen, pygame.Rect(750, 710, 40, 40)) mapp = Map(surface = self.screen, topLeft = (self.MAP_MARGIN, self.MAP_MARGIN), mapRange = self.VIEWRANGE, tileSize = TILE_SIZE, fowTileName = 'images/terrain/smoke.png', borderColors = self.BORDER_COLORS, terrains = self.game.terrains ) inv = Inventory(surface = self.screen, topLeft = (750,500), tileSize = TILE_SIZE, borderColors = self.BORDER_COLORS, size = (4, 2) ) floorItems = Inventory(surface = self.screen, topLeft = (750,610), tileSize = TILE_SIZE, borderColors = self.BORDER_COLORS, size = (4, 1) ) self.drawables.append(mapp) # Add map first, so that other stuff can be drawn on it self.drawables.append(bActivate) self.drawables.append(statusBox) self.drawables.append(coordBox) #self.drawables.append(playerSprite) self.drawables.append(inv) self.drawables.append(floorItems) self.drawables.append(charStatusBox) self.updateables['coordBox'] = coordBox self.updateables['statusBox'] = statusBox self.updateables['charStatusBox'] = charStatusBox self.updateables['map'] = mapp self.updateables['inv'] = inv self.updateables['floorItems'] = floorItems self.eventManager.registerListener(KeyboardController(self.eventManager)) self.eventManager.registerListener(GameController(self.game)) self.eventManager.registerListener(bActivate) self.oneTimers = [] # Listeners that only need to live for one cycle
class MainScreen: BACKGROUND = pygame.image.load('WALLP2.png') def __init__(self, screen): self.screen = screen self.stopped = False self.targetfps = 60 self.black = 0, 0, 0 self.musicenabled = True self.looping = LoopingCall(self.tick) # Network config input fields self.addressfield = InputField('Server Address:',Rect(235,540,500,25),text='localhost') self.portfield = InputField('Server Port:',Rect(235,570,500,25),text='40100',numeric=True) self.errorlabel = TextLabel('',(235, 600),25,fgcolor=(255, 0, 0)) # Enable/disable the background music self.musicbutton = Button('Music Enabled',Rect(335,630,300,40),self.toggleMusic) # Start a game or quit self.hostbutton = Button('Host a Game',Rect(40,710,270,50),self.host) self.joinbutton = Button('Join a Game',Rect(350,710,270,50),self.join) self.quitbutton = Button('Quit',Rect(660,710,270,50),self.stop) # Widgets and focus route (for tabbing through the elements) self.widgets = { self.addressfield: self.portfield, self.portfield: self.musicbutton, self.errorlabel: None, self.musicbutton: self.hostbutton, self.hostbutton: self.joinbutton, self.joinbutton: self.quitbutton, self.quitbutton: self.addressfield } self.focus(self.addressfield) # Call our tick function for each frame def start(self): self.looping.start(1./self.targetfps) # Start up the background music pygame.mixer.music.load('sounds/song_1.ogg') pygame.mixer.music.play(-1) # Stop calling our tick function, and activate the next screen, if there is one def stop(self, newscreen=None): self.looping.stop() self.stopped = True if newscreen: newscreen.start() else: reactor.stop() def tick(self): # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: self.stop() elif event.type == pygame.KEYDOWN: if event.unicode == '\x09': self.focus(self.widgets[self.focuswidget]) else: self.focuswidget.sendKey(event.unicode) elif event.type == pygame.MOUSEBUTTONDOWN: for widget in self.widgets: if widget.click(event.button,event.pos): self.focus(widget) # Tick-tock for widget in self.widgets: widget.tick() # Are we done, yet? if self.stopped: return # Update the screen self.screen.fill(self.black) self.screen.blit(MainScreen.BACKGROUND,(0, 0)) for widget in self.widgets: widget.draw(self.screen) pygame.display.flip() def focus(self, widget): self.focuswidget = widget for w in self.widgets: w.setFocus(w is widget) # Turn the background music on or off def toggleMusic(self): self.musicenabled = not self.musicenabled if self.musicenabled: pygame.mixer.music.play(-1) self.musicbutton.setText('Music Enabled') else: pygame.mixer.music.stop() self.musicbutton.setText('Music Disabled') # Start up a game on the given port (ignore the address) def host(self): port = int(self.portfield.getText()) if port < 1 or port > 65535: self.errorlabel.setText('invalid port number') else: self.stop(Hoster(self.screen,port)) # Attempt to connect to the given address on the given port and join a game def join(self): address = self.addressfield.getText() port = int(self.portfield.getText()) if port < 1 or port > 65535: self.errorlabel.setText('invalid port number') else: self.stop(Joiner(self.screen,address,port))
class CameraScene(BaseScene): ############################################################################ ## Constants ## ############################################################################ #Required Keys. _KEY_CAMERA_PLACEHOLDER_SPRITE = "camera_placeholder"; _KEY_CAMERA_FRAME_SPRITE = "camera_frame"; _KEY_TAKEPHOTO_BUTTON = "take_photo"; _KEY_STATIC_SPRITES = "static_sprites"; _KEY_COUNTDOWN_SPRITES = "countdown"; _REQUIRED_KEYS = [ _KEY_CAMERA_PLACEHOLDER_SPRITE, _KEY_CAMERA_FRAME_SPRITE, _KEY_TAKEPHOTO_BUTTON, _KEY_STATIC_SPRITES, _KEY_COUNTDOWN_SPRITES, ]; #How much time each countdown step will take (in ms). _COUNTDOWN_CLOCK_TIME = 10; #Layers. _LAYER_INDEX_STATIC_SPRITE = 1; _LAYER_INDEX_CAMERA_SPRITE = 2; _LAYER_INDEX_FRAME_SPRITE = 3; _LAYER_INDEX_PHOTO_BUTTON = 4; _LAYER_INDEX_COUNTDOWN_SPRITE = 5; ############################################################################ ## CTOR ## ############################################################################ def __init__(self): BaseScene.__init__(self); ## iVars ## #Filenames and Content. self._config_filename = None; self._config_contents = None; #UI Elements. self._countdown_sprite = None; self._camera_sprite = None; self._frame_sprite = None; self._take_photo_button = None; #Countdown clock. self._countdown_clock = BasicClock(CameraScene._COUNTDOWN_CLOCK_TIME, self._on_countdown_timer_tick); self._camera_sprite_size = None; ############################################################################ ## Overriden Methods ## ############################################################################ def start(self): Logger.instance().log_debug("CameraScene.start"); def end(self): Logger.instance().log_debug("CameraScene.end"); ############################################################################ ## Init ## ############################################################################ def init(self): Logger.instance().log_debug("CameraScene.init"); self._config_filename = scene_manager.SceneManager.instance().get_camera_scene_filename(); #Validate the configuration. config_dict = config_validation.validate("CameraScene", self._config_filename, CameraScene._REQUIRED_KEYS); self._config_contents = DictHelper(config_dict); #Init the UI. self._init_static_sprites(); self._init_camera_sprite(); self._init_frame_sprite(); self._init_buttons(); self._init_countdown_sprite(); def _init_static_sprites(self): sprite_list = self._config_contents.value_or_die(CameraScene._KEY_STATIC_SPRITES); for info in sprite_list: #Create the sprite. sprite = Sprite(); #Set the sprite properties. sprite.load_image (info["image" ]); sprite.set_position(info["position"]); self._background_sprite = sprite; #Add to scene. self.add(sprite, layer = CameraScene._LAYER_INDEX_STATIC_SPRITE); def _init_camera_sprite(self): #Initialize the sprite. self._camera_sprite = Sprite(); #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_CAMERA_PLACEHOLDER_SPRITE); #Set the sprite properties. self._camera_sprite.load_image (info["image" ]); self._camera_sprite.set_position(info["position"]); #Add to scene. self.add(self._camera_sprite, layer = CameraScene._LAYER_INDEX_CAMERA_SPRITE); self._camera_sprite_size = self._camera_sprite.get_size(); def _init_frame_sprite(self): #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_CAMERA_FRAME_SPRITE); #Don't need the frame... if(info == False): return; #Init the sprite. self._frame_sprite = Sprite(); #Set the sprite properties. self._frame_sprite.load_image(info["image"]); self._frame_sprite.set_position(info["position"]); #Frame isn't same size of camera image, so scale it. if(self._frame_sprite.get_size() != self._camera_sprite_size): frame_image = self._frame_sprite.image; scaled_image = pygame.transform.scale(frame_image, self._camera_sprite_size); self._frame_sprite.update_image(scaled_image); #Add to scene. self.add(self._frame_sprite, layer = CameraScene._LAYER_INDEX_FRAME_SPRITE); def _init_buttons(self): #Initialize the button. self._take_photo_button = Button(); #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_TAKEPHOTO_BUTTON); #Set the button properties. self._take_photo_button.load_images(info["normal_image"], info["pressed_image"]); self._take_photo_button.set_position(info["position"]); self._take_photo_button.set_click_callback(self._on_take_photo_button_pressed); #Add to scene. self.add(self._take_photo_button, layer = CameraScene._LAYER_INDEX_PHOTO_BUTTON); def _init_countdown_sprite(self): #Initialize the Sprite. self._countdown_sprite = Sprite(); #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_COUNTDOWN_SPRITES); #Set the sprite properties. self._countdown_sprite.set_position(info["position"]); self._countdown_sprite.load_image(info["sprites"][0]); #Countdown is hidden by default. ############################################################################ ## Update / Draw / Handle Events Methods ## ############################################################################ def update(self, dt): self._countdown_clock.update(dt); img = Camera.instance().get_frame(scale_to = self._camera_sprite_size); self._camera_sprite.update_image(img); def handle_events(self, event): self._take_photo_button.handle_events(event); ############################################################################ ## Button Callbacks ## ############################################################################ def _on_take_photo_button_pressed(self): #Set the UI Elements visibility. self.remove(self._take_photo_button); self.add(self._countdown_sprite, layer = CameraScene._LAYER_INDEX_COUNTDOWN_SPRITE); #Start the countdown... self._countdown_clock.start(); ############################################################################ ## Timer Callbacks ## ############################################################################ def _on_countdown_timer_tick(self): #Get the info. info = self._config_contents.value_or_die(CameraScene._KEY_COUNTDOWN_SPRITES); sprites_list = info["sprites"]; index = self._countdown_clock.get_ticks_count(); #Check if have more countdown images to show... if(index < len(sprites_list)): self._countdown_sprite.load_image(sprites_list[index]); else: #Reset the image to the first frame and inform that #the countdown is done. self._countdown_sprite.load_image(sprites_list[0]); self._countdown_timer_finished(); ############################################################################ ## Other Methods ## ############################################################################ def _countdown_timer_finished(self): #Set the UI Elements visibility. self.remove(self._countdown_sprite); self.add(self._take_photo_button, layer = CameraScene._LAYER_INDEX_PHOTO_BUTTON); #Stop the countdown... self._countdown_clock.stop(); #Call the Camera to grab a photo. Camera.instance().take_photo(); #Go to another scene. scene_mgr = scene_manager.SceneManager; scene_mgr.instance().scene_is_complete(scene_mgr.SCENE_NAME_POSTPHOTO);
class Game(object): print "Setting global Game params." # Game parameters BG_TILE_IMG = 'images/wood2.png' BUTTON_BGIMG = 'images/x.png' SCREEN_WIDTH, SCREEN_HEIGHT = 580, 500 GRID_SIZE = 20 FIELD_SIZE = 400, 400 #need to implement resource loading here #global game constants make cheating easy! def __init__(self): pygame.init() print "Pygame started." #set up screen and background self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT), 0, 32) self.tile_img = pygame.image.load(self.BG_TILE_IMG).convert_alpha() self.tile_img_rect = self.tile_img.get_rect() #Drawing a handy MessageBoard widget #Can use these for any text. print "Configuring tboard MessageBoard params." self.tboard_text = ['This is a test.'] self.tboard_x = 120 self.tboard_y = 120 self.tboard_width = 125 self.tboard_height = 30 self.tboard_rect = Rect(self.tboard_x, self.tboard_y, self.tboard_width, self.tboard_height) self.tboard_bgcolor = Color(50, 20, 0) self.tboard = MessageBoard(self.screen, rect=self.tboard_rect, bgcolor=self.tboard_bgcolor, border_width=4, border_color=Color('black'), text=self.tboard_text, padding=5, font=('comic sans', 18), font_color=Color('yellow')) print "Moving on to buttons..." self.button_bgimgs = ['images/x.png'] #self.button_width = self.button_bgimgs[0].get_width() #self.button_height = self.button_bgimgs[0].get_height() #hopefully this will draw the button -15 pixels from the right end, +15 from the top #(hopefully giving us a nice X) # should be replaced in the future with a method that returns the coords for an x button # in whatever corner we want. #self.button_rect = Rect(self.tboard_width, self.tboard_y-15, self.button_width, self.button_height) self.button = Button(self.screen, pos=vec2d(self.tboard_width, self.tboard_y-15), btntype='Close', imgnames=self.button_bgimgs, attached=self.tboard) print "Created close button." #setting up our toggle button self.togglebtn_bgimgs = ['images/toggle1.png', 'images/toggle2.png'] self.togglebtn = Button(self.screen, pos=vec2d(250, 250), btntype='Toggle', imgnames=self.togglebtn_bgimgs, attached="") print "Created toggle button." self.buttons = [self.button, self.togglebtn] self.clock = pygame.time.Clock() self.paused = False #spawning entities #Setting up gamefield #need a method for dynamically figuring out how many rows/columns we need based on #the spacing we want and field size. Using some constants for now. self.grid_nrows = 30 self.grid_ncols = 30 self.field_rect = Rect(0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT) self.options = dict(debug=True, draw_grid=False) print "Done setting game options, exiting Game init." def xy2coord(self, pos): """ Convert a (x, y) pair to a (nrow, ncol) coordinate """ x, y = (pos[0] - self.field_rect.left, pos[1] - self.field_rect.top) return (int(y) / self.GRID_SIZE, int(x) / self.GRID_SIZE) def coord2xy_mid(self, coord): """ Convert a (nrow, ncol) coordinate to a (x, y) pair, where x,y is the middle of the square at the coord """ nrow, ncol = coord return ( self.field_rect.left + ncol * self.GRID_SIZE + self.GRID_SIZE / 2, self.field_rect.top + nrow * self.GRID_SIZE + self.GRID_SIZE / 2) def get_field_rect(self): """ Return the internal field rect - the rect of the game field exluding its border. """ return self.field_box.get_internal_rect() def draw_background(self): img_rect = self.tile_img.get_rect() nrows = int(self.screen.get_height() / img_rect.height) + 1 ncols = int(self.screen.get_width() / img_rect.width) + 1 for y in range(nrows): for x in range(ncols): img_rect.topleft = (x * img_rect.width, y * img_rect.height) self.screen.blit(self.tile_img, img_rect) def draw_grid(self): for y in range(self.grid_nrows + 1): pygame.draw.line( self.screen, Color(50, 50, 50), (self.field_rect.left, self.field_rect.top + y * self.GRID_SIZE - 1), (self.field_rect.right - 1, self.field_rect.top + y * self.GRID_SIZE - 1)) for x in range(self.grid_ncols + 1): pygame.draw.line( self.screen, Color(50, 50, 50), (self.field_rect.left + x * self.GRID_SIZE - 1, self.field_rect.top), (self.field_rect.left + x * self.GRID_SIZE - 1, self.field_rect.bottom - 1)) def draw(self): #draw background image self.draw_background() #draw game field crap here #decide if we should draw grid. if self.options['draw_grid']: self.draw_grid() #Only stuff being drawn right now. #Message board with x button self.tboard.draw() if self.button.is_visible(): self.button.draw() if self.togglebtn.is_visible(): self.togglebtn.draw() #this way we can draw dynamic MessageBoards. #self.mboard.text = self.mboard_text <-- copy in latest text #self.mboard.draw() #other entity draw calls def run(self): print "Beginning run sequence." # The main game loop # while True: # Limit frame speed to 30 FPS # time_passed = self.clock.tick(30) #~ time_passed = self.clock.tick() #~ print time_passed # If too long has passed between two frames, don't # update (the game must have been suspended for some # reason, and we don't want it to "jump forward" # suddenly) # if time_passed > 100: continue #Event loop. In-game control is routed through here #Will probably need something more robust soon. for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.paused = not self.paused elif event.key == pygame.K_g: #toggle draw grid self.options['draw_grid'] = not self.options['draw_grid'] elif (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1): for button in self.buttons: button.mouse_click_event(event.pos) pass #entity events here. #update hud, counters, score, anything like that here if not self.paused: msg1 = '' msg2 = '' #update stats counters. Not doing anything yet self.mboard_text = [msg1, msg2] #update entities with time passed for internal calculations self.draw() #actually flip Surface buffer pygame.display.flip() def quit(self): sys.exit()
def __init__(self): pygame.init() print "Pygame started." #set up screen and background self.screen = pygame.display.set_mode( (self.SCREEN_WIDTH, self.SCREEN_HEIGHT), 0, 32) self.tile_img = pygame.image.load(self.BG_TILE_IMG).convert_alpha() self.tile_img_rect = self.tile_img.get_rect() #Drawing a handy MessageBoard widget #Can use these for any text. print "Configuring tboard MessageBoard params." self.tboard_text = ['This is a test.'] self.tboard_x = 120 self.tboard_y = 120 self.tboard_width = 125 self.tboard_height = 30 self.tboard_rect = Rect(self.tboard_x, self.tboard_y, self.tboard_width, self.tboard_height) self.tboard_bgcolor = Color(50, 20, 0) self.tboard = MessageBoard(self.screen, rect=self.tboard_rect, bgcolor=self.tboard_bgcolor, border_width=4, border_color=Color('black'), text=self.tboard_text, padding=5, font=('comic sans', 18), font_color=Color('yellow')) print "Moving on to buttons..." self.button_bgimgs = ['images/x.png'] #self.button_width = self.button_bgimgs[0].get_width() #self.button_height = self.button_bgimgs[0].get_height() #hopefully this will draw the button -15 pixels from the right end, +15 from the top #(hopefully giving us a nice X) # should be replaced in the future with a method that returns the coords for an x button # in whatever corner we want. #self.button_rect = Rect(self.tboard_width, self.tboard_y-15, self.button_width, self.button_height) self.button = Button(self.screen, pos=vec2d(self.tboard_width, self.tboard_y-15), btntype='Close', imgnames=self.button_bgimgs, attached=self.tboard) print "Created close button." #setting up our toggle button self.togglebtn_bgimgs = ['images/toggle1.png', 'images/toggle2.png'] self.togglebtn = Button(self.screen, pos=vec2d(250, 250), btntype='Toggle', imgnames=self.togglebtn_bgimgs, attached="") print "Created toggle button." self.buttons = [self.button, self.togglebtn] self.clock = pygame.time.Clock() self.paused = False #spawning entities #Setting up gamefield #need a method for dynamically figuring out how many rows/columns we need based on #the spacing we want and field size. Using some constants for now. self.grid_nrows = 30 self.grid_ncols = 30 self.field_rect = Rect(0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT) self.options = dict(debug=True, draw_grid=False) print "Done setting game options, exiting Game init."
def __init__(self, owner, screen, player, inqueue, outqueue): # Knowledge about the outside world self.owner = owner self.screen = screen self.player = player self.inqueue = inqueue self.outqueue = outqueue # UI configuration self.size = self.width, self.height = self.screen.get_size() self.black = 0, 0, 0 self.yellow = 250, 215, 0 # Game status tracking self.start = False self.cards = [] self.selected = [] self.timestart = 0 # Special flags to allow for the powers to function self.matchallowed = True self.doneselecting = False self.skipturn = False # Set up the bonus timer self.maxbonus = 10000 self.bonusdurations = {1: 5000, 2: 5000} self.bonus = BonusTimer(5000,Rect(600,750,330,25)) # Set up the powers self.powers = [] self.powersallowed = True for i in xrange(12): self.powers.append(Power(self,i)) # Allow us to go back to the menu after a game self.menubutton = Button('Return to Menu',Rect(335,430,300,25),self.gotoMenu,fgcolor=self.yellow) # Network initialization self.inqueue.get().addCallback(self.gotMessage) # Let player 1 be authoritative on the ordering of the cards if self.player == 1: self.arrangeCards() #Basic Initializations self.firstCard = 0 #Stores number of cards that have been selected self.message = "P1 turn" #Whose turn is it? self.p1 = 0 #Score self.p2 = 0 #Score self.p1interp = TimedInterpolator() self.p2interp = TimedInterpolator() self.turn = 1 # Player whose turn it is self.turncount = 0 self.GameOver = False #Create labels self.myfont = pygame.font.SysFont("monospace",30) self.label = self.myfont.render("Memory",1,self.yellow) self.turnlabel = self.myfont.render(str(self.message),1,self.yellow) self.player1 = self.myfont.render("Player 1: "+str(self.p1),1,self.yellow) self.player2 = self.myfont.render("Player 2: "+str(self.p2),1,self.yellow) self.gameover = self.myfont.render("WAITING FOR PLAYER 2",3,self.yellow) self.winsurf = self.myfont.render('You Win!',True,self.yellow) self.tiesurf = self.myfont.render('It\'s a Tie!',True,self.yellow) self.losesurf = self.myfont.render('You Lose!',True,self.yellow)
class GameState: def __init__(self, owner, screen, player, inqueue, outqueue): # Knowledge about the outside world self.owner = owner self.screen = screen self.player = player self.inqueue = inqueue self.outqueue = outqueue # UI configuration self.size = self.width, self.height = self.screen.get_size() self.black = 0, 0, 0 self.yellow = 250, 215, 0 # Game status tracking self.start = False self.cards = [] self.selected = [] self.timestart = 0 # Special flags to allow for the powers to function self.matchallowed = True self.doneselecting = False self.skipturn = False # Set up the bonus timer self.maxbonus = 10000 self.bonusdurations = {1: 5000, 2: 5000} self.bonus = BonusTimer(5000,Rect(600,750,330,25)) # Set up the powers self.powers = [] self.powersallowed = True for i in xrange(12): self.powers.append(Power(self,i)) # Allow us to go back to the menu after a game self.menubutton = Button('Return to Menu',Rect(335,430,300,25),self.gotoMenu,fgcolor=self.yellow) # Network initialization self.inqueue.get().addCallback(self.gotMessage) # Let player 1 be authoritative on the ordering of the cards if self.player == 1: self.arrangeCards() #Basic Initializations self.firstCard = 0 #Stores number of cards that have been selected self.message = "P1 turn" #Whose turn is it? self.p1 = 0 #Score self.p2 = 0 #Score self.p1interp = TimedInterpolator() self.p2interp = TimedInterpolator() self.turn = 1 # Player whose turn it is self.turncount = 0 self.GameOver = False #Create labels self.myfont = pygame.font.SysFont("monospace",30) self.label = self.myfont.render("Memory",1,self.yellow) self.turnlabel = self.myfont.render(str(self.message),1,self.yellow) self.player1 = self.myfont.render("Player 1: "+str(self.p1),1,self.yellow) self.player2 = self.myfont.render("Player 2: "+str(self.p2),1,self.yellow) self.gameover = self.myfont.render("WAITING FOR PLAYER 2",3,self.yellow) self.winsurf = self.myfont.render('You Win!',True,self.yellow) self.tiesurf = self.myfont.render('It\'s a Tie!',True,self.yellow) self.losesurf = self.myfont.render('You Lose!',True,self.yellow) # Code for handling a message (probably from the other player, across # the network, but we don't really care either way). def gotMessage(self, msg): # All commands are text-based, with arguments and such seperated by single spaces cmd = msg.split(' ') try: if cmd[0] == 'connection_made': # Signal to start the game proper self.start = True if self.turn == self.player: self.bonus.reset() self.bonus.start() self.outqueue.put('turn ' + str(self.bonus.starttime)) elif cmd[0] == 'card_order': # Player 2 learning the answers if self.player == 1: print 'card ordering received from a player other than player 1' elif self.cards: print 'already have a card ordering' else: self.initializeCards(int(x) for x in cmd[1:25]) elif cmd[0] == 'turn': # Synchronize the bonus timers if self.turn == self.player: print 'turn message received on own turn' else: starttime = int(cmd[1]) self.bonus.reset(starttime=starttime) elif cmd[0] == 'select_card': # Let the other player know which card you picked if self.turn == self.player: print 'received card selection message on own turn' else: ticks = int(cmd[1]) self.bonus.update(time=ticks) i = int(cmd[2]) self.selectCard(i,notify=False) # All of the below are commands associated with powers; c.f. powers.py elif cmd[0] == 'fast_bonus': self.powers[Card.HORSE].activate(evil=True) elif cmd[0] == 'scramble_cards': self.powers[Card.MONKEY].activate(evil=True) elif cmd[0] == 'skip_turn': self.powers[Card.GORILLA].activate(evil=True) elif cmd[0] == 'extra_points': self.addPoints(1000) self.powers[Card.SQUIRREL].activate(evil=True) elif cmd[0] == 'disable_powers': self.powers[Card.BULL].activate(evil=True) elif cmd[0] == 'show_cards': self.powers[Card.BIRD].activate(evil=True) elif cmd[0] == 'erq_ureevat': self.powers[Card.FISH].activate(evil=True) elif cmd[0] == 'replenish_cards': # Reset (most) cards for card in self.cards: if card.value != Card.SPIDER: card.__init__(self,card.rect.x,card.rect.y,card.value) self.scrambleCards() # Also reset (most) powers for power in self.powers: if power.value != Card.SPIDER: power.setAvailable(False) elif cmd[0] == 'sniff': if not self.doneselecting and len(self.selected) == 1: for i, card in enumerate(self.cards): if card.value == self.selected[0].value and card is not self.selected[0]: self.selectCard(i) if self.turn != self.player: self.powers[Card.PIG].activate(evil=True) elif cmd[0] == 'replenish_card': value = int(cmd[1]) for card in filter(lambda c: c.value in (Card.ROOSTER, value),self.cards): card.__init__(self,card.rect.x,card.rect.y,card.value) self.scrambleCards() self.powers[Card.ROOSTER].activate(evil=True) elif cmd[0] == 'steal_points': if self.turn == 1: points = 0.1*self.p2 self.addPoints( points,player=1) self.addPoints(-points,player=2) else: points = 0.1*self.p1 self.addPoints(-points,player=1) self.addPoints( points,player=2) elif cmd[0] == 'slow_bonus': self.powers[Card.TURTLE].activate(evil=True) else: print 'unknown command: ' + cmd[0] except (IndexError, ValueError): print 'bad command received: ' + msg # Ask for the next one form our DeferredQueue self.inqueue.get().addCallback(self.gotMessage) # Calculate the n-th layout position for a card def cardPosition(self, n): topleft = 10, 100 hspacing = 160 vspacing = 160 ncols = 6 x = topleft[0] + n%ncols*hspacing y = topleft[1] + n/ncols*vspacing return x, y # Determine the official order of the cards for this game def arrangeCards(self): # Two of each of the twelve cards self.initializeCards(random.sample(list(n/2 for n in xrange(24)),24)) # Tell the other player self.outqueue.put('card_order ' + ' '.join(str(c.value) for c in self.cards)) # Don't change the in-memory order of the cards, only the on-screen arrangement def scrambleCards(self): order = iter(random.sample(range(24),24)) for card in self.cards: pos = self.cardPosition(next(order)) card.move(pos[0],pos[1]) # Actually construct and place the cards def initializeCards(self, ids): self.cards = [] # Card arrangement n = 0 for i in ids: pos = self.cardPosition(n) self.cards.append(Card(self,pos[0],pos[1],i)) n += 1 # As long as 2 cards have not already been selected, # and the card clicked is not already matched # or already selected, then flip it. def selectCard(self, i, notify=True): card = self.cards[i] if not self.doneselecting and not card.matched and not card.selected: card.select() self.selected.append(card) self.timestart = pygame.time.get_ticks() self.doneselecting |= len(self.selected) >= 2 if self.doneselecting: self.bonus.stop() # Tell the other player if notify: self.outqueue.put('select_card ' + str(self.bonus.curtime) + ' ' + str(i)) # Change the score of a player (the current player, by default) def addPoints(self, points, player=None): points = int(points) if player == 1 or self.turn == 1: self.p1interp.start(self.p1,self.p1 + points,2000) self.p1 += points else: self.p2interp.start(self.p2,self.p2 + points,2000) self.p2 += points # Adieu def gotoMenu(self): self.owner.stop(main_screen.MainScreen(self.screen)) # The main game logic, called sixty times a second (assuming Twisted is reliable) def gameLoop(self): if self.start: #If a player 2 is connected, then display main screen self.loop() else: #Otherwise display waiting screen self.waiting() def waiting(self): #Handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: reactor.stop() self.screen.fill(self.black) #Display labels self.screen.blit(self.label,(430,30)) self.screen.blit(self.player1,(20,30)) self.screen.blit(self.player2,(750,30)) self.screen.blit(self.gameover,(300,400)) pygame.display.flip() def loop(self): # handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: reactor.stop() elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: # Check for clicks on game objects if self.turn == self.player: for i, card in enumerate(self.cards): if card.rect.collidepoint(pygame.mouse.get_pos()): self.selectCard(i) if not self.doneselecting and self.powersallowed: for power in self.powers: if power.rect.collidepoint(pygame.mouse.get_pos()): power.activate() if self.GameOver: self.menubutton.click(event.button,event.pos) #After 3 seconds, update score, switch turn and flip cards back over if self.doneselecting and pygame.time.get_ticks() - self.timestart > 3000: #The 2 cards are a match if self.matchallowed and self.selected[0].value == self.selected[1].value: for card in self.selected: card.matched = True card.selected = False # Activate the power if self.turn == self.player: self.powers[self.selected[0].value].setAvailable(True) # Update score self.addPoints(100 + int((1 - self.bonus.progress)*self.maxbonus)) else: #The 2 cards are not a match #Flip the cards back over for card in self.selected: card.startFlip() card.selected = False # Reset the selection for the next turn self.selected = [] self.matchallowed = True self.doneselecting = False #Change turns for _ in xrange(2 if self.skipturn else 1): self.bonusdurations[self.turn] = self.bonus.duration self.turn = 2 if self.turn == 1 else 1 self.turncount += 1 self.bonus.setDuration(self.bonusdurations[self.turn]) # Reset the bonus timer self.bonus.stop() self.bonus.reset() if self.turn == self.player: self.bonus.start() # Synchronize with the other player if self.turn == self.player: self.outqueue.put('turn ' + str(self.bonus.starttime)) # Update the on-screen message if self.turn == 1: self.message = "P1 turn" else: self.message = "P2 turn" # send a tick to every game object! for card in self.cards: card.tick() for power in self.powers: power.tick() self.bonus.tick() # Update the on-screen labels self.turnlabel = self.myfont.render(str(self.message),1,self.yellow) self.player1 = self.myfont.render("Player 1: "+str(self.p1interp.current()),1,self.yellow) self.player2 = self.myfont.render("Player 2: "+str(self.p2interp.current()),1,self.yellow) #Make screen black self.screen.fill(self.black) #display cards for card in self.cards: card.draw(self.screen) # Draw the power icons for power in self.powers: power.draw(self.screen) # Draw the bonus timer self.bonus.draw(self.screen) #display labels self.screen.blit(self.label,(430,30)) self.screen.blit(self.player1,(20,30)) self.screen.blit(self.player2,(950 - self.player2.get_width(),30)) self.screen.blit(self.turnlabel,(430,750)) # Check for the endgame condition -- all cards matched self.GameOver = bool(self.cards) for card in self.cards: if card.matched is False: self.GameOver = False # If game over, display a message if self.GameOver: if self.p1 == self.p2: self.screen.blit(self.tiesurf,(400, 400)) elif (self.p1 > self.p2) == (self.player == 1): self.screen.blit(self.winsurf,(400, 400)) else: self.screen.blit(self.losesurf,(400, 400)) self.menubutton.draw(self.screen) pygame.display.flip()