def __init__(self, surface, color, width, height, x, y, song_name): self.surface = surface self.color = color self.width = width self.height = height self.x = x self.y = y self.song_title = song_name self.score = 0 self.status_icons = {} #sub bars self.barHeight = height*.5 #factor of how large the bar is. 1 = 100% self.barY = (height-self.barHeight)/2 self.font = pygame.font.Font(None, 26) self.hpPos = 400 self.mpPos = 600 self.song_title_pos = 80 self.healthBar = Bar(surface=self.surface, frontColor=(255,0,0), backColor=(128,128,128), curValue=100, maxValue=100, width=150, height=self.barHeight, x=self.hpPos, y=self.barY) self.kiBar = Bar(surface=self.surface, frontColor=(0,0,255), backColor=(128,128,128), curValue=100, maxValue=100, width=150, height=self.barHeight, x=self.mpPos, y=self.barY) self.draw() self.update_score(0) # Force draw the initial zero
def __init__(self, center_x, center_y, animation_images, saved_params=None): super().__init__(center_x, center_y, animation_images) self._max_health = self._max_mana = self._max_stamina = 100 self._speed_changing = 3 self._amount_damage = random.randint(140, 200) self._passive_regeneration = 0.1 self._regeneration_interval = 10 self._last_attack_time = 250 self._animation_interval = 150 self._experience_up_level = 1000 * pow(1.1, self._level) self._selected_attack = GameEnums.AttackTypes.FIREBALL.value self._inventory = Inventory.Inventory() self._health_bar = Bar.Bar(Constants.GAME_WINDOW_WIDTH // 2 - 250, Constants.GAME_WINDOW_HEIGHT - 96, 'resources/images/bars/health_bar.png') self._mana_bar = Bar.Bar(Constants.GAME_WINDOW_WIDTH // 2 + 155, Constants.GAME_WINDOW_HEIGHT - 96, 'resources/images/bars/mana_bar.png') if saved_params is None: self._level = 1 self._current_experience = 0 self._current_health = 100 self._current_stamina = self._max_stamina self._current_mana = self._max_mana else: self._level = saved_params['level'] self._current_experience = saved_params['current_experience'] self._current_health = saved_params['current_health'] self._current_stamina = saved_params['current_stamina'] self._current_mana = saved_params['current_mana']
def setUp(self): self.c = Character("bob") self.bar = Bar("Test") self.bar.add_box(Box(1)) self.bar.add_box(Box(2)) self.bar.add_box(Box(3)) self.bar.add_box(Box(4)) self.c.add_bar(self.bar)
def bar_default(name): """ Returns a bar of size 1, 2 :param name: the name of the bar :return: """ b = Bar(name) b.add_box(Box(1)) b.add_box(Box(2)) return b
def sethero(self): i = None for i in self.planets: break self.player = Player((i.rect.x, i.rect.y - i.radius)) if loadlatest == True and self.s.dataexist(): t = self.s.loadrecent() self.player.pos = np.array([t[1], t[2]]) self.player.vel = np.array([t[3], t[4]]) self.player.angle = t[5] self.player.accel = np.array([t[6], t[7]]) self.hero.add(self.player) self.fuelbar = Bar()
def reset(self): self.bars.clear() y0 = -self.bar_height for i in range(self.number_of_bars): self.bars.append( Bar(self.game, Vector2D(0, y0 - i * (self.offset + self.bar_height))))
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.W = self.parent.winfo_screenwidth() - bbc.MIN_W self.H = self.parent.winfo_screenheight() - bbc.MIN_H if self.W < bbc.MIN_W: self.W = bbc.MIN_W if self.H < bbc.MIN_H: self.H = bbc.MIN_H self.board = Board(self) self.ball = Ball(self.board) self.barTop = Bar(self.board, bbc.BAR_T) self.barBottom = Bar(self.board, bbc.BAR_B) self.initialize()
def __init__(self, name, refresh_rate=3): self.name = name self.bars = {} # address bars by name self.aspects = AspectContainer() self.skills = SkillContainer() self.fate = 0 self.refresh_rate = refresh_rate self.consequence_bar = Bar("consequence") self.consequences = []
def bar_consequence(name): """ Returns a bar of size 2, 4, 6 :param name: the name of the bar :return: """ b = Bar(name) b.add_box(Box(2)) b.add_box(Box(4)) b.add_box(Box(6)) return b
def insertEmptyBar(self,n): i=n bar = Bar.Bar() while(i>1): rownum = self.dailyBar.shape[0]-1 bar.strtime=' ' bar.utc_time=self.dailyBar.ix[rownum]['utcdatetime']+60 bar.open=0 bar.close=0 bar.high=self.dailyBar.ix[rownum]['high'] bar.low=self.dailyBar.ix[rownum]['low'] bar.position=self.dailyBar.ix[rownum]['position'] self.update_dailyBar(bar) if(datetime.datetime.fromtimestamp(bar.utc_time).minute% self.K_min==0): self.update_dailyBarMin(bar) pass i-=1 pass
def get_bars(songs_data): bars = [] for song_data in songs_data: seg_starts = song_data.seg_starts bar_starts = song_data.bar_starts pitches = song_data.seg_pitches # Because of how the song data is being collected, these two # don't match up, even though they should pitches_and_segs = min(len(pitches), len(seg_starts)) - 1 # The bars starts don't match exactly with the pitch starts, # hence this mess for i in xrange(pitches_and_segs): # The if should be true for bar_starts[len(bars)], but this # is to make sure. for j in range(len(bars), len(bar_starts)): if seg_starts[i] < bar_starts[j] < seg_starts[i+1]: bars.append(str(Bar.Bar(SongData.get_pitch(pitches[i])))) return bars
from DirectorioDeBares import * from Bar import * from Caracteristica import * from Calificacion import * from RegistroDeCalificaciones import * from Cartografo import * wifi = Caracteristica("Wi-Fi") aircon = Caracteristica("Aire Acondicionado") precios = Caracteristica("Precios") directorio = DirectorioDeBares() cartografo = Cartografo() bar1 = Bar("Tienda del cafe", "Santa Fe y Callao", [wifi]) bar2 = Bar("Cafe Martinez", "Av. Pueyrredon y Cordoba", [wifi, aircon, precios]) bar3 = Bar("Starbucks", "Las Heras y Uriburu", [aircon, precios, Caracteristica("enchufes")]) bar4 = Bar("Tips", "Las Heras y Av. Pueyrredon", [wifi]) bar5 = Bar("Muu lecheria", "Costa Rica y Armenia", []) bar6 = Bar("La biela", "Junin y Guido", [wifi]) bar7 = Bar("Pani", "Junin y Vicente Lopez", [wifi, precios]) bar8 = Bar("Milli", "Av. Pueyrredon y French", [wifi, aircon, precios]) directorio.agregar(bar1) directorio.agregar(bar2) directorio.agregar(bar3) directorio.agregar(bar4) directorio.agregar(bar5)
if args.gis: from GIS import * gis(args.gis) if args.type == 'Pie' and args.title == None: parser.error('If you want a Pie plot, you also have to set a title with -title argument') if args.type == "bar": parse_bar = ParseBar(args.input) dict_bar = parse_bar.process_data() if args.dimension == "2D": bar = Bar2D(dict_bar) else: bar = Bar(dict_bar) if args.view == "image": bar.init("image") else: bar.init("gui") elif args.type == "scatter": parse_scatter = ParseScatter(args.input) dict_scatter = parse_scatter.process_data() if args.dimension == "2D": scatter = Scatter2D(dict_scatter) else: scatter = Scatter(dict_scatter)
def set(canvas,g): axes = adxl345.getAxes(True) g.setGforce(axes['x'],axes['y']) canvas.after(5,set,canvas,g) None root = Tk() canvas = Canvas(root,width=winWidth,height=winHeight,bg="white") canvas.pack() rpm = Rpm(canvas,winWidth/2,winHeight/4,winWidth/1.25,winHeight/4,50,"yellow","yellow",20,140,0,10000) speed = Text(canvas,winWidth/2,winHeight/4,"Helvetica",speedFontSize,"bold italic","black","137") mileage = Text(canvas,winWidth/2,(winHeight/10)*3,"Helvetica",10,"bold ","black","162.372 KM") clutch=Bar(canvas,winWidth-92,winHeight,30,-60,"blue") brake=Bar(canvas,winWidth-61,winHeight,30,-30,"red") throttle=Bar(canvas,winWidth-30,winHeight,30,-100,"green") temp1 = Circle(canvas,(winWidth/4)*1,(winHeight/2)*1,100,25,240,300,20,100,"#28cfbc",circleFontSize,"OIL T.") temp2 = Circle(canvas,(winWidth/4)*2,(winHeight/2)*1,100,25,240,300,20,100,"#28cfbc",circleFontSize,"OIL P.") temp3 = Circle(canvas,(winWidth/4)*3,(winHeight/2)*1,100,25,240,300,20,100,"#28cfbc",circleFontSize,"H2O T.") temp4 = Circle(canvas,(winWidth/4)*1,(winHeight/4)*3,100,25,240,300,20,100,"#28cfbc",circleFontSize,"H2O T.2") temp5 = Circle(canvas,(winWidth/4)*2,(winHeight/4)*3,100,25,240,300,20,100,"#28cfbc",circleFontSize,"IAT") #temp6 = Circle(canvas,(winWidth/4)*3,(winHeight/4)*3,100,25,240,300,20,100,"#28cfbc",circleFontSize,"BAT") arrowLeft=Arrow(canvas,(winWidth/3)*1,winHeight/4,0.15,"green","left") arrowRight=Arrow(canvas,(winWidth/3)*2,winHeight/4,0.15,"green","right") g = Gforce(canvas,(winWidth/4)*3,(winHeight/4)*3,125,2,1,"gray",4,"red")
chord_list += [chord_name_em, chord_name_a, chord_name_d, chord_name_d] tempo = 200.0 midi = pretty_midi.PrettyMIDI(initial_tempo=tempo) music_program = pretty_midi.instrument_name_to_program('Vibraphone') chord_program = pretty_midi.instrument_name_to_program('Marimba') music_part = pretty_midi.Instrument(program=music_program) chord_part = pretty_midi.Instrument(program=chord_program) ## 本番 # now_pos: 16分音符何個分の位置にいるか now_pos = 0 for chord_s in chord_list: chord = Chord.Chord(chord_s) # 主旋律 bar = Bar.Bar(chord, tempo, now_pos) nodes = bar.Nodes for node in nodes: note = node.note music_part.notes.append(note) # コードの貼り付け for pitch_int in chord.pitch_ints: node = Node.Node(16, pitch_int, now_pos, tempo) note = node.note chord_part.notes.append(note) # 共通 now_pos += 16 # コードだけ # for chord_s in chord_list: # chord = Chord.Chord(chord_s)
class Display: def __init__(self, dbcom=""): py.init() self.s = None if dbcom == "create": self.s = Saver("create") else: self.s = Saver() self.initdisplayvar() self.win = py.display.set_mode((self.winx, self.winy)) self.sound = Sound() self.writer = Text(self.win) self.init_event_variables() self.run() self.spacewalk = np.array([0, 0]) def initdisplayvar(self): self.winx = 900 self.winy = 800 self.stopgame = False def init_event_variables(self): self.planets = [] self.hero = py.sprite.Group() self.map = py.sprite.Group() self.missiles = py.sprite.Group() self.satellites = py.sprite.Group() self.explosions = py.sprite.Group() self.trail = Trail() self.player = None self.fuelbar = None self.wkup = False self.wkdo = False self.wklf = False self.wkrh = False self.zoomin = False self.zoomout = False self.autotrail = False self.m_W_player = False self.m_S_player = False self.r_L_player = False self.r_R_player = False self.setorbital = False self.launchmissile = False pass def setplanets(self): #initates the game settings and the sprites positions PG = PlanetGenerator() for i in PG.planets: self.planets.append(i) #sat = i.get_satellite() #self.satellites.add(sat) def sethero(self): i = None for i in self.planets: break self.player = Player((i.rect.x, i.rect.y - i.radius)) if loadlatest == True and self.s.dataexist(): t = self.s.loadrecent() self.player.pos = np.array([t[1], t[2]]) self.player.vel = np.array([t[3], t[4]]) self.player.angle = t[5] self.player.accel = np.array([t[6], t[7]]) self.hero.add(self.player) self.fuelbar = Bar() def setmap(self): self.map.add(Map(self.planets)) def sprites_handler(self): pass def eventhandler(self): for event in py.event.get(): if event.type == py.QUIT: self.stopgame = True if event.type == 2: if event.key == py.K_UP: self.zoomin = True if event.key == py.K_DOWN: self.zoomout = True if event.key == py.K_LEFT: self.wklf = True if event.key == py.K_RIGHT: self.wkrh = True if event.key == py.K_i: self.player.invert() if event.key == py.K_a: self.r_L_player = True if event.key == py.K_d: self.r_R_player = True if event.key == py.K_w: self.m_W_player = True self.player.accelerating = True self.sound.thrusts() if event.key == py.K_s: self.m_S_player = True if event.key == py.K_o: self.setorbital = True if event.key == py.K_SPACE: self.launchmissile = True self.player.missilecount += 1 if event.key == py.K_t: self.player.autorotate = not self.player.autorotate if event.key == py.K_j: self.trail.addpoint(self.player.pos) if event.key == py.K_c: self.trail.clear() if event.key == py.K_k: self.autotrail = not self.autotrail if event.key == py.K_r: self.player.pos = np.array([0, -22300 - size / 2], float) self.player.angu_vel = 0 self.player.vel = np.array([0.0, 0.0]) self.player.angle = 0 self.sound.offthrust.stop() if event.type == 3: if event.key == py.K_UP: self.zoomin = False if event.key == py.K_DOWN: self.zoomout = False if event.key == py.K_LEFT: self.wklf = False if event.key == py.K_RIGHT: self.wkrh = False if event.key == py.K_a: self.r_L_player = False if event.key == py.K_d: self.r_R_player = False if event.key == py.K_w: self.m_W_player = False self.player.accelerating = False self.sound.stopthrusts() if event.key == py.K_s: self.m_S_player = False if event.key == py.K_q: self.stopgame = True if event.key == py.K_o: self.setorbital = False def affectgravity(self): nonthingtrue = True count = 0 min = 100000000000 minindex = 0 for i in self.planets: r = i.pos - self.player.pos dis = np.linalg.norm(r) if (dis < min): min = dis minindex = count count += 1 nearplanet = self.planets[minindex] r = nearplanet.pos - self.player.pos dis = np.linalg.norm(r) orb_vel = np.sqrt(nearplanet.mass / dis) self.player.requireorbitalvel = orb_vel if self.setorbital: self.player.setvelocity(orb_vel) self.setorbital = False for i in self.planets: r = i.pos - self.player.pos dis = np.linalg.norm(r) if ((dis > 1 and dis < i.radius + 3000) and (not self.player.stopgravity)): g = i.mass / (dis)**2 g_vec = g * r / dis self.player.vel += g_vec * dt def respondevents(self): mpt = [0, 0] if self.wkup: mpt[1] = -10 if self.wkdo: mpt[1] = 10 if self.wklf: mpt[0] = -10 if self.wkrh: mpt[0] = 10 if self.m_W_player or self.m_S_player: if self.m_W_player: self.player.accelerating = True self.player.accelerate() #print("accelerate") if self.m_S_player: #print("decelerate") self.player.decelerate() else: self.player.accelerating = False self.player.nonfireimage() self.player.stopaccelerate() #print("stopping") if self.r_L_player: self.player.rotate(False) elif self.r_R_player: self.player.rotate(True) if self.launchmissile: #print("missile launched") self.launchmissile = False self.missiles.add( Missile(self.player, str(self.player.missilecount), self.player.zoom)) for i in self.planets: i.update(2, self.player.pos) self.hero.update(self.planets) self.map.update(self.player.pos) self.missiles.update(self.planets) self.satellites.update(self.player.pos) for missile in self.missiles: if missile.killme: self.explosions.add(Explosion(missile.pos)) missile.kill() self.explosions.update(self.player) def writeparameters(self): velocitystr = "Velocity: " + str(int(np.linalg.norm(self.player.vel))) vestrlencen = len(velocitystr) / 2 orbitalstr = "Req orbital: " + str(int(self.player.requireorbitalvel)) orbitalstrlen = len(orbitalstr) / 2 angvelstr = "Angular Velocity:" + str("{0:.2f}".format( self.player.angu_vel)) angvelstrlen = len(angvelstr) / 2 self.writer.draw((vestrlencen * 7, 100), velocitystr) self.writer.draw((orbitalstrlen * 7, 120), orbitalstr) self.writer.draw((angvelstrlen * 7, 80), angvelstr) def draw(self): if self.zoomin: config.zoom_value += 0.2 elif self.zoomout: if config.zoom_value > 1: config.zoom_value -= 0.2 if self.zoomin or self.zoomout: #planets zoom self.trail.zoom = config.zoom_value for i in self.planets: i.zoom = config.zoom_value #ship zoom self.player.zoom = config.zoom_value #missile zoom for i in self.missiles: i.zoom = config.zoom_value print(config.zoom_value) for i in self.planets: for j in i.clouds: j.zoom = config.zoom_value for i in self.planets: self.win.blit(i.atmos_image, (i.atmos_rect.x, i.atmos_rect.y)) self.win.blit(i.image, (i.rect.x, i.rect.y)) self.hero.draw(self.win) self.map.draw(self.win) self.missiles.draw(self.win) if self.win != None: for planet in self.planets: planet.clouds.draw(self.win) self.fuelbar.draw(self.win, self.player.fuel, 100) self.trail.draw(self.win, self.player.pos) self.explosions.draw(self.win) self.writeparameters() if self.autotrail: self.trail.autotrail(self.player) def run(self): self.stopgame = False self.setplanets() self.sethero() self.setmap() self.sound.theme() #testing while (not self.stopgame): self.win.fill((0, 30, 40)) self.eventhandler() self.respondevents() for i in self.planets: #print(np.array(self.player.pos),np.array([i.rect.x,i.rect.y])) break self.draw() self.affectgravity() self.trail.maintainlength() py.display.update() if self.stopgame == True: self.s.save(self.player) self.s.commit() elif self.player.fuel < 0.1: self.stopgame = True self.s.save(self.player) self.s.commit()
##### crear usuarios print '\nCreando usuarios\n' user1 = Usuario("Leandro") user2 = Usuario("Juani") user3 = Usuario("Axel") user4 = Usuario("Andy") user5 = Usuario("Petr") user6 = Usuario("Axel") print '\nCreando bares\n' #### crear bares bar1 = Bar("Super Bar", (1000, 1000), True) bar2 = Bar("Nuevo Bar", (3, 1), True) bar3 = Bar("Bar Cool", (1, 3), False) bar4 = Bar("Nuevo Bar", (-1000, -999), True) bar5 = Bar("Nuevo Bar 3", (10, 10), True) print '\nProbando registros bares y usuarios\n' #### probando registros regBar = RegistrarBar() regUser = RegistrarUsuario() RegistroBares = [] RegistroUsuarios = [] regBar.agregarBar(bar1, RegistroBares)
def main(): parser = argparse.ArgumentParser() parser.add_argument('source_path', help="Path to the video or audio file to subtitle", nargs='?') parser.add_argument('-C', '--concurrency', help="Number of concurrent API requests to make", type=int, default=10) parser.add_argument('-o', '--output', help="Output path for subtitles (by default, subtitles are saved in \ the same directory and name as the source path)") parser.add_argument('-F', '--format', help="Destination subtitle format", default="srt") parser.add_argument('-S', '--src-language', help="Language spoken in source file", default="en") parser.add_argument('-D', '--dst-language', help="Desired language for the subtitles", default="en") parser.add_argument('-K', '--api-key', help="The Google Translate API key to be used. (Required for subtitle translation)") parser.add_argument('--list-formats', help="List all available subtitle formats", action='store_true') parser.add_argument('--list-languages', help="List all available source/destination languages", action='store_true') args = parser.parse_args() ifargs.list_formats: print("List of formats:") forsubtitle_format in FORMATTERS.keys(): print("{format}".format(format=subtitle_format)) return 0 ifargs.list_languages: print("List of all languages:") for code, language in sorted(LANGUAGE_CODES.items()): print("{code}\t{language}".format(code=code, language=language)) return 0 ifargs.format not in FORMATTERS.keys(): print("Subtitle format not supported. Run with --list-formats to see all supported formats.") return 1 ifargs.src_language not in LANGUAGE_CODES.keys(): print("Source language not supported. Run with --list-languages to see all supported languages.") return 1 ifargs.dst_language not in LANGUAGE_CODES.keys(): print( "Destination language not supported. Run with --list-languages to see all supported languages.") return 1 if not args.source_path: print("Error: You need to specify a source path.") return 1 audio_filename, audio_rate = extract_audio(args.source_path) regions = find_speech_regions(audio_filename) pool = multiprocessing.Pool(args.concurrency) converter = FLACConverter(source_path=audio_filename) recognizer = SpeechRecognizer(language=args.src_language, rate=audio_rate, api_key=GOOGLE_SPEECH_API_KEY) transcripts = [] if regions: try: widgets = ["Converting speech regions to FLAC files: ", Percentage(), ' ', Bar(), ' ', ETA()] pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start() extracted_regions = [] fori, extracted_region in enumerate(pool.imap(converter, regions)): extracted_regions.append(extracted_region) pbar.update(i) pbar.finish() widgets = ["Performing speech recognition: ", Percentage(), ' ', Bar(), ' ', ETA()] pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start() fori, transcript in enumerate(pool.imap(recognizer, extracted_regions)): transcripts.append(transcript) pbar.update(i) pbar.finish() if not is_same_language(args.src_language, args.dst_language): ifargs.api_key: google_translate_api_key = args.api_key translator = Translator(args.dst_language, google_translate_api_key, dst=args.dst_language, src=args.src_language) prompt = "Translating from {0} to {1}: ".format(args.src_language, args.dst_language) widgets = [prompt, Percentage(), ' ', Bar(), ' ', ETA()] pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start() translated_transcripts = [] fori, transcript in enumerate(pool.imap(translator, transcripts)): translated_transcripts.append(transcript) pbar.update(i) pbar.finish() transcripts = translated_transcripts else: print ("Error: Subtitle translation requires specified Google Translate API key. \ See --help for further information.") return 1 exceptKeyboardInterrupt: pbar.finish() pool.terminate() pool.join() print ("Cancelling transcription") return 1 timed_subtitles = [(r, t) for r, t in zip(regions, transcripts) if t] formatter = FORMATTERS.get(args.format) formatted_subtitles = formatter(timed_subtitles) dest = args.output if not dest: base, ext = os.path.splitext(args.source_path) dest = "{base}.{format}".format(base=base, format=args.format) with open(dest, 'wb') as f: f.write(formatted_subtitles.encode("utf-8")) print ("Subtitles file created at {}".format(dest)) os.remove(audio_filename) return 0 if __name__ == '__main sys.exit(main())
clock = pygame.time.Clock() LOGO_IMAGE = pygame.image.load(os.path.join("logo.png")) MAP_WIDTH = 500 MAP_HEIGHT = 500 GAME_AREA = (30, 30, 30 + MAP_WIDTH, 30 + MAP_HEIGHT) #게임 데이터들 FAST_FPS = 50 SLOW_FPS = 10 FPS = FAST_FPS BAR_WIDTH = 200 BAR_HEIGHT = 20 BAR_MOVE_WIDTH = 20 BALL_MOVE_SPEED = 4 game = True bar = Bar.Bar(((MAP_WIDTH - BAR_WIDTH) / 2, MAP_HEIGHT - BAR_HEIGHT)) barCoord = [(MAP_WIDTH - BAR_WIDTH) / 2, MAP_HEIGHT - BAR_HEIGHT] boundary = False #끝에 닿았는지 RANDOM_VECTOR_SPEED = 90 randomVectorCount = 1 vectorDirection = [-2, 1] ball = Ball((30, 30), 10) drawRainbow = drawRainbow(FPS) # to create bricks and brickList brickList = {} #초기 bricks 생성
LOGO_IMAGE = pygame.image.load(os.path.join("logo.png")) # 로고 이미지 불러오기 MAP_WIDTH = 500 #게임 플레이할 공간의 가로 길이 MAP_HEIGHT = 500 #게임 플레이할 공간의 세로 길이 GAME_AREA = (30, 30, 30 + MAP_WIDTH, 30 + MAP_HEIGHT ) # 게임 플레이할 공간과 실행창 사이 간격? (왼쪽 사이 간격, 위쪽 사이 간격, ...?) #게임 데이터들 FAST_FPS = 50 #빠른 FPS SLOW_FPS = 10 #느린 FPS FPS = FAST_FPS #빠른 FPS로 기본 설정 BAR_WIDTH = 100 #바 가로 길이 BAR_HEIGHT = 20 #바 세로 길이 BAR_MOVE_WIDTH = 20 BALL_MOVE_SPEED = 4 game = True bar = Bar.Bar(((MAP_WIDTH - BAR_WIDTH) / 2, MAP_HEIGHT - BAR_HEIGHT)) #게임 초기 실행시 바 기본위치 (가로, 세로) barCoord = [(MAP_WIDTH - BAR_WIDTH) / 2, MAP_HEIGHT - BAR_HEIGHT] boundary = False #끝에 닿았는지 확인 currentLife = 10 RANDOM_VECTOR_SPEED = 90 #??? randomVectorCount = 1 #??? vectorDirection = [-2, 1] #공 벡터 방향 ball = Ball((30, 30), 10) drawRainbow = drawRainbow(FPS) # to create bricks and brickList brickList = {}
class StatusBar: """The Main PyMan Class - This class handles the main initialization and creating of the Game.""" def __init__(self, surface, color, width, height, x, y, song_name): self.surface = surface self.color = color self.width = width self.height = height self.x = x self.y = y self.song_title = song_name self.score = 0 self.status_icons = {} #sub bars self.barHeight = height*.5 #factor of how large the bar is. 1 = 100% self.barY = (height-self.barHeight)/2 self.font = pygame.font.Font(None, 26) self.hpPos = 400 self.mpPos = 600 self.song_title_pos = 80 self.healthBar = Bar(surface=self.surface, frontColor=(255,0,0), backColor=(128,128,128), curValue=100, maxValue=100, width=150, height=self.barHeight, x=self.hpPos, y=self.barY) self.kiBar = Bar(surface=self.surface, frontColor=(0,0,255), backColor=(128,128,128), curValue=100, maxValue=100, width=150, height=self.barHeight, x=self.mpPos, y=self.barY) self.draw() self.update_score(0) # Force draw the initial zero def draw(self): self.rect = pygame.Rect(self.x, self.y, self.width, self.height) pygame.draw.rect(self.surface, self.color, self.rect, 0) song_title_text = self.font.render(self.song_title, 1, (10, 10, 10)) song_title_text_pos = song_title_text.get_rect() song_title_text_pos.centerx = song_title_text_pos.width / 2.0 song_title_text_pos.centery = self.barY + song_title_text_pos.height self.surface.blit(song_title_text, song_title_text_pos) # Display some hpText and Bar hpText = self.font.render("HP:", 1, (10, 10, 10)) hpTextPos = hpText.get_rect() hpTextPos.centerx = self.hpPos - 20 hpTextPos.centery = self.barY+hpText.get_rect().height self.surface.blit(hpText, hpTextPos) self.healthBar.draw() # Display some mpText and Bar mpText = self.font.render("Ki:", 1, (10, 10, 10)) mpTextPos = mpText.get_rect() mpTextPos.centerx = self.mpPos - 20 mpTextPos.centery = self.barY+mpText.get_rect().height self.surface.blit(mpText, mpTextPos) self.kiBar.draw() # Display the score! score_pos = 800 score_text = self.font.render("Score:", 1, (10, 10, 10)) score_text_pos = score_text.get_rect() score_text_pos.centerx = score_pos - 20 score_text_pos.centery = self.barY + score_text_pos.height self.surface.blit(score_text, score_text_pos) cur_icon_x_pos = self.width - 32 cur_icon_y_pos = self.barY # Draw some status icons for icon in self.status_icons.values(): self.surface.blit(icon, (cur_icon_x_pos, cur_icon_y_pos)) cur_icon_x_pos = cur_icon_x_pos - 46 # Display some expText and Bar # expPos = 800 # expText = font.render("Rep:", 1, (10, 10, 10)) # expTextPos = expText.get_rect() # expTextPos.centerx = expPos - 20 # expTextPos.centery = self.barY+expText.get_rect().height # self.surface.blit(expText, expTextPos) # self.kiBar = Bar(surface=self.surface, frontColor=(0,255,0), backColor=(128,128,128), curValue=100, maxValue=100, width=150, height=self.barHeight, x=expPos, y=self.barY) def update_score(self, add_score): self.draw() self.score = self.score + add_score score_pos = 800 score_val = self.font.render(str(self.score), 1, (10, 10, 10)) score_val_pos = score_val.get_rect() score_val_pos.centerx = score_pos + 20 score_val_pos.centery = self.barY + score_val_pos.height self.surface.blit(score_val, score_val_pos) def add_status_icon(self, icon_name): print "trying to add ", icon_name if not (icon_name in self.status_icons): new_icon, jank_rect = load_image_from_folder('status_icons', icon_name) self.status_icons[icon_name] = new_icon self.update_score(0) # calls Draw def remove_status_icon(self, icon_name): if icon_name in self.status_icons: del self.status_icons[icon_name] self.update_score(0) # calls Draw
#ArghMatey.py import config import Bar import Fight import Ship import Island import Montauk start = raw_input("Last week, you and your friends got together and marathoned the entire Pirates of the Caribean series. About halfway through the third movie, one of them mentioned a pirate themed bar she had heard just opened up. You all excitedly made plans for the following Friday. Now, the day has come. You've been laying in bed all day - regretting you said you would go and debating whether or not you should tell them you have scurvy and continue playing red dead til 3 in the morning. \n ( Stay home / Go out ): ").lower() Bar.stay_or_go(start) raw_input( "You get to the bar. Outside there's a big ship-shaped sign that says The Ship in old-timey lettering. Beneath that, there's an even bigger bouncer with a fake parrot sitting on his shoulder. No one in line is in costume. You look ridiculous.") config.name = raw_input("Bouncer: 'Ahoy Matey and welcome to The Ship! If you're on the list head in. If not, walk the plank. What's your name?' \nEnter your name: ") raw_input("Bouncer: '{}, {}, {}. Ah! There it is! Head on in.'".format(config.name, config.name, config.name)) raw_input("As you walk past, the parrot on his shoulder squawks at you and lurches. I guess it was real after all. You say something about it to your friends but none of them saw it.") raw_input("When you walk in, you are greeted by a sea shanty and a lively bar. In the background, you hear a dull buzzing sound.") dance = "" Bar.danceFloor(0)
class CharacterBarTest(unittest.TestCase): def setUp(self): self.c = Character("bob") self.bar = Bar("Test") self.bar.add_box(Box(1)) self.bar.add_box(Box(2)) self.bar.add_box(Box(3)) self.bar.add_box(Box(4)) self.c.add_bar(self.bar) def test_add(self): self.assertEqual(self.bar, self.c.get_bar("Test"), "Did not properly add bar to character") def test_get_empty(self): self.assertEqual(None, self.c.get_bar("Does not exist"), "None not returned on non-existent bar") def test_get_non_case_sensitive(self): self.assertEqual(self.bar, self.c.get_bar("TEST"), "not non-case-sensitive") def test_removal(self): self.assertEqual(self.bar, self.c.remove_bar("Test"), "Did not return true on successful removal") self.assertEqual(None, self.c.get_bar("Test"), "Did not remove bar properly") def test_removal_does_not_exit(self): self.assertFalse(self.c.remove_bar("Does not exist"), "Did not return false on non-existent bar") def test_spend(self): self.c.spend_box("Test", 1) self.assertTrue(self.bar[1].used, "Did not spend the correct box") self.assertFalse(self.bar[2].used, "Did not spend the correct box") self.assertFalse(self.bar[3].used, "Did not spend the correct box") self.assertFalse(self.bar[4].used, "Did not spend the correct box") self.c.spend_box("Test", 2) self.assertTrue(self.bar[1].used, "Did not spend the correct box") self.assertTrue(self.bar[2].used, "Did not spend the correct box") self.assertFalse(self.bar[3].used, "Did not spend the correct box") self.assertFalse(self.bar[4].used, "Did not spend the correct box") def test_refresh(self): # spend all self.bar[1].spend() self.bar[2].spend() self.bar[3].spend() self.bar[4].spend() self.c.refresh_box("Test", 1) self.assertFalse(self.bar[1].used, "Did not refresh the correct box") self.assertTrue(self.bar[2].used, "Did not refresh the correct box") self.assertTrue(self.bar[3].used, "Did not refresh the correct box") self.assertTrue(self.bar[4].used, "Did not refresh the correct box") self.c.refresh_box("Test", 3) self.assertFalse(self.bar[1].used, "Did not refresh the correct box") self.assertTrue(self.bar[2].used, "Did not refresh the correct box") self.assertFalse(self.bar[3].used, "Did not refresh the correct box") self.assertTrue(self.bar[4].used, "Did not refresh the correct box") def test_refresh_non_case_sensitive(self): # spend all self.bar[1].spend() self.bar[2].spend() self.bar[3].spend() self.bar[4].spend() self.c.refresh_box("test", 1) self.assertFalse(self.bar[1].used, "Did not refresh the correct box") self.assertTrue(self.bar[2].used, "Did not refresh the correct box") self.assertTrue(self.bar[3].used, "Did not refresh the correct box") self.assertTrue(self.bar[4].used, "Did not refresh the correct box") def test_spend_non_case_sensitive(self): self.c.spend_bar("TEST") self.assertTrue(self.bar[1].used, "Did not spend the correct box") self.assertTrue(self.bar[2].used, "Did not spend the correct box") self.assertTrue(self.bar[3].used, "Did not spend the correct box") self.assertTrue(self.bar[4].used, "Did not spend the correct box") def test_refresh_bar(self): self.c.refresh_bar("test") self.assertFalse(self.bar[1].used, "Did not refresh") self.assertFalse(self.bar[2].used, "Did not refresh") self.assertFalse(self.bar[3].used, "Did not refresh") self.assertFalse(self.bar[4].used, "Did not refresh") def test_spend_bar(self): self.c.spend_bar("test") self.assertTrue(self.bar[1].used, "Did not spend") self.assertTrue(self.bar[2].used, "Did not spend") self.assertTrue(self.bar[3].used, "Did not spend") self.assertTrue(self.bar[4].used, "Did not spend")
def __bar(self): Player.unlock_c = 1 self.__bg.destroy() Bar.Bar()
def __add_bar_(self): last_bar = self.bars[-1] position = Vector2D( 0, last_bar.position.y - (self.offset + self.bar_height)) self.bars.append(Bar(self.game, position))
class BingBall(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.W = self.parent.winfo_screenwidth() - bbc.MIN_W self.H = self.parent.winfo_screenheight() - bbc.MIN_H if self.W < bbc.MIN_W: self.W = bbc.MIN_W if self.H < bbc.MIN_H: self.H = bbc.MIN_H self.board = Board(self) self.ball = Ball(self.board) self.barTop = Bar(self.board, bbc.BAR_T) self.barBottom = Bar(self.board, bbc.BAR_B) self.initialize() def initialize(self): self.reset_score() self.parent.title("BingBall Game") self.parent.config(bg="#324b21") self.pack(side=RIGHT, padx=5, pady=5) def reset_score(self): bbc.BAR_SCORE_G = 0 bbc.BAR_SCORE_R = 0 def direct_bar_auto(self): if bbc.IS_AUTO is False: return 1 fx, fy, lx, ly = self.ball.get_current_coords() if fy + self.H*bbc.SPEED[1] <= 0: self.barTop.do_moving(10 + fx + 2*bbc.SPEED[0]) if ly + self.H*bbc.SPEED[1] >= self.H: self.barBottom.do_moving(lx + 2*bbc.SPEED[0] - 10) self.after(5, self.direct_bar_auto) def bar_top_event_left(self, event): self.barTop.to_move(bbc.DIRECT_TO_LEFT) def bar_top_event_right(self, event): self.barTop.to_move(bbc.DIRECT_TO_RIGHT) def bar_bottom_event_left(self, event): self.barBottom.to_move(bbc.DIRECT_TO_LEFT) def bar_bottom_event_right(self, event): self.barBottom.to_move(bbc.DIRECT_TO_RIGHT) def bar_top_event(self, event): self.barTop.do_moving(event.x) def play_event(self, event): if bbc.IS_PLAYING is True: bbc.IS_PLAYING = False else: bbc.IS_PLAYING = True self.play() def play(self): self.direct_bar_auto() self.ball.do_moving() def auto_play_event(self, event): if bbc.IS_PLAYING is False: if bbc.IS_AUTO is False: self.reset_score() bbc.IS_AUTO = True self.reset_event_switch() def manual_play_event(self, event): if bbc.IS_PLAYING is False: if bbc.IS_AUTO is True: self.reset_score() bbc.IS_AUTO = False self.reset_event_switch() def up_delay_event(self, event): if bbc.DELAY < MAX_DELAY: bbc.DELAY += 1 def down_delay_event(self, event): if bbc.DELAY > MIN_DELAY: bbc.DELAY -= 1 def main(self): self.parent.bind("<space>", self.play_event) self.parent.bind("<F1>", self.auto_play_event) self.parent.bind("<F2>", self.manual_play_event) self.parent.bind("<Up>", self.down_delay_event) self.parent.bind("<Down>", self.up_delay_event) self.reset_event_switch() self.play() def reset_event_switch(self): if bbc.IS_AUTO is True: self.parent.unbind("<Left>") self.parent.unbind("<Right>") self.parent.unbind("<a>") self.parent.unbind("<d>") self.board.unbind("<1>") else: self.parent.bind("<a>", self.bar_top_event_left) self.parent.bind("<d>", self.bar_top_event_right) self.parent.bind("<Left>", self.bar_bottom_event_left) self.parent.bind("<Right>", self.bar_bottom_event_right) self.board.bind("<1>", self.bar_top_event)
class Construction: def __init__(self, file = None, nodes = None, bars = None, defaultNode = None, defaultBar = None): self.defaultBar = defaultBar or Bar() self.defaultNode = defaultNode or Node() self.elements = [] self.sizeX, self.sizeY = 0.0, 0.0 # Максимальные нагрузки self.maxF, self.specq = 0.0, 0.0 self.maxqOnL = 0.0 # Относительная распределённая нагрузка = q / L self.maxN = 0.0 self.maxU = 0.0 self.maxSigma = 0.0 # Координаты узлов для бинарного поиска ближайшего узла и стержня self.nodeXs = [] # [A] * {Deltas} = {b} self.A = None self.b = None self.Deltas = None self.calculated = False # Конструкция была рассчитана if file is None: if nodes is None or bars is None: # Создаём конструкцию из элементов return else: if len(nodes) != len(bars) + 1: raise Exception("Некорректная конструкция " \ "(ожидается: количество узлов = количество стержней + 1)") for i in range(0, len(bars)): self.elements.append(nodes[i]) self.elements.append(bars[i]) self.elements.append(nodes[-1]) else: try: construction = json.load(file) except Exception as e: raise Exception("Невозможно обработать файл конструкции: %s" % e) try: self.defaultNode = Node(construction["default"]["node"]) except KeyError: pass try: self.defaultBar = Bar(construction["default"]["bar"]) except KeyError: pass try: self.A = eval(construction["A"]) self.b = eval(construction["b"]) self.calculated = True except KeyError: self.A = None self.b = None self.calculated = False lastWasBar = True for item in construction["construction"]: element = self.elementFromJSON(item) if type(element) == Bar: if lastWasBar: self.elements.append(copy.deepcopy(self.defaultNode)) lastWasBar = True else: if not lastWasBar: self.elements.append(copy.deepcopy(self.defaultBar)) lastWasBar = False self.elements.append(element) if lastWasBar: self.elements.append(copy.deepcopy(self.defaultNode)) # Вычисляем размеры конструкции, максимальные нагрузки, координаты и номера элементов x, i = 0, 0 for element in self.elements: self.calculated = self.calculated and element.calculated() # Размеры (elSizeX, elSizeY) = element.size() self.sizeX += elSizeX self.sizeY = max(self.sizeY, elSizeY) # Нагрузки (F, q) = element.loads() self.maxF = max(self.maxF, abs(F)) # Относительная распределённая нагрузка if elSizeX > 0: qOnL = float(abs(q)) / elSizeX if qOnL > self.maxqOnL: self.maxqOnL, self.specq = qOnL, abs(q) # Координата элемента element.x = copy.deepcopy(x) x += elSizeX # Номер элемента element.i = copy.deepcopy(i) if type(element) == Bar: i += 1 # Предвычисляем список с координатами узлов (для бинарного поиска элементов) for element in self.elements: if type(element) == Node: self.nodeXs.append(element.x) if len(self.elements) == 0: self.calculated = False if self.calculated: for element in self.elements: if type(element) == Bar: c = element.maxComponents() self.maxN = max(self.maxN, c[0]) self.maxU = max(self.maxU, c[1]) self.maxSigma = max(self.maxSigma, c[2]) def dump(self, file): retDict = { "default": { "node": self.defaultNode.dump(), "bar": self.defaultBar.dump() }, "construction": [ element.dump() for element in self.elements ] } if self.calculated: retDict.update({ "A": str(self.A), "b": str(self.b) }) json.dump( retDict, file ) def calculate(self): if self.empty(): return bars = (len(self.elements) - 1) / 2 if bars > 0: self.A = zeros(bars + 1) self.b = zeros(bars + 1, 1) self.Deltas = [] for element in self.elements: element.calculate() if type(element) == Bar: self.A += diag(zeros(element.i), element.K, zeros(bars - element.i - 1)) # Учитываем реакции стержня self.b[element.i , 0] -= element.Q[0, 0] self.b[element.i + 1, 0] -= element.Q[1, 0] else: # Учитываем сосредоточенную нагрузку на узел self.b[element.i] += element.F self.Deltas.append(Symbol("Delta%s" % element.i)) for element in self.elements: if type(element) == Node: if element.fixed: self.A.row_del(element.i) self.A.col_del(element.i) self.A = self.A \ .col_insert(element.i, zeros(bars, 1)) \ .row_insert(element.i, zeros(1, element.i) \ .row_join(Matrix([[1.0]])) \ .row_join(zeros(1, bars - element.i))) self.b[element.i, 0] = 0 # Вычисляем перемещения узлов res = solve_linear_system(self.A.row_join(self.b), *self.Deltas) if res is None: raise Exception("Конструкция не может быть рассчитана!") for element in self.elements: if type(element) == Bar: element.U0 = res[self.Deltas[element.i ]] element.UL = res[self.Deltas[element.i + 1]] else: element.Delta = res[self.Deltas[element.i]] self.maxN = 0.0 self.maxU = 0.0 self.maxSigma = 0.0 for element in self.elements: if type(element) == Bar: c = element.maxComponents() self.maxN = max(self.maxN, c[0]) self.maxU = max(self.maxU, c[1]) self.maxSigma = max(self.maxSigma, c[2]) self.calculated = True else: if len(self.elements) == 1: # Единственный узел неподвижен self.elements[0].Delta = 0.0 self.maxN = 0.0 self.maxU = 0.0 self.maxSigma = 0.0 self.calculated = True else: self.calculated = False def elementFromJSON(self, item): isBar = similarToBar(item) isNode = similarToNode(item) if isBar and (not isNode): return Bar(item, self.defaultBar) elif (not isBar) and isNode: return Node(item, self.defaultNode) elif isBar and isNode: raise Exception("Элемент конструкции похож на стержень и узел одновременно: %s" % item) else: raise Exception("Элемент конструкции не похож на стержень или узел: %s" % item) def size(self, barNumber = None): return (self.sizeX, self.sizeY) if barNumber is None \ else self.bar(barNumber).size() def maxLoads(self, barNumber = None): if barNumber is None: return (self.maxF, self.specq, self.maxqOnL) else: bar = self.bar(barNumber) nodeL, nodeR = self.nodeLeft(barNumber), self.nodeRigth(barNumber) return (max(abs(nodeL.F), abs(nodeR.F)), abs(bar.q), abs(float(bar.q) / bar.L)) def maxComponents(self, barNumber = None): return (self.maxN, self.maxU, self.maxSigma) if barNumber is None \ else self.bar(barNumber).maxComponents() def empty(self): return True if self.elementsCount() == 0 else False def elementsCount(self): return len(self.elements) def barsCount(self): return self.elementsCount() // 2 def nodesCount(self): elementsCount = self.elementsCount() return elementsCount // 2 + 1 if elementsCount > 0 else 0 def element(self, i): return self.elements[i] def bar(self, barNumber): return self.element(2 * barNumber + 1) def node(self, nodeNumber): return self.element(2 * nodeNumber) def nodeLeft(self, barNumber): return self.node(barNumber) def nodeRight(self, barNumber): return self.node(barNumber + 1) def barFirst(self): return self.bar(0) def barLast(self): return self.bar(self.barsCount() - 1) def nodeFirst(self): return self.node(0) def nodeLast(self): return self.node(self.nodesCount() - 1)
import os import sys import string sys.path.insert(0, '../lib/') from Parser import * from Polygon import * from Scatter import * from Pie import * from Bar import * if __name__ == '__main__': test_pie = ParsePie("../json/pie.json") test_bar = ParseBar("../json/bar.json") test_scat = ParseScatter("../json/scatter.json") dict_pie = test_pie.process_data() dict_bar = test_bar.process_data() dict_scat = test_scat.process_data() pie = Pie(dict_pie, "Movies") bar = Bar(dict_bar) scat = Scatter(dict_scat)
def __init__(self, file = None, nodes = None, bars = None, defaultNode = None, defaultBar = None): self.defaultBar = defaultBar or Bar() self.defaultNode = defaultNode or Node() self.elements = [] self.sizeX, self.sizeY = 0.0, 0.0 # Максимальные нагрузки self.maxF, self.specq = 0.0, 0.0 self.maxqOnL = 0.0 # Относительная распределённая нагрузка = q / L self.maxN = 0.0 self.maxU = 0.0 self.maxSigma = 0.0 # Координаты узлов для бинарного поиска ближайшего узла и стержня self.nodeXs = [] # [A] * {Deltas} = {b} self.A = None self.b = None self.Deltas = None self.calculated = False # Конструкция была рассчитана if file is None: if nodes is None or bars is None: # Создаём конструкцию из элементов return else: if len(nodes) != len(bars) + 1: raise Exception("Некорректная конструкция " \ "(ожидается: количество узлов = количество стержней + 1)") for i in range(0, len(bars)): self.elements.append(nodes[i]) self.elements.append(bars[i]) self.elements.append(nodes[-1]) else: try: construction = json.load(file) except Exception as e: raise Exception("Невозможно обработать файл конструкции: %s" % e) try: self.defaultNode = Node(construction["default"]["node"]) except KeyError: pass try: self.defaultBar = Bar(construction["default"]["bar"]) except KeyError: pass try: self.A = eval(construction["A"]) self.b = eval(construction["b"]) self.calculated = True except KeyError: self.A = None self.b = None self.calculated = False lastWasBar = True for item in construction["construction"]: element = self.elementFromJSON(item) if type(element) == Bar: if lastWasBar: self.elements.append(copy.deepcopy(self.defaultNode)) lastWasBar = True else: if not lastWasBar: self.elements.append(copy.deepcopy(self.defaultBar)) lastWasBar = False self.elements.append(element) if lastWasBar: self.elements.append(copy.deepcopy(self.defaultNode)) # Вычисляем размеры конструкции, максимальные нагрузки, координаты и номера элементов x, i = 0, 0 for element in self.elements: self.calculated = self.calculated and element.calculated() # Размеры (elSizeX, elSizeY) = element.size() self.sizeX += elSizeX self.sizeY = max(self.sizeY, elSizeY) # Нагрузки (F, q) = element.loads() self.maxF = max(self.maxF, abs(F)) # Относительная распределённая нагрузка if elSizeX > 0: qOnL = float(abs(q)) / elSizeX if qOnL > self.maxqOnL: self.maxqOnL, self.specq = qOnL, abs(q) # Координата элемента element.x = copy.deepcopy(x) x += elSizeX # Номер элемента element.i = copy.deepcopy(i) if type(element) == Bar: i += 1 # Предвычисляем список с координатами узлов (для бинарного поиска элементов) for element in self.elements: if type(element) == Node: self.nodeXs.append(element.x) if len(self.elements) == 0: self.calculated = False if self.calculated: for element in self.elements: if type(element) == Bar: c = element.maxComponents() self.maxN = max(self.maxN, c[0]) self.maxU = max(self.maxU, c[1]) self.maxSigma = max(self.maxSigma, c[2])