def _create_sprites(self, path): ''' Create all of the sprites we'll need ''' self.smiley_graphic = svg_str_to_pixbuf( svg_from_file(os.path.join(path, 'smiley.svg'))) self.frown_graphic = svg_str_to_pixbuf( svg_from_file(os.path.join(path, 'frown.svg'))) self.egg_graphic = svg_str_to_pixbuf( svg_from_file(os.path.join(path, 'Easter_egg.svg'))) self.blank_graphic = svg_str_to_pixbuf( svg_header(REWARD_HEIGHT, REWARD_HEIGHT, 1.0) + \ svg_rect(REWARD_HEIGHT, REWARD_HEIGHT, 5, 5, 0, 0, '#C0C0C0', '#282828') + \ svg_footer()) self.ball = Ball(self.sprites, os.path.join(path, 'basketball.svg')) self.current_frame = 0 self.bar = Bar(self.sprites, self.width, self.height, self.scale, self.ball.width()) self.current_bar = self.bar.get_bar(2) self.ball_y_max = self.bar.bar_y() - self.ball.height() self.ball.move_ball((int( (self.width - self.ball.width()) / 2), self.ball_y_max))
def get_bar(bar_id, day): day = int(day) auth_header = request.headers.get('Authorization') auth_token, valid = get_authorization(auth_header) if valid: try: bar = db_ops.check_bar_db(bar_id) if bar: specials = create_specials(bar['specials'][day]) bar = Bar(bar['bar_id'], bar['name'], bar['location'], bar['phone'], bar['cover']) bar.specials[day] = specials print(bar) responseObject = { 'status': 'success', 'message': 'Found bar.', 'bar': bar.to_dict(day) } return make_response(jsonify(responseObject)), 200 else: create_response('fail', 'Did not find bar', 401) except Exception as e: traceback.print_exc(file=sys.stdout) return create_response('fail', 'Threw an Exception', 401) else: return create_response('fail', 'Invalid Token', 401)
def testAgregar(self): print 'Test de agregar bar.\n' bar0 = Bar('Barcito', 'Av. Callao 493', 4, 'El bar mas bonito.', 1) bar1 = Bar('Tragos', 'Araoz 1274', 2, 'Ambientes tranquilo para estudiar.', 0) bar2 = Bar('Hola Mundo', 'Avellaneda 621', 1, 'Todos son bienvenidos.', 1) bar3 = Bar('Las Tortas', 'Av. Corrientes 948', 4, 'Nuestra comida es la mejor de la ciudad.', 1) self.listaBares.agregarBar(bar0) self.listaBares.agregarBar(bar1) self.listaBares.agregarBar(bar2) self.listaBares.agregarBar(bar3) print 'bar 1:', bar0, '\nbar 2:', bar1, '\nbar 3:', bar2, '\nbar 4:', bar3, '\n' bares = self.listaBares.inhabilitados() i = 0 for bar in bares: if i == 0 and bar == bar0: print 'Bar 1 se agrega correctamente.' elif i == 1 and bar == bar1: print 'Bar 2 se agrega correctamente.' elif i == 2 and bar == bar2: print 'Bar 3 se agrega correctamente.' elif i == 3 and bar == bar3: print 'Bar 4 se agrega correctamente.' else: print 'Alguno de los bares no fue agregado correctamente.' i += 1
def index(): turmas = Turma.query.all() turmas = turmas_schema.dump(turmas) instituicoes = Instituicao.query.all() instituicoes = instituicoes_schema.dump(instituicoes) alunos = Aluno.query.all() totais = [] tick_label = [] for instituicao in instituicoes: for inst in instituicao: if len(inst['name']) > 0: id = inst['id'] tick_label.append(inst['name']) points = db.engine.execute( f'SELECT points FROM aluno WHERE instituicao_id = {id}') points = [{ column: value for column, value in rowproxy.items() } for rowproxy in points] total = 0 for point in points: total += point['points'] total = total / len(points) totais.append(total) color = ['red', 'green'] width = 0.8 graph = Bar(tick_label, totais, width, color, 'nome', 'média', '', 'bar') return render_template('pages/index.html', turmas=turmas.data, instituicoes=instituicoes.data, grafico=graph.plotGraph())
def test_null(self): with TestDatabase.db.transaction() as t: TestDatabase.db.upsert(Bar(999, 90, 120.0, 'C')) bars = TestDatabase.db.select(Bar(999)) self.assertEqual(len(bars), 1) self.assertEqual( str(bars[0]), "bar : Keys {'id': 999} : Values {'heading': 90, 'speed': 120.0, 'signal': 'C'}") # force a rollback t.fail()
def test_transaction(self): # test commit with TestDatabase.db.transaction(): TestDatabase.db.upsert(Bar(101, 180, 33.5, 'A')) TestDatabase.db.upsert(Bar(102, 270, 50.33, 'B')) bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 4) # test rollback on exception with TestDatabase.db.transaction(), \ self.assertRaises(DatabaseIntegrityError) as cm: TestDatabase.db.upsert(Foo('a new foo', )) self.assertEqual(cm.exception.args[0], 'NOT NULL constraint failed: foo.desc') self.assertEqual(len(bars), 4) # test a forced rollback with TestDatabase.db.transaction() as t: TestDatabase.db.upsert( Bar(104, 355, 99.99, 'D')) t.fail() bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 4) # restore table to pre-test state with TestDatabase.db.transaction(): TestDatabase.db.delete(Bar(101)) TestDatabase.db.delete(Bar(102)) bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 2)
def init(self): self.width, self.height = self.screen.get_size() bar_width = 0.03 * self.width bar_height = 0.3 * self.height self.bars = [ Bar(0.1 * self.width, (self.height - bar_height) / 2, bar_width, bar_height, self.height, (255, 0, 0)), Bar(0.9 * self.width - bar_width, (self.height - bar_height) / 2, bar_width, bar_height, self.height, (0, 0, 255)) ] self.balls = [] self.score = [0, 0] self.last_spawn_y = 0.1 for i in range(4 + 2 * self.difficulty): self.create_ball()
def test_delete(self): with TestDatabase.db.transaction(): TestDatabase.db.upsert(Bar(123, 456, 78.9, 'D')) bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 3) self.assertEqual( str(bars[2]), "bar : Keys {'id': 123} : Values {'heading': 456, 'speed': 78.9, 'signal': 'D'}") with TestDatabase.db.transaction(): TestDatabase.db.delete(Bar(123)) bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 2) bars = TestDatabase.db.select(Bar(123)) self.assertEqual(len(bars), 0)
def collision_crap(self): if self.bar.rect.x < 0: # Class bounds it self.manlinesses -= 1 self.sounds['haha'].play() if self.manlinesses == 0: self.gameover() else: self.all_sprites.pop('man2') self.bar = Bar(self.sounds) # Moving bar self.all_sprites['moving_bar'] = [self.bar.image, self.bar.rect] self.bar.v_change = -20 self.all_sprites['player'][0] = pygame.image.load(\ path.join('data','deadplayer.png')).convert_alpha() # Whip on player? if self.master1.state == 3: # Final chain self.bar.v_change = 200 self.sounds['whip'].play() self.bar.play_sound() self.time_since_whip = self.time_passed if self.master2.state == 3: self.bar.v_change = 200 self.sounds['whip'].play() self.bar.play_sound() if self.master1.state == 3 and self.master2.state == 3: self.bar.v_change = 400 if (self.master1.state == 0 or self.master2.state == 0) and \ self.time_passed - self.time_since_whip >= 0.5: self.bar.v_change = 0 if self.master1.state == 2 or self.master2.state == 2: self.blood.render_blood() self.all_sprites['blood'][0] = self.blood.image
def __init__(self): """Initialize the game, and create game resources.""" pygame.init() # Clock set-up for framerate self.clock = pygame.time.Clock() self.settings = Settings() self.stats = GameStats(self) self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Bouncing Ball") self.bar = Bar(self) self.ball = Ball(self) self.timebar = TimeBar(self) self.play_button = Button(self, 'Play')
def create_bar(): auth_header = request.headers.get('Authorization') auth_token, valid = get_authorization(auth_header) if valid: try: resp, success = User.decode_auth_token(auth_token) user = db_ops.check_user_db(resp) if success: if user['status'] == 'admin': content = request.get_json() bar = Bar(content['username'], content['password'], content['name'], content['location'], content['phone']) responseObject = { 'status': 'success', 'message': 'Successfully added bar.' } db_ops.add_bar_to_db(bar) return make_response(jsonify(responseObject)), 200 else: return create_response('fail', 'Incorrect Priveleges', 401) else: return create_response('fail', resp, 401) except Exception as e: return create_response('fail', 'Threw an Exception', 401) else: return create_response('fail', 'Invalid Token', 401)
def from_mktdata_to_bar(mktData, freq): if (mktData.isnull().sum() == 0) or (mktData.isnull().sum() == 1 and np.isnan(mktData.adjClose)): return Bar(mktData.dateTime, mktData.open, mktData.high, mktData.low, mktData.close, mktData.volume, mktData.adjClose, freq) else: return None
def parse(file_path): tree = ElementTree.parse(file_path) score = tree.getroot() lines = [] for line in score.findall('line'): bars = [] for bar in line.findall('bar'): units = [] time_signature = bar.get('time_signature') for unit in bar.findall('unit'): notes = [] for note in unit.findall('note'): pitch = note.get('pitch') hold_str = note.get('hold') hold = {'True': True, 'False': False}[hold_str] print(pitch) notes.append(Note(pitch, hold)) beats = unit.get('beats') units.append(Unit(notes, Fraction(beats))) key = bar.get('key') bars.append(Bar(key, time_signature, units)) lines.append(bars) title = score.get('title') author = score.get('author') return Score(lines, title, author)
def get_last_bars(self, ticker, length, time_segment): if length == 250: return [Bar({"t": 0,"o": 400.0,"h": 550.0,"l": 340.0,"c": 500.0,"v": 100})] bars_copy = copy.copy(self.bars[ticker]) del self.bars[ticker][0] return bars_copy[0]
def run(): pygame.init() # load the game settings settings = Settings() # create the screen and add a title screen = pygame.display.set_mode(settings.screen_dimension) pygame.display.set_caption('BreakOut - Python') # create the game elements bar = Bar(screen, settings) chances = Chances(screen, settings) score = Score(screen, settings) ball = Ball(screen, bar, settings, chances, score) btn_start = Button(screen, 'press space to start') btn_game_over = Button(screen, 'Game Over') object_group = [] function.dispose_objects(screen, object_group, score) while True: function.check_events(bar, settings, chances, score) function.update_screen(bar, screen, ball, settings, object_group, btn_start, btn_game_over, chances, score)
def __init__(self, width, height): self.mWidth = width self.mHeight = height self.mBackground = Background(width, height) self.mBall = Ball(width, height) self.mBars = [] self.mBars.append(Bar(width, height)) self.mBars[0].evolve() self.mScore = 0 self.mGameStart = False self.mEZGame = False self.mEZText = Text("EZ MODE", self.mWidth / 2, 40) self.mGameStartTextTop = Text("Press 'W' to flap", self.mWidth / 2, self.mHeight / 3) self.mGameStartTextBot = Text("Press 'E' for EZ Mode", self.mWidth / 2, self.mHeight / 3 + 35) self.mScoreText = Text(str(self.mScore), self.mWidth / 10 - 20, self.mHeight / 10 - 20) self.mGameOverTextTop = Text("GAME OVER NERD", self.mWidth / 2, self.mHeight / 3) self.mGameOverTextBot = Text("Press 'A' to play again", self.mWidth / 2, self.mHeight / 3 + 35) self.mGameOver = False self.mFlapSound = Sound("sounds/flap.wav") self.mPipeSound = Sound("sounds/pipe_sound.wav") self.mHitSound = Sound("sounds/hit.wav") self.mThemeSong = Sound("sounds/theme_song.wav") self.mThemePlaying = False self.mThemeSong.setVolume(.5) self.mWings = 0 return
def main(): if path.exists("wp_plugins.txt"): w = open("wp_plugins.txt", 'r') #w=lista de todos los plugins del fichero w = w.read().split('\n') #lista=lista de los plugins encontrados lista = [] url = "https://www.nationalarchives.gov.uk" with Bar("Espere...", count=len(w)) as b: for plugin in w: b.step() try: p = requests.get(url=url + "/" + plugin) # si la url formada existe if p.status_code == 200: final = url + "/" + plugin lista.append(final.split("/")[-2]) except: pass b.exit() for plugin in lista: print("Plugin encontrado: {}".format(plugin)) else: print("No se encuentra la lista")
def restart_menu(self): self.progressBar = [] for i in range(15): self.progressBar.append(pygame.image.load(f'img/marking_{i}.png')) self.students = [] for i in range(3): self.students.append( random.choice( self.student_type).clone(wish=random.randint(10, 40))) self.active_students = [] self.curr_coctail = None self.spots = { (90, 525): self.alcs['Пиво'], (0, 525): self.alcs['Водка'] } self.spot_size = (80, 150) self.game_over = False self.free_places = frozenset({1: None, 2: None, 3: None}) self.places = {1: (100, 100), 2: (300, 100), 3: (500, 100)} self.bar = Bar(list(self.alcs.values())) self.player = Player(self.bar) self.menu()
def evolve(self): if self.mThemePlaying == False: self.mThemeSong.play() self.mThemePlaying = True for bar in self.mBars: if bar.getWidth() + bar.getShift() - self.mBall.getWidth() == 0: self.mPipeSound.play() self.mScore += 1 self.mScoreText = Text(str(self.mScore), self.mWidth / 10 - 20, self.mHeight / 10 - 20) if self.groundCollide() or self.barCollide(): self.mGameOver = True self.mHitSound.play() self.mThemeSong.stop() self.mBall.flip(180) if not self.mGameOver: self.mBall.evolve() for bar in self.mBars: bar.evolve() lastBar = self.mBars[len(self.mBars) - 1] if lastBar.getShift() <= -150: newBar = Bar(self.mWidth, self.mHeight) self.mBars.append(newBar) return
def submit_values(self): caption = "" value = 0 # get data from input boxes for button in self.menu: # input box id 0 is the caption box if button.id == 0: # so the data is a string caption = str(button.data) # input box id 1 is the value box elif button.id == 1: # so the data should be int try: value = int(button.data) except: print "Incorrect input!" # if either data field is empty or invalid if caption == "" or value < 1: for button in self.menu: if button.id == 2: # flash the "Add" button red button.throw_error() else: maxvalue = value if self.bars: # get greatest current value of a bar maxvalue = max(bar.value for bar in self.bars) # if new value is bigger than current maxvalue if value > maxvalue: # set it as new maxvalue maxvalue = value for bar in self.bars: # and scale all bars according to it bar.set_size(maxvalue) barwidth = self.buttonheight + self.padding * 3 bars = len(self.bars) * barwidth oldpadding = len(self.bars) * self.padding # other bar paddings and bars, padding left x = oldpadding + bars + self.padding # don't let the user add more bars if end of window is reached if x + self.buttonheight + self.padding * 3 > self.width: for button in self.menu: if button.id == 2: button.throw_error() else: y = self.height - self.bbarheight - self.buttonheight self.bars.add( Bar(caption, value, maxvalue, self.maxheight, x, y - self.padding * 2, barwidth))
def test_select_Ordered(self): bars = TestDatabase.db.select(Bar.createAdhoc(order=('>id',))) self.assertEqual(len(bars), 2) self.assertEqual( str(bars[0]), "bar : Keys {'id': 99} : Values {'heading': 99, 'speed': 2.4, 'signal': 'Z'}") self.assertEqual( str(bars[1]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}") with TestDatabase.db.transaction() as t: TestDatabase.db.upsert(Bar(101, 180, 33.5, 'A')) bars = TestDatabase.db.select(Bar.createAdhoc(order=('signal',))) self.assertEqual(len(bars), 3) self.assertEqual( str(bars[0]), "bar : Keys {'id': 101} : Values {'heading': 180, 'speed': 33.5, 'signal': 'A'}") self.assertEqual( str(bars[1]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}") self.assertEqual( str(bars[2]), "bar : Keys {'id': 99} : Values {'heading': 99, 'speed': 2.4, 'signal': 'Z'}") t.fail()
def spawnBar(self): h = random.randrange(100, 450, 25) color = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256)) bar = Bar(550, 0, 50, h, color) bar.accelerate(20) self.mBars.append(bar) color2 = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256)) randy = h + 100 botbar = Bar(550, randy, 50, 500-randy, color) botbar.accelerate(20) self.mbotBars.append(botbar) return
def getBars(self, day, period=PERIOD, intervals=INTERVALS): if self.average_height is None: return [] tomorrow = day + timedelta(days=1) # day = day.strftime("%Y-%m-%d") # tomorrow = tomorrow.strftime("%Y-%m-%d") data = self.getData(day, tomorrow, period, intervals, update=True) self._bars = [Bar(self.name, data.reset_index().iloc[[x]], self.average_height, self.average_volume) for x in range(len(data))]
def test_upsert(self): with TestDatabase.db.transaction() as t: TestDatabase.db.upsert(Bar(101, 180, 23.45, 'F')) bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 3) self.assertEqual( str(bars[2]), "bar : Keys {'id': 101} : Values {'heading': 180, 'speed': 23.45, 'signal': 'F'}") TestDatabase.db.upsert(Bar(98, 270, signal='B')) bars = TestDatabase.db.select(Bar(98)) self.assertEqual(len(bars), 1) self.assertEqual( str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 270, 'speed': None, 'signal': 'B'}") # force a rollback t.fail()
def test_select(self): bars = TestDatabase.db.select(Bar()) self.assertEqual(len(bars), 2) self.assertEqual( str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}") self.assertEqual(bars[1].getTable(), 'bar') self.assertEqual(bars[1].getId(), 99) self.assertEqual(bars[1].getHeading(), 99) self.assertEqual(bars[1].getSignal(), 'Z') bars = TestDatabase.db.select(Bar(98)) self.assertEqual(len(bars), 1) self.assertEqual( str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}") bars = TestDatabase.db.select(Bar.createAdhoc({'signal': 'Z'})) self.assertEqual(len(bars), 1) self.assertEqual( str(bars[0]), "bar : Keys {'id': 99} : Values {'heading': 99, 'speed': 2.4, 'signal': 'Z'}")
def menuAgregarBar(self): print "Ingrese nombre del bar " nombre = raw_input() print "Ingrese direccion (Todas las palabras separadas por espacios) " direcc = raw_input() print "Ingrese cantidad de enchufes " enchuf = input() print "Ingrese Descripcion" desc = raw_input() wifi = self.ingresarWifi() self.listaDeBares.agregarBar(Bar(nombre, direcc, enchuf, desc, wifi)) self.menuInicial()
def readData(self): with open(self.filename, 'rb') as f: header = f.read(148) while 1: first = f.read(4) if not first: break datetime = struct.unpack('I', first)[0] tmp = struct.unpack('ddddq', f.read(40)) bar = Bar(datetime, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4]) self.data.append(bar)
def _create_sprites(self, path): ''' Create all of the sprites we'll need ''' self.smiley_graphic = svg_str_to_pixbuf(svg_from_file( os.path.join(path, 'images', 'smiley.svg'))) self.frown_graphic = svg_str_to_pixbuf(svg_from_file( os.path.join(path, 'images', 'frown.svg'))) self.blank_graphic = svg_str_to_pixbuf( svg_header(REWARD_HEIGHT, REWARD_HEIGHT, 1.0) + svg_rect(REWARD_HEIGHT, REWARD_HEIGHT, 5, 5, 0, 0, 'none', 'none') + svg_footer()) self.ball = Ball(self._sprites, os.path.join(path, 'images', 'soccerball.svg')) self._current_frame = 0 self.bar = Bar(self._sprites, self.ball.width(), COLORS) self._current_bar = self.bar.get_bar(2) self.ball_y_max = self.bar.bar_y() - self.ball.height() + \ int(BAR_HEIGHT / 2.) self.ball.move_ball((int((self._width - self.ball.width()) / 2), self.ball_y_max)) self._backgrounds = {} width, height = self._calc_background_size() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( os.path.join(path, 'images', 'grass_background.png'), width, height) if Gdk.Screen.height() > Gdk.Screen.width(): pixbuf = self._crop_to_portrait(pixbuf) self._backgrounds['grass_background.png'] = pixbuf self._background = Sprite(self._sprites, 0, 0, pixbuf) self._background.set_layer(-100) self._background.type = 'background' self._current_bg = 'grass_background.png'
def __init__(self, starting_point, angle): """ Creates a set of bars :param starting_point: initial point where all begins :type starting_point: tuple of float :param angle: set of angles for each bar :type angle: numpy array """ self.bars = [] self.starting_point = starting_point for i in range(len(angle)): if i is 0: self.bars.append( Bar(self.starting_point, angle[i], length=BAR_LENGTH / len(angle))) else: self.bars.append( Bar(self.bars[i - 1].end_point, angle[i], length=BAR_LENGTH / len(angle)))
def test_center_and_var2(self): chords = [ Note.init_notes(['d1', 'e1']), Note.init_notes(['d1', 'f#1']), Note.init_notes(['d1', 'g#1']), Note.init_notes(['d1', 'a#1']) ] units = [Unit(chord, Fraction(1, 1)) for chord in chords] bar = Bar(key='C', time_signature='4/4', units=units) self.assertAlmostEqual(bar.center, 5.5, delta=self.ERROR) self.assertAlmostEqual(bar.var, 1.25, delta=self.ERROR)
def __on_bar(self, data): bar = Bar() bar.set_pd(data) bar.set_symbol(self.__symbol) # 撮合限价单 self.cross_limit_order(bar) # 推送给策略 self.__strategy.on_bar(bar)
def load_crap(self): # Loads all images, makes objects if applicable, adds any images and # rects to all_sprites{} # Now also loads all sounds at the very top! self.sounds = {'gasp' : self.load_sound('gasp.ogg'),\ 'ugh' : self.load_sound('ugh.ogg'),\ 'ow' : self.load_sound('ow.ogg'),\ 'ahh' : self.load_sound('ahh.ogg'),\ 'cry' : self.load_sound('cry.ogg'),\ 'whip' : self.load_sound('whip.ogg'),\ 'music' : self.load_sound('music1.ogg'),\ 'haha' : self.load_sound('haha.ogg')} self.sounds['music'].play(-1) self.all_sprites = {} self.bg_img = pygame.image.load(\ path.join('data','background.png')).convert_alpha() playerimg=pygame.image.load(path.join('data', 'player.png')).convert_alpha() player_pos = [370,384] # Does not move? self.all_sprites['player'] = [playerimg,player_pos] self.master1 = Master('left', self.screen) self.master2 = Master('right', self.screen) self.all_sprites['master1'] = [self.master1.image, self.master1.rect] self.all_sprites['master2'] = [self.master2.image, self.master2.rect] big_bar = pygame.image.load(path.join('data','big_bar.png')).convert_alpha() big_bar_pos = (400-250, 500) # 500 bottom? 10 top? Edit background for bot self.all_sprites['big_bar'] = [big_bar, big_bar_pos] self.bar = Bar(self.sounds) # Moving bar self.all_sprites['moving_bar'] = [self.bar.image, self.bar.rect] self.timer = Timer() #Clock so player knows how long they've gone self.all_sprites['timer'] = [self.timer.image, self.timer.rect] manliness = pygame.image.load(\ path.join('data','manliness.png')).convert_alpha() manliness1pos = (65, 1) manliness2pos = (100, 1) self.all_sprites['man1'] = [manliness, manliness1pos] self.all_sprites['man2'] = [manliness, manliness2pos] self.blood = Blood(self.screen, player_pos) self.all_sprites['blood'] = [self.blood.image, self.blood.rect]
def __init__(self): pygame.init() self.screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) self.clock = pygame.time.Clock() # Game states self.paused = 0 self.game_over = 0 self.running = 1 self.keep_drawing_ship = 1 # Game objects self.ship = ship.Ship( self.screen, (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)) self.asteroids = [] self.bullets = [] # Scoreboard self.score = 0 self.scoreboard = Scoreboard(self.screen) # Bullet Gauge self.bullet_gauge = BulletGauge(self.screen, 10, self.spawn_bullet) # Health bar self.health_bar = Bar(self.screen, self.ship.max_health, [30, SCREEN_HEIGHT - 20, 80, 10], RED, WHITE) # Game Over Text self.game_over_text = GameOverText(self.screen) self.reduce_game_over_text_alpha = Timer( 100, self.game_over_text.reduce_alpha) # Asteroid spawning self.since_last_asteroid = 0 self.new_asteroid_time = 1000 # Levels self.level_gen = generate_levels() self.level = 1 self.level_limit = next(self.level_gen) self.level_text = LevelText(self.screen)
class Game(object): def __init__(self): pygame.init() self.screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) self.clock = pygame.time.Clock() # Game states self.paused = 0 self.game_over = 0 self.running = 1 self.keep_drawing_ship = 1 # Game objects self.ship = ship.Ship( self.screen, (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)) self.asteroids = [] self.bullets = [] # Scoreboard self.score = 0 self.scoreboard = Scoreboard(self.screen) # Bullet Gauge self.bullet_gauge = BulletGauge(self.screen, 10, self.spawn_bullet) # Health bar self.health_bar = Bar(self.screen, self.ship.max_health, [30, SCREEN_HEIGHT - 20, 80, 10], RED, WHITE) # Game Over Text self.game_over_text = GameOverText(self.screen) self.reduce_game_over_text_alpha = Timer( 100, self.game_over_text.reduce_alpha) # Asteroid spawning self.since_last_asteroid = 0 self.new_asteroid_time = 1000 # Levels self.level_gen = generate_levels() self.level = 1 self.level_limit = next(self.level_gen) self.level_text = LevelText(self.screen) def run(self): while self.running: time_passed = self.clock.tick(60) # KEYBOARD INPUT for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = 0 break if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = 0 break if event.key == pygame.K_SPACE: if not self.paused and not self.game_over: self.bullet_gauge.shoot() if event.key == pygame.K_p: self.paused = not self.paused if not self.paused and not self.game_over: self.update(time_passed) if self.game_over: self.update_game_over_sequence(time_passed) self.draw() def update(self, time_passed): # Send keyboard input self.ship.handleKeyevents(pygame.key.get_pressed()) # Object updates self.ship.update(time_passed) for bullet in self.bullets: bullet.update(time_passed) for asteroid in self.asteroids: asteroid.update(time_passed, self.ship.pos) # Maintenance functions self.ship.keep_in_bounds() self.maintain_bullets() self.maintain_asteroids() # Collisions self.handle_collisions() # Update bullet gauge self.bullet_gauge.update(time_passed) # Update levels self.handle_levels() # Add asteroids self.spawn_asteroid(time_passed) def draw(self): self.screen.fill(BLACK) # Game HUD self.scoreboard.blitme(self.score) self.level_text.blitme(self.level) if not self.game_over: self.bullet_gauge.blitme() self.health_bar.blitme(self.ship.health) for bullet in self.bullets: bullet.blitme() for asteroid in self.asteroids: asteroid.blitme() if self.keep_drawing_ship: self.ship.blitme() # Game over sequence if self.game_over: self.explosion.blitme() self.game_over_text.blitme() pygame.display.flip() def maintain_bullets(self): for i, bullet in reverse_enumerate(self.bullets): if not bullet.in_bounds(): self.bullets = self.bullets[:i] + self.bullets[i + 1:] def maintain_asteroids(self): for i, asteroid in reverse_enumerate(self.asteroids): if asteroid.time_alive > 1000.0 and not asteroid.in_bounds(): self.asteroids = self.asteroids[:i] + self.asteroids[i + 1:] def handle_collisions(self): # Between bullets and asteroids for i, bullet in reverse_enumerate(self.bullets): for j, asteroid in reverse_enumerate(self.asteroids): if collisions.do_collide(bullet, asteroid): self.bullets = self.bullets[:i] + self.bullets[i + 1:] self.asteroids = self.asteroids[ :j] + self.asteroids[j + 1:] self.score += 1 break if not self.ship.invincible: for i, asteroid in enumerate(self.asteroids): if collisions.do_collide(self.ship, asteroid): self.ship_collision(i) break # Do not collide with anymore asteroids def ship_collision(self, asteroid_index): self.ship.health -= 1 if self.ship.health == 0: self.game_over_sequence(asteroid_index) else: self.ship.make_invincible() def spawn_bullet(self): self.bullets.append(Bullet( self.screen, self.ship.pos, self.ship.dir)) def handle_levels(self): # Check if we passed current level if self.score >= self.level_limit: self.level += 1 self.level_limit = next(self.level_gen) def spawn_asteroid(self, time_passed): self.since_last_asteroid += time_passed if self.since_last_asteroid > self.new_asteroid_time: rand = random.randint(1, 25) if rand <= 1: self.asteroids.append(HomingAsteroid(self.screen)) else: self.asteroids.append(Asteroid(self.screen)) self.since_last_asteroid = 0.0 # Randomize asteroid spawns and add difficulty # by making asteroid spawn faster self.new_asteroid_time = ( random.randint(500, 600) - LEVEL_TIME_CONSTANT * self.level) def game_over_sequence(self, colliding_asteroid_index): """ Sequence played when game is over. Leave only colliding asteroid, remove all bullets. Create ship explosion. Make ship stop displaying, but spawn ship animation. """ self.game_over = 1 time_per_frame = 200 self.bullets = [] self.asteroids = [self.asteroids[colliding_asteroid_index]] self.spawn_ship_explosion(time_per_frame) self.ship_timer = Timer( time_per_frame * 4, self.stop_drawing_ship, 1) def spawn_ship_explosion(self, ms_per_frame): explosion_images = [par_dir() + '/images/explosion%i.png' % i for i in range(1, 11)] self.explosion = Animation( self.screen, self.ship.pos, explosion_images, ms_per_frame, ms_per_frame * 10) def stop_drawing_ship(self): self.keep_drawing_ship = 0 def update_game_over_sequence(self, time_passed): self.explosion.update(time_passed) self.ship_timer.update(time_passed) self.reduce_game_over_text_alpha.update(time_passed)
from foo import Foo from bar import Bar if __name__ == '__main__': b = Bar() print b.get_font() f = Foo() print f.get_font() b.set_font('bar') print b.get_font() print f.get_font() pass
#!/usr/bin/python # Author: Ellis Adigvom <*****@*****.**> from bar import Bar import time import os import widgets PID_FILE = '/home/ellis/.bar_pid' if __name__ == '__main__': bar = Bar() bar.foreground = 'black' bar.height = '25' bar.font = ['siji:size=8', 'ohsnap:size=8'] bar.padding = ' ' mpdwidget = widgets.MpdWidget() mpdwidget.background = 'dark_green' mpdwidget.icon = '' wifiwidget = widgets.WiFiWidget() wifiwidget.background = 'dark_blue' wifiwidget.icon = '' batterywidget = widgets.BatteryWidget() batterywidget.icon = '' batterywidget.hide_value = 80 batterywidget.background = 'blue' clockwidget = widgets.ClockWidget() clockwidget.background = 'red'
def yum(self): bar = Bar() return bar.mitzvah()
def what_is_love(self,i_am): bar = Bar() return bar.give_me_some(i_am)
def add_date_bars(self, x_values, y_values, name='', width=0.5, has_baseline=True, baseline_pos=0, color='', alpha=0.5, total_bars=1, twinx=False, first_last_left_blank=False, plus_minus_seperate_color=False, above_color='red', below_color='blue'): self.alpha = float(alpha) if twinx: self.ax2 = self.ax.twinx() self.bar_count += 1 if len(x_values) > 1: date_interval = mpl.dates.date2num(x_values[1]) - mpl.dates.date2num(x_values[0]) else: date_interval = 1 first_last_left_blank = True bar_width = width * date_interval / total_bars x_values = [mpl.dates.date2num(i)-(date_interval * width/2) + (self.bar_count-1) * bar_width for i in x_values] bar = Bar(self, twinx) y_values = self.change_missing_value(y_values, [np.nan, 'nan', 'Nan'], 0) after_last_date_number = x_values[-1] + date_interval x_values.append(after_last_date_number) y_values.append(0) if first_last_left_blank: first_data_minus_one_period = x_values[0] - date_interval x_values.insert(0, first_data_minus_one_period) y_values.insert(0, 0) if plus_minus_seperate_color: plus_bars = [i if i>baseline_pos else 0 for i in y_values] minus_bars = [i if i<baseline_pos else 0 for i in y_values] self.set_legend(False) bar.date_plotting(x_values, plus_bars, bar_width, name, color=above_color, alpha=float(alpha), twinx=twinx) bar.date_plotting(x_values, minus_bars, bar_width, name, color=below_color, alpha=float(alpha), twinx=twinx) self.now_color = '' else: if color == '': bar_color = self.ax._get_lines.color_cycle.next() else: bar_color = color self.now_color = bar_color bars = bar.date_plotting(x_values, y_values, bar_width, name, color=bar_color, alpha=alpha, twinx=twinx) self.set_legend(True) self._add_legends(bars, name) self.fig.subplots_adjust(left=0.05, right=0.88) no_zero_values = [i for i in y_values if i != 0] if len(no_zero_values) > 0: if max(np.nanmin(no_zero_values) ,np.nanmax(no_zero_values)) < 10: ax2_min = np.nanmin(no_zero_values) -0.5 ax2_max = np.nanmax(no_zero_values) + 0.5 else: ax2_min = np.nanmin(no_zero_values) * 0.95 ax2_max = np.nanmax(no_zero_values) * 1.05 else: ax2_min = -0.5 ax2_max = 0.5 self.add_text(0.40, 0.7, 'no index data found!') self.max_value.append(ax2_max) self.min_value.append(ax2_min) if has_baseline: now_ax = getattr(self, 'ax2' if twinx else 'ax') now_ax.plot(x_values, [baseline_pos]*len(x_values), 'k-') self.min_date = mpl.dates.num2date(x_values[0]) self.max_date = mpl.dates.num2date(x_values[-1]) self.set_xaxis_limit() if twinx: self.set_yaxis_limit(ax2_max, ax2_min,axis=self.ax2, auto=False)
class Game(Menu): # Need draw_text() def __init__(self, start=1): if start: pygame.init() environ['SDL_VIDEO_CENTERED'] = '1' self.scr_size = (800, 600) self.screen = pygame.display.set_mode(self.scr_size) pygame.display.set_caption('Chain Pain - By Jach') while 1: cont = self.load_menu() if cont == 'play': self.load_crap() self.play() break elif cont == 'time': self.high_time() elif cont == 'man': self.instructions() else: exit() def load_menu(self): m = Menu(self.screen) return m.load() def high_time(self): # Display highest time self.screen.fill( (0,0,0) ) # Kill menu best_time = BestTime(self.screen) def instructions(self): self.screen.fill( (0,0,0) ) # Kill menu manual = Man(self.screen) def play(self): self.screen.fill( (0,0,0) ) self.clock = pygame.time.Clock() self.time_passed = 0 self.manlinesses = 2 # Lives self.masters_allowed = 0 # To update self.time_since_whip = 0 self.master_chosen = 0 while 1: self.secs = self.clock.tick(FPS) / 1000.0 self.time_passed += self.secs self.events() self.update_crap() # Updates, no more no less self.draw_crap() # Erases too self.collision_crap() def load_crap(self): # Loads all images, makes objects if applicable, adds any images and # rects to all_sprites{} # Now also loads all sounds at the very top! self.sounds = {'gasp' : self.load_sound('gasp.ogg'),\ 'ugh' : self.load_sound('ugh.ogg'),\ 'ow' : self.load_sound('ow.ogg'),\ 'ahh' : self.load_sound('ahh.ogg'),\ 'cry' : self.load_sound('cry.ogg'),\ 'whip' : self.load_sound('whip.ogg'),\ 'music' : self.load_sound('music1.ogg'),\ 'haha' : self.load_sound('haha.ogg')} self.sounds['music'].play(-1) self.all_sprites = {} self.bg_img = pygame.image.load(\ path.join('data','background.png')).convert_alpha() playerimg=pygame.image.load(path.join('data', 'player.png')).convert_alpha() player_pos = [370,384] # Does not move? self.all_sprites['player'] = [playerimg,player_pos] self.master1 = Master('left', self.screen) self.master2 = Master('right', self.screen) self.all_sprites['master1'] = [self.master1.image, self.master1.rect] self.all_sprites['master2'] = [self.master2.image, self.master2.rect] big_bar = pygame.image.load(path.join('data','big_bar.png')).convert_alpha() big_bar_pos = (400-250, 500) # 500 bottom? 10 top? Edit background for bot self.all_sprites['big_bar'] = [big_bar, big_bar_pos] self.bar = Bar(self.sounds) # Moving bar self.all_sprites['moving_bar'] = [self.bar.image, self.bar.rect] self.timer = Timer() #Clock so player knows how long they've gone self.all_sprites['timer'] = [self.timer.image, self.timer.rect] manliness = pygame.image.load(\ path.join('data','manliness.png')).convert_alpha() manliness1pos = (65, 1) manliness2pos = (100, 1) self.all_sprites['man1'] = [manliness, manliness1pos] self.all_sprites['man2'] = [manliness, manliness2pos] self.blood = Blood(self.screen, player_pos) self.all_sprites['blood'] = [self.blood.image, self.blood.rect] def draw_crap(self): # Erase everything first (yeah yeah optimization later) self.screen.blit(self.bg_img, (0,0) ) for key in sorted(self.all_sprites): self.screen.blit(self.all_sprites[key][0], self.all_sprites[key][1]) # Note: if I need something to blit on top of something else, give # it a z first letter or something. self.master1.chain.redraw_chain() self.master2.chain.redraw_chain() pygame.display.update() def update_crap(self): self.bar.update(self.secs) # Update bar self.all_sprites['moving_bar'][1] = self.bar.rect # Update rect self.timer.update(self.time_passed) # Update clock self.all_sprites['timer'][0] = self.timer.image # update image if not self.masters_allowed and randint(1, 70) == 1: self.masters_allowed = 1 if self.masters_allowed and randint(1,5) == 1: # Rand used to slow down # Masters can update if not self.master_chosen: self.master_chosen = randint(1, 3) if self.master_chosen == 1: self.master1.update() self.all_sprites['master1'][0] = self.master1.image if self.master_chosen == 2: self.master2.update() self.all_sprites['master2'][0] = self.master2.image if self.master_chosen == 3: self.master1.update() self.master2.update() self.all_sprites['master1'][0] = self.master1.image self.all_sprites['master2'][0] = self.master2.image self.clock.tick(FPS) if self.master1.state == 0 and self.master2.state == 0: # Done animating self.masters_allowed = 0 self.master_chosen = 0 self.blood.image = self.blood.blank_image self.all_sprites['blood'][0] = self.blood.image else: # masters can't update, still need to draw chain pass def events(self): for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: exit() if event.key == K_LEFT: self.bar.push = -1 if event.key == K_RIGHT: self.bar.push = 1 def collision_crap(self): if self.bar.rect.x < 0: # Class bounds it self.manlinesses -= 1 self.sounds['haha'].play() if self.manlinesses == 0: self.gameover() else: self.all_sprites.pop('man2') self.bar = Bar(self.sounds) # Moving bar self.all_sprites['moving_bar'] = [self.bar.image, self.bar.rect] self.bar.v_change = -20 self.all_sprites['player'][0] = pygame.image.load(\ path.join('data','deadplayer.png')).convert_alpha() # Whip on player? if self.master1.state == 3: # Final chain self.bar.v_change = 200 self.sounds['whip'].play() self.bar.play_sound() self.time_since_whip = self.time_passed if self.master2.state == 3: self.bar.v_change = 200 self.sounds['whip'].play() self.bar.play_sound() if self.master1.state == 3 and self.master2.state == 3: self.bar.v_change = 400 if (self.master1.state == 0 or self.master2.state == 0) and \ self.time_passed - self.time_since_whip >= 0.5: self.bar.v_change = 0 if self.master1.state == 2 or self.master2.state == 2: self.blood.render_blood() self.all_sprites['blood'][0] = self.blood.image def load_sound(self, sound): file = pygame.mixer.Sound(path.join('data',sound)) return file def gameover(self): for e in self.sounds.itervalues(): e.stop() self.sounds['cry'].play() self.all_sprites['player'][0] = pygame.image.load(\ path.join('data','superdeadplayer.png')).convert_alpha() self.draw_crap() pygame.display.update() pygame.time.wait(700) # wait half a sec so they can see their death self.screen.fill( (0,0,0) ) # Grab time mins = '%02d' % (self.time_passed / 60) secs = '%02d' % (self.time_passed % 60) font = pygame.font.Font(path.join('data','cour.ttf'), 50) font2 = pygame.font.Font(path.join('data','digib.ttf'), 70) font.set_underline(1) self.draw_text('Final Time', font, (5,0), (255,255,255) ) font.set_underline(0) self.draw_text(mins + ':' + secs, font2, (5, 100), (255,255,255) ) # Check if it was a high score f = open(path.join('data', 'best_time.txt'), 'r') line = f.next().replace('\n', '').split(' ')[1].split(':') beaten = 0 if int(line[0]) * 60 + int(line[1]) < int(self.time_passed): self.draw_text('Congrats!', font,\ (5, 200), (255,255,255)) self.draw_text('You beat the best time!', font, (5,300), (255,255,255)) self.draw_text('Enter your initials:', font, (5,400), (255,255,255)) f.close() beaten = 1 pygame.display.update() if not beaten: while 1: self.clock.tick(10) for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_ESCAPE or event.key == K_RETURN: self.screen.fill( (0,0,0) ) pygame.display.update() self.__init__(0) else: self.enter_initials(mins, secs, font) def enter_initials(self, mins, secs, font): font.set_underline(1) letters = 0 initials = '' pygame.event.clear() while 1: self.clock.tick(10) if letters > 2: break for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN and letters < 3: letters += 1 self.draw_text(event.unicode.upper(), font,\ (letters * 50, 500), (255,255,255)) initials += event.unicode.upper() f = open(path.join('data', 'best_time.txt'), 'w') f.write(initials + ' ' + mins + ':' + secs) f.close() self.screen.fill( (0,0,0) ) pygame.display.update() self.__init__(0)
class Bounce(): ''' The Bounce class is used to define the ball and the user interaction. ''' def __init__(self, canvas, path, parent=None): ''' Initialize the canvas and set up the callbacks. ''' self._activity = parent self._fraction = None self._path = path if parent is None: # Starting from command line self._sugar = False else: # Starting from Sugar self._sugar = True self._canvas = canvas self._canvas.grab_focus() self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK) self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK) self._canvas.add_events(Gdk.EventMask.KEY_PRESS_MASK) self._canvas.add_events(Gdk.EventMask.KEY_RELEASE_MASK) self._canvas.connect('draw', self.__draw_cb) self._canvas.connect('button-press-event', self._button_press_cb) self._canvas.connect('button-release-event', self._button_release_cb) self._canvas.connect('key-press-event', self._keypress_cb) self._canvas.connect('key-release-event', self._keyrelease_cb) self._canvas.set_can_focus(True) self._canvas.grab_focus() self._sprites = Sprites(self._canvas) self._width = Gdk.Screen.width() self._height = Gdk.Screen.height() - GRID_CELL_SIZE self._scale = Gdk.Screen.height() / 900.0 self._timeout = None self.buddies = [] # used for sharing self._my_turn = False self.select_a_fraction = False self._easter_egg = int(uniform(1, 100)) # Find paths to sound files self._path_to_success = os.path.join(path, LAUGH) self._path_to_failure = os.path.join(path, CRASH) self._path_to_bubbles = os.path.join(path, BUBBLES) self._create_sprites(path) self.mode = 'fractions' self._challenge = 0 self._expert = False self._challenges = [] for challenge in CHALLENGES[self._challenge]: self._challenges.append(challenge) self._fraction = 0.5 # the target of the current challenge self._label = '1/2' # the label self.count = 0 # number of bounces played self._correct = 0 # number of correct answers self._press = None # sprite under mouse click self._new_bounce = False self._n = 0 self._accel_index = 0 self._accel_flip = False self._accel_xy = [0, 0] self._guess_orientation() self._dx = 0. # ball horizontal trajectory # acceleration (with dampening) self._ddy = (6.67 * self._height) / (STEPS * STEPS) self._dy = self._ddy * (1 - STEPS) / 2. # initial step size if self._sugar: if _is_tablet_mode(): self._activity.reset_label( _('Click the ball to start. Rock the computer left ' 'and right to move the ball.')) else: self._activity.reset_label( _('Click the ball to start. Then use the arrow keys to ' 'move the ball.')) def _accelerometer(self): return os.path.exists(ACCELEROMETER_DEVICE) and _is_tablet_mode() def configure_cb(self, event): self._width = Gdk.Screen.width() self._height = Gdk.Screen.height() - GRID_CELL_SIZE self._scale = Gdk.Screen.height() / 900.0 # We need to resize the backgrounds width, height = self._calc_background_size() for bg in self._backgrounds.keys(): if bg == 'custom': path = self._custom_dsobject.file_path pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( path, width, height) else: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( os.path.join(self._path, 'images', bg), width, height) if Gdk.Screen.height() > Gdk.Screen.width(): pixbuf = self._crop_to_portrait(pixbuf) self._backgrounds[bg] = pixbuf self._background = Sprite(self._sprites, 0, 0, self._backgrounds[self._current_bg]) self._background.set_layer(-100) self._background.type = 'background' # and resize and reposition the bars self.bar.resize_all() self.bar.show_bar(2) self._current_bar = self.bar.get_bar(2) # Calculate a new accerlation based on screen height. self._ddy = (6.67 * self._height) / (STEPS * STEPS) self._guess_orientation() def _create_sprites(self, path): ''' Create all of the sprites we'll need ''' self.smiley_graphic = svg_str_to_pixbuf(svg_from_file( os.path.join(path, 'images', 'smiley.svg'))) self.frown_graphic = svg_str_to_pixbuf(svg_from_file( os.path.join(path, 'images', 'frown.svg'))) self.blank_graphic = svg_str_to_pixbuf( svg_header(REWARD_HEIGHT, REWARD_HEIGHT, 1.0) + svg_rect(REWARD_HEIGHT, REWARD_HEIGHT, 5, 5, 0, 0, 'none', 'none') + svg_footer()) self.ball = Ball(self._sprites, os.path.join(path, 'images', 'soccerball.svg')) self._current_frame = 0 self.bar = Bar(self._sprites, self.ball.width(), COLORS) self._current_bar = self.bar.get_bar(2) self.ball_y_max = self.bar.bar_y() - self.ball.height() + \ int(BAR_HEIGHT / 2.) self.ball.move_ball((int((self._width - self.ball.width()) / 2), self.ball_y_max)) self._backgrounds = {} width, height = self._calc_background_size() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( os.path.join(path, 'images', 'grass_background.png'), width, height) if Gdk.Screen.height() > Gdk.Screen.width(): pixbuf = self._crop_to_portrait(pixbuf) self._backgrounds['grass_background.png'] = pixbuf self._background = Sprite(self._sprites, 0, 0, pixbuf) self._background.set_layer(-100) self._background.type = 'background' self._current_bg = 'grass_background.png' def _crop_to_portrait(self, pixbuf): tmp = GdkPixbuf.Pixbuf.new(0, True, 8, Gdk.Screen.width(), Gdk.Screen.height()) x = int(Gdk.Screen.height() / 3) pixbuf.copy_area(x, 0, Gdk.Screen.width(), Gdk.Screen.height(), tmp, 0, 0) return tmp def _calc_background_size(self): if Gdk.Screen.height() > Gdk.Screen.width(): height = Gdk.Screen.height() return int(4 * height / 3), height else: width = Gdk.Screen.width() return width, int(3 * width / 4) def new_background_from_image(self, path, dsobject=None): if path is None: path = dsobject.file_path width, height = self._calc_background_size() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( path, width, height) if Gdk.Screen.height() > Gdk.Screen.width(): pixbuf = self._crop_to_portrait(pixbuf) self._backgrounds['custom'] = pixbuf self.set_background('custom') self._custom_dsobject = dsobject self._current_bg = 'custom' def set_background(self, name): if not name in self._backgrounds: width, height = self._calc_background_size() pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size( os.path.join(self._path, 'images', name), width, height) if Gdk.Screen.height() > Gdk.Screen.width(): pixbuf = self._crop_to_portrait(pixbuf) self._backgrounds[name] = pixbuf self._background.set_image(self._backgrounds[name]) self.bar.mark.hide() self._current_bar.hide() self.ball.ball.hide() self.do_expose_event() self.ball.ball.set_layer(3) self._current_bar.set_layer(2) self.bar.mark.set_layer(1) self._current_bg = name def pause(self): ''' Pause play when visibility changes ''' if self._timeout is not None: GObject.source_remove(self._timeout) self._timeout = None def we_are_sharing(self): ''' If there is more than one buddy, we are sharing. ''' if len(self.buddies) > 1: return True def its_my_turn(self): ''' When sharing, it is your turn... ''' GObject.timeout_add(1000, self._take_a_turn) def _take_a_turn(self): ''' On your turn, choose a fraction. ''' self._my_turn = True self.select_a_fraction = True self._activity.set_player_on_toolbar(self._activity.nick) self._activity.reset_label( _("Click on the bar to choose a fraction.")) def its_their_turn(self, nick): ''' When sharing, it is nick's turn... ''' GObject.timeout_add(1000, self._wait_your_turn, nick) def _wait_your_turn(self, nick): ''' Wait for nick to choose a fraction. ''' self._my_turn = False self._activity.set_player_on_toolbar(nick) self._activity.reset_label( _('Waiting for %(buddy)s') % {'buddy': nick}) def play_a_fraction(self, fraction): ''' Play this fraction ''' fraction_is_new = True for i, c in enumerate(self._challenges): if c[0] == fraction: fraction_is_new = False self._n = i break if fraction_is_new: self.add_fraction(fraction) self._n = len(self._challenges) self._choose_a_fraction() self._move_ball() def _button_press_cb(self, win, event): ''' Callback to handle the button presses ''' win.grab_focus() x, y = map(int, event.get_coords()) self._press = self._sprites.find_sprite((x, y)) return True def _button_release_cb(self, win, event): ''' Callback to handle the button releases ''' win.grab_focus() x, y = map(int, event.get_coords()) if self._press is not None: if self.we_are_sharing(): if self.select_a_fraction and self._press == self._current_bar: # Find the fraction closest to the click fraction = self._search_challenges( (x - self.bar.bar_x()) / float(self.bar.width())) self.select_a_fraction = False self._activity.send_a_fraction(fraction) self.play_a_fraction(fraction) else: if self._timeout is None and self._press == self.ball.ball: self._choose_a_fraction() self._move_ball() return True def _search_challenges(self, f): ''' Find the fraction which is closest to f in the list. ''' dist = 1. closest = '1/2' for c in self._challenges: numden = c[0].split('/') delta = abs((float(numden[0]) / float(numden[1])) - f) if delta <= dist: dist = delta closest = c[0] return closest def _guess_orientation(self): if self._accelerometer(): fh = open(ACCELEROMETER_DEVICE) string = fh.read() fh.close() xyz = string[1:-2].split(',') x = int(xyz[0]) y = int(xyz[1]) self._accel_xy = [x, y] if abs(x) > abs(y): self._accel_index = 1 # Portrait mode self._accel_flip = x > 0 else: self._accel_index = 0 # Landscape mode self._accel_flip = y < 0 def _move_ball(self): ''' Move the ball and test boundary conditions ''' if self._new_bounce: self.bar.mark.move((0, self._height)) # hide the mark if not self.we_are_sharing(): self._choose_a_fraction() self._new_bounce = False self._dy = self._ddy * (1 - STEPS) / 2 # initial step size if self._accelerometer(): self._guess_orientation() self._dx = float(self._accel_xy[self._accel_index]) / 18. if self._accel_flip: self._dx *= -1 if self.ball.ball_x() + self._dx > 0 and \ self.ball.ball_x() + self._dx < self._width - self.ball.width(): self.ball.move_ball_relative((int(self._dx), int(self._dy))) else: self.ball.move_ball_relative((0, int(self._dy))) # speed up ball in x while key is pressed self._dx *= DDX # accelerate in y self._dy += self._ddy # Calculate a new ball_y_max depending on the x position self.ball_y_max = self.bar.bar_y() - self.ball.height() + \ self._wedge_offset() if self.ball.ball_y() >= self.ball_y_max: # hit the bottom self.ball.move_ball((self.ball.ball_x(), self.ball_y_max)) self._test() self._new_bounce = True if self.we_are_sharing(): if self._my_turn: # Let the next player know it is their turn. i = (self.buddies.index(self._activity.nick) + 1) % \ len(self.buddies) self.its_their_turn(self.buddies[i]) self._activity.send_event('', {"data": (self.buddies[i])}) else: if not self.we_are_sharing() and self._easter_egg_test(): self._animate() else: self._timeout = GObject.timeout_add( max(STEP_PAUSE, BOUNCE_PAUSE - self.count * STEP_PAUSE), self._move_ball) else: self._timeout = GObject.timeout_add(STEP_PAUSE, self._move_ball) def _wedge_offset(self): return int(BAR_HEIGHT * (1 - (self.ball.ball_x() / float(self.bar.width())))) def _mark_offset(self, x): return int(BAR_HEIGHT * (1 - (x / float(self.bar.width())))) - 12 def _animate(self): ''' A little Easter Egg just for fun. ''' if self._new_bounce: self._dy = self._ddy * (1 - STEPS) / 2 # initial step size self._new_bounce = False self._current_frame = 0 self._frame_counter = 0 self.ball.move_frame(self._current_frame, (self.ball.ball_x(), self.ball.ball_y())) self.ball.move_ball((self.ball.ball_x(), self._height)) GObject.idle_add(play_audio_from_file, self, self._path_to_bubbles) if self._accelerometer(): fh = open(ACCELEROMETER_DEVICE) string = fh.read() xyz = string[1:-2].split(',') self._dx = float(xyz[0]) / 18. fh.close() else: self._dx = uniform(-int(DX * self._scale), int(DX * self._scale)) self.ball.move_frame_relative( self._current_frame, (int(self._dx), int(self._dy))) self._dy += self._ddy self._frame_counter += 1 self._current_frame = self.ball.next_frame(self._frame_counter) if self.ball.frame_y(self._current_frame) >= self.ball_y_max: # hit the bottom self.ball.move_ball((self.ball.ball_x(), self.ball_y_max)) self.ball.hide_frames() self._test(easter_egg=True) self._new_bounce = True self._timeout = GObject.timeout_add(BOUNCE_PAUSE, self._move_ball) else: GObject.timeout_add(STEP_PAUSE, self._animate) def add_fraction(self, string): ''' Add a new challenge; set bar to 2x demominator ''' numden = string.split('/', 2) self._challenges.append([string, int(numden[1]), 0]) def _get_new_fraction(self): ''' Select a new fraction challenge from the table ''' if not self.we_are_sharing(): n = int(uniform(0, len(self._challenges))) else: n = self._n fstr = self._challenges[n][0] if '/' in fstr: # fraction numden = fstr.split('/', 2) fraction = float(numden[0].strip()) / float(numden[1].strip()) elif '%' in fstr: # percentage fraction = float(fstr.strip().strip('%').strip()) / 100. else: # To do: add support for decimals (using locale) _logger.debug('Could not parse challenge (%s)', fstr) fstr = '1/2' fraction = 0.5 return fraction, fstr, n def _choose_a_fraction(self): ''' choose a new fraction and set the corresponding bar ''' # Don't repeat the same fraction twice in a row fraction, fstr, n = self._get_new_fraction() if not self.we_are_sharing(): while fraction == self._fraction: fraction, fstr, n = self._get_new_fraction() self._fraction = fraction self._n = n if self.mode == 'percents': self._label = str(int(self._fraction * 100 + 0.5)) + '%' else: # percentage self._label = fstr if self.mode == 'sectors': self.ball.new_ball_from_fraction(self._fraction) if not Gdk.Screen.width() < 1024: self._activity.reset_label( _('Bounce the ball to a position ' '%(fraction)s of the way from the left side of the bar.') % {'fraction': self._label}) else: self._activity.reset_label(_('Bounce the ball to %(fraction)s') % {'fraction': self._label}) self.ball.ball.set_label(self._label) self.bar.hide_bars() if self._expert: # Show two-segment bar in expert mode nseg = 2 else: if self.mode == 'percents': nseg = 10 else: nseg = self._challenges[self._n][1] # generate new bar on demand self._current_bar = self.bar.get_bar(nseg) self.bar.show_bar(nseg) def _easter_egg_test(self): ''' Test to see if we show the Easter Egg ''' delta = self.ball.width() / 8 x = self.ball.ball_x() + self.ball.width() / 2 f = self.bar.width() * self._easter_egg / 100. if x > f - delta and x < f + delta: return True else: return False def _test(self, easter_egg=False): ''' Test to see if we estimated correctly ''' self._timeout = None if self._expert: delta = self.ball.width() / 6 else: delta = self.ball.width() / 3 x = self.ball.ball_x() + self.ball.width() / 2 f = int(self._fraction * self.bar.width()) self.bar.mark.move((int(f - self.bar.mark_width() / 2), int(self.bar.bar_y() + self._mark_offset(f)))) if self._challenges[self._n][2] == 0: # label the column spr = Sprite(self._sprites, 0, 0, self.blank_graphic) spr.set_label(self._label) spr.move((int(self._n * 27), 0)) spr.set_layer(-1) self._challenges[self._n][2] += 1 if x > f - delta and x < f + delta: spr = Sprite(self._sprites, 0, 0, self.smiley_graphic) self._correct += 1 GObject.idle_add(play_audio_from_file, self, self._path_to_success) else: spr = Sprite(self._sprites, 0, 0, self.frown_graphic) GObject.idle_add(play_audio_from_file, self, self._path_to_failure) spr.move((int(self._n * 27), int(self._challenges[self._n][2] * 27))) spr.set_layer(-1) # after enough correct answers, up the difficulty if self._correct == len(self._challenges) * 2: self._challenge += 1 if self._challenge < len(CHALLENGES): for challenge in CHALLENGES[self._challenge]: self._challenges.append(challenge) else: self._expert = True self.count += 1 self._dx = 0. # stop horizontal movement between bounces def _keypress_cb(self, area, event): ''' Keypress: moving the slides with the arrow keys ''' k = Gdk.keyval_name(event.keyval) if k in ['KP_Page_Down', 'KP_Home', 'h', 'Left', 'KP_Left']: self._dx = -DX * self._scale elif k in ['KP_Page_Up', 'KP_End', 'l', 'Right', 'KP_Right']: self._dx = DX * self._scale elif k in ['Return']: self._choose_a_fraction() self._move_ball() else: self._dx = 0. if self._accel_flip: self._dx = -self._dx return True def _keyrelease_cb(self, area, event): ''' Keyrelease: stop horizontal movement ''' self._dx = 0. return True def __draw_cb(self, canvas, cr): self._sprites.redraw_sprites(cr=cr) def do_expose_event(self, event=None): ''' Handle the expose-event by drawing ''' # Restrict Cairo to the exposed area cr = self._activity.get_window().cairo_create() if event is None: cr.rectangle(0, 0, Gdk.Screen.width(), Gdk.Screen.height()) else: cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) cr.clip() self._sprites.redraw_sprites(cr=cr) def _destroy_cb(self, win, event): ''' Callback to handle quit ''' Gtk.main_quit()
def complete_implement(if_new, type, dir, true_folder_path): prompt = '>' operate_type = '' print "Type:" + type + ", as follows:" for temp in dir: print temp if if_new != '3': print "Choose operate type:" print "1: CNN+RF based on trained CNN model;" print "2: CNN+SVM based on trained CNN model;" print "3: Fine tune trained CNN network;" print "4: Draw RGB graphs;" operate_type = raw_input(prompt) elif if_new == '3': print "Compute OA,AA and Kappa on batched experiments." operate_type = '5' #选择类型 #1 已有CNN模型,进行CNN+RF的实验 #2 已有CNN模型,进行CNN+SVM的实验 #3 对CNN进行训练微调 #4 没有RGB图像,补充RGB图像 #5 根据已有的实验结果计算OA、AA、Kappa系数等参数 #operate_type = raw_input(prompt) trees = '' if operate_type == '1': print "Enter the number of trees you want to set in RF, if you want it to be a series trees, use - to express it, for example: if you want to do a series trees experiments among 1 to 20, enter 1-20. no space or other char between numbers." trees = raw_input(prompt) if type == 'one': #执行一个逻辑 complete_operate(operate_type = operate_type, folder_path = dir, trees = trees, neurons = neurons, neuronLayersCount = neuronLayersCount, maxpoolings = maxpoolings, fullLayers = fullLayers) else: #执行一组的逻辑 neurons = "" neuronLayersCount = "" maxpoolings = "" fullLayers = "" data_set_name_in_configure = "" if os.path.exists(true_folder_path + '/network.conf'): print "Fetching configurations in the network.conf file...." cf = ConfigParser.ConfigParser() cf.read(true_folder_path + '/network.conf') data_set_name_in_configure = cf.get("cnn","dataset") print "data set is " + data_set_name_in_configure neurons = cf.get("cnn", "conv_neuron_count") neuronLayersCount = cf.get("cnn", "conv_layer_count") maxpoolings = cf.get("cnn", "maxpooling_size") fullLayers = cf.get("cnn", "fully_layers_count") print "the number of convolutional neurons is " + neurons print "the number of layers of each convolutional neuron operates is " + neuronLayersCount print "the number of numbers of each maxpooling kernel operates is " + maxpoolings print "the number of neurons in full layer is " + fullLayers else: print "网络参数配置文件不存在,请手动输入:" print "Enter convolutional neurons in this network:" neurons = int(raw_input(prompt)) print "Enter layers each convolutional neuron operates:" neuronLayersCount = int(raw_input(prompt)) print "Enter maxpooling kernel size:" maxpoolings = int(raw_input(prompt)) print "Enter fully layer neurons count:" fullLayers = int(raw_input(prompt)) bar = Bar(total = len(dir)) for folder in dir: bar.move() bar.log('Now processing ' + folder + '...') complete_operate(operate_type = operate_type, folder_path = folder, trees = trees, neurons = neurons, neuronLayersCount = neuronLayersCount, maxpoolings = maxpoolings, fullLayers = fullLayers) #完成后计算精度 print "Now calculating the average accuracy of all results..." #遍历SumResults目录 sum_results_folder = true_folder_path + '/SumResults' print "Results are saved in " + sum_results_folder + "." files = os.listdir(sum_results_folder) # print files sum_result_txt = open(sum_results_folder + '/results.txt','w') bar = Bar(total = len(files)) for result_file in files: bar.move() bar.log('Now calcluating for ' + result_file + "...") file_whole = result_file file_name = result_file.split('.')[0] sum_result_txt.write(file_name + ":") OA = cal_oa(sum_results_folder + '/' + file_whole) kappa = cal_kappa(sum_results_folder + "/" + file_whole) sum_result_txt.write("\t\tOA:" + str(OA) + "\t\tkappa:" + str(kappa) + "\n") sum_result_txt.close()