def waitForClick(): Engine.flipOnce() cont = True while(cont): for evt in pygame.event.get(): if evt.type is pygame.MOUSEBUTTONDOWN: cont = False
def __init__(self): # Storing the engines of this car self.__leftengine = Engine('A') self.__rightengine = Engine('B') self.__engines = [self.__leftengine,self.__rightengine] # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines)
def execute(self, s): if self.isUsable(): # perform altering commands self.alter() Engine.getInstance().show(self.description) else: Engine.getInstance().show("You can not do that") raise Exception
def shutdown() : global addToQueue, queueIsEmpty, clearQueue msg("SMDS Shutting down.") Engine.shutdown() Dispatch.shutdown() if theCache : theCache.close() addToQueue = notInit queueIsEmpty = notInit clearQueue = notInit
def SelectCf2(node): player = Engine.GetCurrentPlayer() player.SetShipName("cf2") uiManager = Engine.GetUIManager() uiManager.GetUIObjectByName( "ssMenuC").GetChildren()[0].GetChildren()[0].SetVisible(True) uiManager.GetUIObjectByName( "ssMenuC").GetChildren()[0].GetChildren()[1].SetVisible(False) uiManager.GetUIObjectByName("cf1Info").SetVisible(False) uiManager.GetUIObjectByName("cf2Info").SetVisible(True)
def init_joystick(self): if Engine.joystick_avail(): joystick = Engine.get_joystick() joystick.init() self.joystick = joystick self.joystick_name = joystick.get_name() else: self.joystick = None self.joystick_name = None print(self.joystick_name)
def execute(self, s): engine = Engine.getInstance() availablePaths = Engine.getScenario().getPaths() # paths that can currently be taken # search for an item specified for path in availablePaths: if path in s: engine.setScenario(path) return engine.show("No such path exists")
def updateEvents(): #print("here") for evt in pygame.event.get(): if evt.type is pygame.QUIT: #Engine.stop() if g.multithreading: Engine.stop() pygame.quit() sys.exit() #print(pygame.event.event_name(evt.type)) EventList[pygame.event.event_name(evt.type)](evt)
def __init__(self): self.__input_going = False self.__input_thread = None self.__command_thread = None self.__command_going = False self.__leftengine = Engine('A') self.__rightengine = Engine('B') self.__distanceLego = MindstormSensor('1','ULTRASONIC_CONT') self.__brickpi = BrickPi_Thread([self.__leftengine,self.__rightengine],[self.__distanceLego]) self.__gearratio = 1./1. self.__perimeter = 2*math.pi*2.758 self.__commands = ['F','S','L','R','B','V','E']
def build_units(self, units): for unit in units: if unit.position: pos = unit.position[0] * self.scale_factor, unit.position[1] * self.scale_factor if unit.team == 'player': self.pin_surf.blit(Engine.subsurface(self.minimap_units, (0, 0, self.scale_factor, self.scale_factor)), pos) elif unit.team == 'enemy': self.pin_surf.blit(Engine.subsurface(self.minimap_units, (self.scale_factor*1, 0, self.scale_factor, self.scale_factor)), pos) elif unit.team == 'other': self.pin_surf.blit(Engine.subsurface(self.minimap_units, (self.scale_factor*2, 0, self.scale_factor, self.scale_factor)), pos) else: self.pin_surf.blit(Engine.subsurface(self.minimap_units, (self.scale_factor*3, 0, self.scale_factor, self.scale_factor)), pos)
def main(): # TODO arg parsing # TODO options other than just running; e.g. show stats item = sys.argv[1] engine = Engine() # TODO exit condition # TODO gui while True: engine.run()
def __init__(self, klass, gender, team, position): self.standspritesName = team + klass + gender # Ex: EnemyMercenaryM self.movespritesName = team + klass + gender + '_move' # Ex: EnemyMercenaryM_move self.position = position # Describes the actual position of the sprite self.new_position = position # Describe where the sprite wants to go self.isMoving = False self.loadSprites() # Counters self.moveSpriteCounter = 0 self.lastUpdate = Engine.get_time() self.last_move_update = Engine.get_time()
def test4(): chessboard = ChessBoard() chessboard.init_board() engine = Engine(chessboard) #创建chessMan对象 并写入棋子颜色 chessman = ChessMan() chessman.set_color('x') input = '13,b' engine.parse_uesr_input(input, chessman) #把该棋子对象放置到棋盘上 chessboard.set_chessman(chessman) #打印棋盘 chessboard.print_board()
def test3(): chessboard = ChessBoard() chessboard.init_board() #创建Engine对象 engine = Engine(chessboard) #创建chessMan对象 并写入棋子颜色 chessman = ChessMan() chessman.set_color('o') engine.computer_go(chessman) #方法中填入位置 #把该棋子对象放置到棋盘上 chessboard.set_chessman(chessman) #打印棋盘 chessboard.print_board()
def loadSprites(self): if not self.sprites_loaded_flag: self.sprites_loaded_flag = True # Handle grabbing normal sprites self.map_image = Engine.image_load(self.mapfilename, convert=True) Engine.set_colorkey(self.map_image, COLORKEY, rleaccel=True) # Auto-tiles auto_loc = self.levelfolder + '/Autotiles/' self.autotile_frame = 0 if os.path.exists(auto_loc): files = sorted([ fp for fp in os.listdir(auto_loc) if fp.startswith('autotile') and fp.endswith('.png') ], key=lambda x: int(x[8:-4])) imageList = [ Engine.image_load(auto_loc + image, convert=True) for image in files ] for image in imageList: Engine.set_colorkey(image, COLORKEY, rleaccel=True) self.autotiles = imageList else: self.autotiles = [] # Loose Tile Sprites lts_loc = self.levelfolder + '/LooseTileSprites/' if os.path.exists(lts_loc): itemnameList = [ image[:-4] for image in os.listdir(lts_loc) if image.endswith('.png') ] imageList = [ Engine.image_load(lts_loc + image, convert=True) for image in os.listdir(lts_loc) if image.endswith('.png') ] for image in imageList: Engine.set_colorkey(image, COLORKEY, rleaccel=True) self.loose_tile_sprites = dict(zip(itemnameList, imageList)) else: self.loose_tile_sprites = {} # Re-add escape highlights if necessary for position, tile_values in self.tile_info_dict.iteritems(): if "Escape" in tile_values or "Arrive" in tile_values: self.escape_highlights[position] = CustomObjects.Highlight( GC.IMAGESDICT["YellowHighlight"]) if "Formation" in tile_values: self.formation_highlights[ position] = CustomObjects.Highlight( GC.IMAGESDICT["BlueHighlight"]) # Re-add associated status sprites for position, value in self.tile_info_dict.iteritems(): if 'Status' in value: for status in value['Status']: status.loadSprites()
def update(self, gameStateObj=None): currentTime = Engine.get_time() if self.on and currentTime > self.start_time: # If this animation has every frame's count defined if self.set_timing: num_frames = self.set_timing[self.frameCount] # If you get a -1 on set timing, switch to blend tint while num_frames < 0: self.tint = not self.tint self.frameCount += 1 num_frames = self.set_timing[self.frameCount] self.timing_count += 1 if self.timing_count >= num_frames: self.timing_count = 0 self.frameCount += 1 if self.frameCount >= self.total_num_frames: if self.loop: self.frameCount = 0 elif self.hold: self.frameCount = self.total_num_frames - 1 else: if gameStateObj and self in gameStateObj.allanimations: gameStateObj.allanimations.remove(self) return True if self.frameCount >= 0: rect = (self.frameCount % self.frame_x * self.indiv_width, self.frameCount // self.frame_x * self.indiv_height, self.indiv_width, self.indiv_height) self.image = Engine.subsurface(self.sprite, rect) # Otherwise elif currentTime - self.lastUpdate > self.animation_speed: self.frameCount += int((currentTime - self.lastUpdate) // self.animation_speed) # 1 self.lastUpdate = currentTime if self.frameCount >= self.total_num_frames: if self.loop: # Reset framecount self.frameCount = 0 elif self.hold: self.frameCount = self.total_num_frames - 1 # Hold on last frame else: if gameStateObj and self in gameStateObj.allanimations: gameStateObj.allanimations.remove(self) return True if self.frameCount >= 0: rect = (self.frameCount % self.frame_x * self.indiv_width, self.frameCount // self.frame_x * self.indiv_height, self.indiv_width, self.indiv_height) self.image = Engine.subsurface(self.sprite, rect)
def draw_hp(self, surf, gameStateObj): current_time = Engine.get_time() if self.transition_state == 'normal': # print('draw_hp') x, y = self.unit.position left = x * GC.TILEWIDTH + self.spriteOffset[0] top = y * GC.TILEHEIGHT + self.spriteOffset[1] # Health Bar if not self.unit.isDying: if (cf.OPTIONS['HP Map Team'] == 'All') or \ (cf.OPTIONS['HP Map Team'] == 'Ally' and self.unit.team in ['player', 'other']) or \ (cf.OPTIONS['HP Map Team'] == 'Enemy' and self.unit.team.startswith('enemy')): if (cf.OPTIONS['HP Map Cull'] == 'All') or \ (cf.OPTIONS['HP Map Cull'] == 'Wounded' and (self.unit.currenthp < self.unit.stats['HP'] or self.current_cut_off != 13)): health_outline = GC.IMAGESDICT['Map_Health_Outline'] health_bar = GC.IMAGESDICT['Map_Health_Bar'] if(self.unit.currenthp >= int(self.unit.stats['HP'])): cut_off = 13 elif self.unit.currenthp <= 0: cut_off = 0 else: cut_off = int((self.unit.currenthp/float(self.unit.stats['HP']))*12) + 1 if gameStateObj.combatInstance and self.unit in gameStateObj.combatInstance.health_bars: self.current_cut_off = int(min(float(gameStateObj.combatInstance.health_bars[self.unit].true_hp)/self.unit.stats['HP'], 1)*13) else: dt = current_time - self.lastHPUpdate if dt > 50: self.lastHPUpdate = current_time if self.current_cut_off < cut_off: self.current_cut_off += int(dt/50) self.current_cut_off = min(cut_off, self.current_cut_off) elif self.current_cut_off > cut_off: self.current_cut_off -= int(dt/50) self.current_cut_off = max(cut_off, self.current_cut_off) surf.blit(health_outline, (left, top+13)) health_bar = Engine.subsurface(health_bar, (0, 0, self.current_cut_off, 1)) surf.blit(health_bar, (left+1, top+14)) # Extra Icons # Essentially an every 132 millisecond timer if 'Boss' in self.unit.tags and self.image_state in ('gray', 'passive') and int((current_time%450)//150) in (1, 2): bossIcon = GC.ICONDICT['BossIcon'] surf.blit(bossIcon, (left - 8, top - 8)) if self.unit.TRV: if gameStateObj.get_unit_from_id(self.unit.TRV).team == 'player': rescueIcon = GC.ICONDICT['BlueRescueIcon'] else: # self.TRV.team == 'other': rescueIcon = GC.ICONDICT['GreenRescueIcon'] topleft = (left - max(0, (rescueIcon.get_width() - 16)//2), top - max(0, (rescueIcon.get_height() - 16)//2)) surf.blit(rescueIcon, topleft)
def mouseClicked(): global isPlaying, menu, play_mode, curr_song, score, play_list if menu: isPlaying = True play_list = [random.randint(0, 3)] curr_song = 0 play_mode = False score = 0 menu = False isPlaying = False else: if play_mode: if mouseX < width / 2: if mouseY < height / 2: unclick(0) eng.stopSound() click(0) else: unclick(2) eng.stopSound() click(2) else: if mouseY < height / 2: unclick(1) eng.stopSound() click(1) else: unclick(3) eng.stopSound() click(3)
def show_clicked(dt): global isPlaying if clicked_fields[0] > 0: if clicked_fields[0] > DELAY_TIME: eng.drawRect(0, 0, width / 2, height / 2, clicked_colors[0]) clicked_fields[0] -= dt if clicked_fields[0] <= 0: isPlaying = False if clicked_fields[1] > 0: if clicked_fields[1] > DELAY_TIME: eng.drawRect(width / 2, 0, width / 2, height / 2, clicked_colors[1]) clicked_fields[1] -= dt if clicked_fields[1] <= 0: isPlaying = False if clicked_fields[2] > 0: if clicked_fields[2] > DELAY_TIME: eng.drawRect(0, height / 2, width / 2, height / 2, clicked_colors[2]) clicked_fields[2] -= dt if clicked_fields[2] <= 0: isPlaying = False if clicked_fields[3] > 0: if clicked_fields[3] > DELAY_TIME: eng.drawRect(width / 2, height / 2, width / 2, height / 2, clicked_colors[3]) clicked_fields[3] -= dt if clicked_fields[3] <= 0: isPlaying = False
def getImages(home='./'): # General Sprites IMAGESDICT = {} for root, dirs, files in os.walk(home + 'Sprites/General/'): for name in files: if name.endswith('.png'): full_name = os.path.join(root, name) IMAGESDICT[name[:-4]] = Engine.image_load(full_name, convert_alpha=True) # Icon Sprites loc = home + 'Sprites/Icons/' ICONDICT = {image[:-4]: Engine.image_load(loc + image, convert_alpha=True) for image in os.listdir(loc) if image.endswith('.png')} # Item and Skill and Status sprites loc = home + 'Data/Items/' ITEMDICT = {image[:-4]: Engine.image_load(loc + image, convert=True) for image in os.listdir(loc) if image.endswith('.png')} for image in ITEMDICT.values(): Engine.set_colorkey(image, COLORKEY, rleaccel=True) # Unit Sprites UNITDICT = {} for root, dirs, files in os.walk(home + 'Data/Characters/'): for name in files: if name.endswith('.png'): full_name = os.path.join(root, name) image = Engine.image_load(full_name, convert=True) Engine.set_colorkey(image, COLORKEY, rleaccel=True) UNITDICT[name[:-4]] = image # Battle Animations ANIMDICT = AnimationManager.BattleAnimationManager(COLORKEY, home) return IMAGESDICT, UNITDICT, ICONDICT, ITEMDICT, ANIMDICT
def __init__(self): cursor_image = pyglet.resource.image('cursor.png') self.cursor = pyglet.sprite.Sprite(cursor_image, x=16, y=79) self.textboxes = [ Engine.TextBox(240, 56, 8, 8), Engine.TextBox(240, 152, 8, 64), Engine.TextBox(64, 32, 8, 200) ] self.labels = [ pyglet.text.Label('ITEM', x=16, y=208, font_size=8), pyglet.text.Label('You have nothing.', x=16, y=32, font_size=8) ] Engine.window.push_handlers(on_draw=self.on_draw, on_key_press=self.on_key_press)
def __init__(self): # Storing the engines of this car self.__leftengine = Engine("A") self.__rightengine = Engine("B") self.__engines = [self.__leftengine, self.__rightengine] # Storing the distance between the centers of the cars self.__widthcar = 2.6 + 11.1 - 0.2 self.__gearratio = 1.0 # Storing the perimeter of the wheels (2*pi*r) self.__perimeter = 2 * math.pi * 2.579 # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines) self.__command_going = False self.__command_thread = None
def __init__(self, name, origin): self.name = name if not isinstance(origin, Base.Vector): raise RuntimeError("origin is not a Vector!") self.origin = origin self.center = Engine(name + "_center", origin, size='E24') self.centermount = BodyTube(name+"_centermount",\ origin.add(Base.Vector(0,0,6.35)),\ size='BT-50',length=95) self.stagetube = BodyTube(name+"_stagetube",\ origin.add(Base.Vector(0,0,6.35)),\ size='BT-55',length=95) self.centermountlowerring = EngineMountRing(\ name+"_centermountlowerring",\ origin.add(Base.Vector(0,0,6.35)),\ enginesize='E24',tubesize='BT-55') self.centermountupperring = EngineMountRing(\ name+"_centermountlowerring",\ origin.add(Base.Vector(0,0,70)),\ enginesize='E24',tubesize='BT-55') s1origin = origin.add(Geometry.pointXdeltaatang(0, 12.5 + 17, 0)) self.s1 = Engine(name + "_s1Engine", s1origin, size='D') self.s1mount = BodyTube(name+"_s1Mount",\ s1origin.add(Base.Vector(0,0,6.35)), size='BT-50',length=2*95) self.s1cone = NoseCone(name+"_s1cone",\ s1origin.add(Base.Vector(0,0,6.35+2*95)),\ size='BT-50',height=30) s2origin = origin.add(Geometry.pointXdeltaatang(120, 12.5 + 17, 0)) self.s2 = Engine(name + "_s2Engine", s2origin, size='D') self.s2mount = BodyTube(name+"_s2Mount",\ s2origin.add(Base.Vector(0,0,6.35)), size='BT-50',length=2*95) self.s2cone = NoseCone(name+"_s2cone",\ s2origin.add(Base.Vector(0,0,6.35+2*95)),\ size='BT-50',height=30) s3origin = origin.add(Geometry.pointXdeltaatang(240, 12.5 + 17, 0)) self.s3 = Engine(name + "_s3Engine", s3origin, size='D') self.s3mount = BodyTube(name+"_s3Mount",\ s3origin.add(Base.Vector(0,0,6.35)), size='BT-50',length=2*95) self.s3cone = NoseCone(name+"_s3cone",\ s3origin.add(Base.Vector(0,0,6.35+2*95)),\ size='BT-50',height=30) couplerOrig = origin.add(Base.Vector(0, 0, 70 + 6.35)) couplerExtrude = Base.Vector(0, 0, 50.8) self.stage1coupler = Part.Face(Part.Wire(Part.makeCircle(33.0/2.0,\ couplerOrig))).extrude(couplerExtrude) couplerCut = Part.Face(Part.Wire(Part.makeCircle(31/2.0,\ couplerOrig))).extrude(couplerExtrude) self.stage1coupler = self.stage1coupler.cut(couplerCut) self.fin1 = FinType1(self.name+"_fin1",\ origin.add(Geometry.pointXdeltaatang(60,17,6.35+70)),\ orient=60,height=70,angle=30,length=200) self.fin2 = FinType1(self.name+"_fin2",\ origin.add(Geometry.pointXdeltaatang(180,17,6.35+70)),\ orient=180,height=70,angle=30,length=200) self.fin3 = FinType1(self.name+"_fin3",\ origin.add(Geometry.pointXdeltaatang(300,17,6.35+70)),\ orient=300,height=70,angle=30,length=200)
def draw(self, surf): self.arrow_counter.update() if self.direction == 'up': pos = (self.x, self.y - (self.offset.pop() if self.offset else 0)) surf.blit(Engine.subsurface(self.images['up'], (0, self.arrow_counter.get()*8, 14, 8)), pos) elif self.direction == 'down': pos = (self.x, self.y + (self.offset.pop() if self.offset else 0)) surf.blit(Engine.subsurface(self.images['down'], (0, self.arrow_counter.get()*8, 14, 8)), pos) elif self.direction == 'left': pos = (self.x - (self.offset.pop() if self.offset else 0), self.y) surf.blit(Engine.subsurface(self.images['left'], (self.arrow_counter.get()*8, 0, 8, 14)), pos) elif self.direction == 'right': pos = (self.x + (self.offset.pop() if self.offset else 0), self.y) surf.blit(Engine.subsurface(self.images['right'], (self.arrow_counter.get()*8, 0, 8, 14)), pos)
def roundTest(): player1 = Upbidder.upbidder() player2 = LieCaller.LieCaller() players = [player1, player2] diceState = {player1: [5], player2: [2, 3]} loosers = Engine.round(diceState, players) assert loosers[ 0] == 0, "Expected upbidder to bid 6,1 and liecaller to call it, winning. Instead got loosers " + str( loosers) diceState = {player1: [6], player2: [2, 3]} loosers = Engine.round(diceState, players) assert loosers[ 0] == 1, "Expected upbidder to bid 6,1 and liecaller to call it, losing. Instead got loosers " + str( loosers)
def test6(): chessboard = ChessBoard() engine = Engine(chessboard) chessboard.init_board() chessboard.set_chess((8, 5), 'x') chessboard.set_chess((9, 5), 'x') chessboard.set_chess((10, 5), 'x') chessboard.set_chess((11, 5), 'x') chessboard.set_chess((12, 5), 'x') print(chessboard.get_board()) ret = engine.is_Win(chessboard.get_board()) chessboard.print_board() #print(chessboard.get_board()) print(ret)
def formatSprite(self, sprite): # Sprites are in 64 x 64 boxes passivesprite = Engine.subsurface( sprite, (0, 0, GC.TILEWIDTH * 2 * 4, GC.TILEHEIGHT * 2)) redsprite = Engine.subsurface( sprite, (0, GC.TILEHEIGHT * 2, GC.TILEWIDTH * 2 * 4, GC.TILEHEIGHT * 2)) activesprite = Engine.subsurface( sprite, (0, GC.TILEHEIGHT * 4, GC.TILEWIDTH * 2, GC.TILEHEIGHT * 2)) formationsprite = Engine.subsurface( sprite, (GC.TILEWIDTH * 2 * 2, GC.TILEHEIGHT * 4, GC.TILEWIDTH * 2 * 2, GC.TILEHEIGHT * 2)) return passivesprite, activesprite, redsprite, formationsprite
def __init__(self): # Storing the engines of this car self.__leftengine = Engine('A') self.__rightengine = Engine('B') self.__engines = [self.__leftengine, self.__rightengine] # Storing the distance between the centers of the cars self.__widthcar = 2.6 + 11.1 - .2 self.__gearratio = 1. # Storing the perimeter of the wheels (2*pi*r) self.__perimeter = 2 * math.pi * 2.579 # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines) self.__command_going = False self.__command_thread = None
class Controller: def __init__(self): # Storing the engines of this car self.__leftengine = Engine('A') self.__rightengine = Engine('B') self.__engines = [self.__leftengine,self.__rightengine] # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines) def drive(self): while True: if raspiSckt.new_values(): leftspeed,rightspeed = raspiSckt.get_values() self.__leftengine.set_speed(leftspeed) self.__rightengine.set_speed(rightspeed) time.sleep(0.005)
def draw_warning_marker(self, surf, left, top, cur_unit): items = self.unit.items # print(items) # Effective Weapons if any(item.effective and any(comp in cur_unit.tags for comp in item.effective.against) for item in items): frame = (Engine.get_time()//125)%8 topleft = (left + 5, top - 12) surf.blit(Engine.subsurface(GC.IMAGESDICT['DangerMarker'], (frame*8, 0, 8, 16)), topleft) # Killer Weapons and Master Weapons for item in items: if (item.warning and eval(item.warning)) or \ (item.reverse and cur_unit.getMainWeapon() and Weapons.TRIANGLE.compute_advantage(item, cur_unit.getMainWeapon())[0]): frame = (Engine.get_time()//125)%8 topleft = (left + 5, top - 12) surf.blit(Engine.subsurface(GC.IMAGESDICT['WarningMarker'], (frame*8, 0, 8, 16)), topleft)
def update(self, gameStateObj): if Engine.get_time() - self.last_move_update > 100: self.x += self.x_change self.y += self.y_change self.last_move_update = Engine.get_time() if self.transition: self.transparency -= self.change_over_time if self.transparency <= 5: self.transition = False else: self.transparency += self.change_over_time if self.transparency >= 75: self.remove_me = True self.transparency = 100
def draw(self, surf, gameStateObj=None, blend=None): if self.on and self.frameCount >= 0 and Engine.get_time() > self.start_time: # The animation is too far to the right. Must move left. (" - 32") image = self.image x, y = self.position if self.ignore_map: topleft = x, y else: topleft = (x-gameStateObj.cameraOffset.x-1)*GC.TILEWIDTH, (y-gameStateObj.cameraOffset.y)*GC.TILEHEIGHT if blend: image = Image_Modification.change_image_color(image, blend) if self.tint: Engine.blit(surf, image, topleft, image.get_rect(), Engine.BLEND_RGB_ADD) else: surf.blit(image, topleft)
def finetune(model_path, augment_frame, max_augment_frame, city_name, trans_testset, trans_test_loader, trans_pop_sr, center_time_slot=48 * 2, max_iters=50): used_sr_pop = trans_pop_sr[(trans_pop_sr.shape[0] // 2 - augment_frame):(trans_pop_sr.shape[0] // 2 + augment_frame + 1)] trans_hr_dataset = dataset.AugmentedDataset( trans_testset, np.arange(center_time_slot - augment_frame, center_time_slot + augment_frame + 1), args.frame, used_sr_pop) trans_hr_loader = load(trans_hr_dataset, 'pop_hr', args.batch_size, '{}_train'.format(city_name)) G = torch.load(model_path, map_location='cuda:' + str(args.cuda_num)) G.assign_cuda(args.cuda_num) lr = 1e-4 criterion_2 = nn.MSELoss().cuda(args.cuda_num) mse_list = [] min_string = '' G.train() iters_count = 0 max_iters = 50 while True: for batch_3 in trans_hr_loader['loader']: output_3 = G(batch_3) loss_G_3 = criterion_2( output_3['pop_sr'][:, -1:], batch_3['pop_hr'][:, -1:].cuda(args.cuda_num)) G.optimizer.zero_grad() loss_G_3.backward(retain_graph=True) G.optimizer.step() iters_count += 1 if iters_count == max_iters: break if iters_count == max_iters: break Engine.test_data(G, [trans_test_loader], True, 0)
def __init__(self, name): # Setup default values. self.alluppercase = False self.alllowercase = False self.chartable = {} self.idxfile = Engine.engine_constants[ 'home'] + "Sprites/Fonts/" + name.split('_')[0] + '.idx' self.bmpfile = Engine.engine_constants[ 'home'] + "Sprites/Fonts/" + name + '.png' self.width = 8 self.height = 16 self.transrgb = (0, 0, 0) # Read the font index. File errors will bubble up to caller. f = open(self.idxfile, "r") for x in f.readlines(): # Remove EOL, if any. if x[-1] == '\n': x = x[:-1] words = x.split() # Handle keywords. if words[0] == "alluppercase": self.alluppercase = True elif words[0] == "alllowercase": self.alllowercase = True elif words[0] == "width": self.width = int(words[1]) elif words[0] == "height": self.height = int(words[1]) elif words[0] == "transrgb": self.transrgb = (int(words[1]), int(words[2]), int(words[3])) else: # Default to index entry. if words[0] == "space": words[0] = ' ' if self.alluppercase: words[0] = words[0].upper() if self.alllowercase: words[0] = words[0].lower() self.chartable[words[0]] = (int(words[1]) * self.width, int(words[2]) * self.height, int(words[3])) f.close() # Setup the actual bitmap that holds the font graphics. self.surface = Engine.image_load(self.bmpfile) Engine.set_colorkey(self.surface, self.transrgb, rleaccel=True)
def home_form_post(): text = request.form['text'] option = request.form['metric'] engine = Engine.Engine() top = engine.get_recommendations(text, 5, option) if top[0] == 'film not found': return render_template('submitted_form.html', name='FILM NOT FOUND!', metric=option, rec1=' ', rec2=' ', rec3=' ', rec4=' ', rec5=' ') elif top[0] == 'insufficient ratings': return render_template('submitted_form.html', name='INSUFFICIENT RATINGS! TRY ANOTHER MOVIE', metric=option, rec1=' ', rec2=' ', rec3=' ', rec4=' ', rec5=' ') else: return render_template('submitted_form.html', name=text, metric=option, rec1=top[0], rec2=top[1], rec3=top[2], rec4=top[3], rec5=top[4])
def get_image(self, frame, shake, range_offset, pan_offset, static): image = frame[0].copy() if not self.right: image = Engine.flip_horiz(image) offset = frame[1] # Handle own offset if self.lr_offset: offset = offset[0] + self.lr_offset.pop(), offset[1] if self.effect_offset: offset = offset[0] + self.effect_offset[0], offset[ 1] + self.effect_offset[1] if self.personal_offset: offset = offset[0] + self.personal_offset[0], offset[ 1] + self.personal_offset[1] left = 0 if not static: left += shake[0] + range_offset if self.at_range and not static: if self.ignore_pan: if self.right: pan_max = range_offset - 24 else: pan_max = range_offset + 24 left -= pan_max else: left += pan_offset if self.right: offset = offset[0] + shake[0] + left, offset[1] + shake[1] else: offset = GC.WINWIDTH - offset[0] - image.get_width( ) + left, offset[1] + shake[1] return image, offset
def main(): """Run the engine and start the game""" if len(sys.argv) < 3: print("Usage: multiplegames.py player1,player2(,playerx)? games_per_pairing [config_file]") sys.exit(0) players = sys.argv[1].split(",") rrPlay = abs(int(sys.argv[2])) if len(players) != 2: print("Exactly 2 players are required") sys.exit(0) # Get config if len(sys.argv) < 4: cfg = Config(GlobalConfig.DEFAULT_CFG) else: cfg = Config(sys.argv[3]) cfg.data['UI'] = False cfg.data['STDOUT_LOGGING'] = False # build player win dictionary playerWins = {} for player in players: if player.strip()in playerWins.keys(): print("Player names must be unique. Clone your player module to play against yourself.") sys.exit(0) playerWins[player.strip()] = 0 # round-robin the players game = 1 # play all pairings the players while game <= rrPlay: pairings = [] for pairing in itertools.permutations(playerWins.keys(), 2): pairings.append(pairing) random.shuffle(pairings) for pairing in pairings: if game <= rrPlay: print ("Game: %s Pairing: %s" % (game, pairing)) cfg.data['PLAYER_MODULES'] = pairing s = time.clock() winningPlayer, valid = Engine.run(cfg) if winningPlayer != False: print ("\tWinner: %s" % (cfg.data['PLAYER_MODULES'][winningPlayer - 1])) playerWins[cfg.data['PLAYER_MODULES'][winningPlayer - 1]] += 1 else: print ("\tNo winner.") print ("\tValid players: " + str(valid)) print ("\tTime: %s seconds." % (time.clock() - s)) game += 1 # sort dictionary by wins and display rankings rank = 1 for item in sorted(playerWins.items(), key=operator.itemgetter(1), reverse=True): print("Rank", rank, "is player", item[0], "with", item[1], "wins.") rank += 1
def validMoves(self, position): """returns positions of valid moves for a regular red gamepiece on an empty board""" moves = [] if Engine.isOnTopRow(position): moves = [] elif Engine.isOnRightEdge(position) or Engine.isOnLeftEdge(position): # Edges only have one valid move moves = [position - 4] elif Engine.isOnOddRow(position): # diagonals above pieces on odd rows are always 4 and 5 pieces after moves = [position - 4, position - 3] elif Engine.isOnEvenRow(position): # diagonals below pieces on even rows are always 3 and 4 piececs after moves = [position - 5, position - 4] return moves
def create_image(self): # Weapon Icons Pictures if self.grey: weaponIcons = GC.ITEMDICT['Gray_Wexp_Icons'] else: weaponIcons = GC.ITEMDICT['Wexp_Icons'] self.image = Engine.subsurface(weaponIcons, (0, 16 * self.idx, 16, 16))
def get_image(self, grid, x, y, grid_name): top_pos = (x, y - 1) left_pos = (x - 1, y) right_pos = (x + 1, y) bottom_pos = (x, y + 1) if grid_name == 'all_attack' or grid_name == 'all_spell': top = bool(grid[x * self.gridHeight + y - 1]) if self.check_bounds(top_pos) else False left = bool(grid[(x - 1) * self.gridHeight + y]) if self.check_bounds(left_pos) else False right = bool(grid[(x + 1) * self.gridHeight + y]) if self.check_bounds(right_pos) else False bottom = bool(grid[x * self.gridHeight + y + 1]) if self.check_bounds(bottom_pos) else False else: top = any( u_id in self.displaying_units for u_id in grid[x * self.gridHeight + y - 1]) if self.check_bounds(top_pos) else False left = any( u_id in self.displaying_units for u_id in grid[(x - 1) * self.gridHeight + y]) if self.check_bounds(left_pos) else False right = any( u_id in self.displaying_units for u_id in grid[(x + 1) * self.gridHeight + y]) if self.check_bounds(right_pos) else False bottom = any(u_id in self.displaying_units for u_id in grid[x * self.gridHeight + y + 1]) if self.check_bounds(bottom_pos) else False index = top * 8 + left * 4 + right * 2 + bottom # Binary logic to get correct index # print(str(index) + ' '), return Engine.subsurface( self.types[grid_name], (index * GC.TILEWIDTH, 0, GC.TILEWIDTH, GC.TILEHEIGHT))
def getJumpPosition(self, position, middlePosition): # On odd rows, the square on the right is not at position - 4 # On even rows, the square on the right is at position - 4 isSkippingRight = Engine.isOnOddRow(position) != (position - middlePosition == 4) distanceToNextPosition = 7 if isSkippingRight else 9 finalPosition = position - distanceToNextPosition return finalPosition
def updateEvents(): #print("here") for evt in pygame.event.get(): if evt.type is pygame.QUIT: #Engine.stop() if g.multithreading: Engine.stop() pygame.quit() sys.exit() #print(pygame.event.event_name(evt.type)) EventList[pygame.event.event_name(evt.type)](evt) if g.draggedEventActive: if evt.type is pygame.MOUSEBUTTONDOWN: g.mouseDown = True elif evt.type is pygame.MOUSEBUTTONUP: g.mouseDown = False #print(g.mouseDown) if g.mouseDown and (evt.type is pygame.MOUSEMOTION): EventList["MouseDragged"](evt)
def writeMultiSolution(targetSolutionName, candidates, projectExt, solutionHeader, is2010): basePath = os.path.dirname(targetSolutionName) projects = [] for item in map(os.path.abspath, candidates): generalDict, projectDict, solutionDict = Engine.readConfiguration(item) if len(solutionDict) == 0: logging.debug('No solution section found, skipping (offending file %s)' % item) continue baseProject = os.path.splitext(item)[0] + projectExt try: dependencies = Engine.findDependencies( basePath, solutionDict['dependencies'], solutionDict['dependenciespaths'], generalDict['platform'], lambda x: x+'.bdgcfg' ) except KeyError: dependencies = [] # HACK: The platform will just be the last one referenced. platform = projectDict['platform'] projects.append( [baseProject] + [os.path.splitext(x)[0] + projectExt for x in dependencies] ) solution = writeSolution( basePath, projects, platform, Engine.getConfigurations(projectDict) ) # All is now done, try to write the target file to disk... Engine.writeConfigFile( targetSolutionName, solutionHeader + '\n' + solution )
def isUsable(self): engine = Engine.getInstance() # ignore execution if the location where the command can be executed is not equal # to the name of the current scenario if not self.requirements: print "no requirements, automatically pass" return True for item in self.requirements: if not engine.getPlayer().hasItem(item): print "failed, did not have " + item return False print "pass requirements check" return True
def __init__(self): # Storing the engines of this car self.__leftengine = Engine('A') self.__rightengine = Engine('B') self.__topengine = Engine('C') self.__engines = [self.__leftengine,self.__rightengine,self.__topengine] # Storing the distance between the centers of the cars self.__widthcar = 2.6 + 11.1 - .2 # Storing the Lego MINDSTORM distance sensor self.__distanceLego = MindstormSensor('1','ULTRASONIC_CONT') # Storing the GPIO distance sensor self.__distancePi = DistanceSensor(17,4) # Storing the current gearration self.__gearratio = 1./1. # Storing the perimeter of the wheels (2*pi*r) self.__perimeter = 2*math.pi*2.758 # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines,[self.__distanceLego]) # Storing a reference to a gpio thread self.__gpio = GPIO_Thread([self.__distancePi]) # Turn the threads on self.__brickpi.on() self.__gpio.on()
def execute(self, s): # now we look for an item in the list of known items for i in Engine.getInstance().getScenario().getObjects() + Engine.getInstance().getPlayer().getInventory(): if str(i) in s: Engine.getInstance().show(i.getDescription()) return # if nothing was found display an error Engine.getInstance().show("No such thing exists")
def __init__(self): # Storing the engines of this car self.__leftengine = Engine("A") self.__rightengine = Engine("B") self.__topengine = Engine("C") self.__engines = [self.__leftengine, self.__rightengine, self.__topengine] # Storing the distance between the centers of the cars self.__widthcar = 2.6 + 11.1 - 0.2 # Storing the Lego MINDSTORM distance sensor self.__distanceLego = MindstormSensor("4", "ULTRASONIC_CONT") # Storing the GPIO distance sensor self.__distancePi = DistanceSensor(17, 4) # Storing the current gearration self.__gearratio = 1.0 # Storing the perimeter of the wheels (2*pi*r) self.__perimeter = 2 * math.pi * 2.579 # Storing a reference to a brickpi thread self.__brickpi = BrickPi_Thread(self.__engines, [self.__distanceLego]) # Storing a reference to a gpio thread self.__gpio = GPIO_Thread([self.__distancePi]) self.__brickpi.on() self.__gpio.on() self.__command_going = False self.__command_thread = None
def writeSingleSolution(configFileName, projectExt, solutionExt, solutionHeader, is2010): basePath = os.path.dirname(configFileName) try: # Load the overall configuration from the .tcfg file. generalDict, projectDict, solutionDict = Engine.readConfiguration(configFileName) if len(solutionDict) == 0: logging.debug('No solution section found, bailing out of solution generation (offending file %s)' % configFileName) return 1 if 'dependencies' not in solutionDict: solutionDict['dependencies'] = '' if 'dependenciespaths' not in solutionDict: solutionDict['dependenciespaths'] = '' if 'additionalprojects' not in solutionDict: solutionDict['additionalprojects'] = '' if 'additionalprojectspaths' not in solutionDict: solutionDict['additionalprojectspaths'] = '' # Determine the output product path. targetName = os.path.join( basePath, generalDict['name'] + solutionExt ) logging.debug( 'Now generating solution %s' % targetName ) baseProject = os.path.splitext(configFileName)[0] + projectExt dependencies = Engine.findDependencies( basePath, solutionDict['dependencies'], solutionDict['dependenciespaths'], generalDict['platform'], lambda x: x+'.bdgcfg') additionalProjects = Engine.findDependencies( basePath, solutionDict['additionalprojects'], solutionDict['additionalprojectspaths'], generalDict['platform'], lambda x: x+'.bdgcfg') platform = projectDict['platform'] solution = writeSolution( basePath, [[baseProject] + [os.path.splitext(x)[0] + projectExt for x in dependencies]] + [[os.path.splitext(x)[0] + projectExt for x in additionalProjects]], platform, Engine.getConfigurations(projectDict)) # All is now done, try to write the target file to disk... Engine.writeConfigFile( targetName, solutionHeader + '\n' + solution ) except SyntaxError, e: logging.error( str(e) ) return 1
def initialize(dispatch = True, seed = None, cache = None, autoClean = True) : """initialize(dispatch = True, seed = None, cache = None, autoClean = True) Initialize the Single-Molecule Diffusion Simulator. If dispatch is True, SMDS will attempt to contact the local Foundry to operate in distributed mode. If this contact fails or if dispatch is False, SMDS will operate in single-processor mode. An optional seed for the random number generator may be provided, otherwise the generator is initialized with the current time.\n""" global initialized, addToQueue, queueIsEmpty, clearQueue, theCache if initialized : return if dispatch and Dispatch.initialize() : addToQueue = Dispatch.addToQueue queueIsEmpty = Dispatch.queueIsEmpty clearQueue = Dispatch.clearQueue msg("SMDS Initialized in Dispatch mode.") else : Engine.initialize() addToQueue = Engine.addToQueue queueIsEmpty = Engine.queueIsEmpty clearQueue = Engine.clearQueue msg("SMDS Initialized in Single-processor mode.") if seed : Cores.c2D.sRnd(int(seed)) else : Cores.c2D.sRnd() initialized = True if cache : theCache = Cache(cache, autoClean) # Ensure proper shutdown() from atexit import register from sys import exit from signal import signal, SIGTERM register(shutdown) signal(SIGTERM, lambda x,y : exit()) try : from signal import SIGBREAK signal(SIGBREAK, lambda x,y : exit()) except : pass
def execute(self, s): engine = Engine.getInstance() itemsInRoom = engine.getScenario().getObjects() # get all the items in the room # search for an item specified for item in itemsInRoom: if str(item) in s: # add the item to the player's inventory if it can be possessed if item.possess: engine.getPlayer().addItem(item) itemsInRoom.remove(item) # remove the item from the room after placing it in your inventory engine.show("You picked up the " + str(item)) # display an error if the item can not be possessed else: engine.show("You can not pick up that item") return
def main(): """Run the engine and start the game""" sys.setcheckinterval(500) if len(sys.argv) == 1: sys.argv.append("cablecar.cfg") wins = {} scores = {} games = abs(int(raw_input("Enter number of games: "))) # Get config cfg = Config(sys.argv[1]) cfg.data['UI'] = False cfg.data['STDOUT_LOGGING'] = False for game in xrange(1, games + 1): startTime = time.clock() winningPlayer, score, eliminated, moves = Engine.run(cfg) endTime = time.clock() if len(eliminated) > 0: print "Players errored: %s" % eliminated print "Game %s time: %s seconds" % (game, endTime - startTime) if winningPlayer != []: for player in winningPlayer: if player not in wins.keys(): wins[player] = 1 scores[player] = [score[player]] else: wins[player] += 1 scores[player].append(score[player]) print "Player %s won the game with %s points!" % (winningPlayer, score) else: print "No winner." for player,wins in wins.iteritems(): print "Player %s won %s times" % (player, wins) score = 0 for num in scores[player]: score += num print "Total Score: %s" % score
def readTemplate(generalDict, projectdict): dir = Engine.getTemplatesDir(generalDict) try: filename = os.path.join(dir, VISUAL_STUDIO_MASTER_TEMPLATE) template = file(filename).read() except IOError: return '' typefilename = os.path.join(dir, VISUAL_STUDIO_TEMPLATES[generalDict['type']]) typetemplate = file(typefilename).read() for config in Engine.CONFIGURATION_NAMES__NAKED: ttp = typetemplate.replace('{{{CONFIG}}}', config.upper()) template = template.replace( '{{{%sLINKSECTION}}}' % config.upper(), ttp ) template = template.replace('{{{MFC_USAGE}}}', MFC_USAGE_TABLE[generalDict['type']]) template = template.replace('{{{CHARACTER_SET}}}', CHARACTER_SET_TABLE[generalDict['type']]) return template
def possibleJumps(position, board): jumps = [] piece = board[position] validMoves = piece.validMoves(position) canJumpOver = lambda move: squareIsOccupied(move, board) and not areSameColor(piece, board[move]) occupiedEnemySquares = list(filter(canJumpOver, validMoves)) for middlePosition in occupiedEnemySquares: jumpPosition = piece.getJumpPosition(position, middlePosition) if not (Engine.isOnEdge(middlePosition) or squareIsOccupied(jumpPosition, board)): newBoard = jumpOver(position, middlePosition, board) nextJumps = possibleJumps(jumpPosition, newBoard) # If there are no next jumps if not nextJumps: # Add this jump to the list jumps.append(newBoard) else: # Add the next jumps to the list jumps += nextJumps return jumps
def redraw(self, screen, drawselected=True): if not self.visible:return #Draw inventory background screen.blit(self.image, (self.invpos[0]-\ self.imgoffset[0]+self.invsoffset[0], \ self.invpos[1]-self.imgoffset[1]+self.invsoffset[1])) xx=0 #current slot #Skip draw when there no inventory if not self.inventory:return for item in self.inventory.slots: if item!=None: img=self.imgloader.loadimage(item[0]) nx=(xx%self.invsize[0])*self.ts+self.getinvpos()[0] ny=(xx/self.invsize[0])*self.ts+self.getinvpos()[1] screen.blit(img, (nx, ny)) #Draw count txt=self.font.render(str(item[1]), 1, (255, 255, 0)) screen.blit(txt, (nx, ny)) #Draw selection if xx==self.selected and drawselected: pygame.draw.rect(screen, (255, 255, 0), \ (nx-1, ny-1, self.ts-2, self.ts-2), 1) drawselected=False #increase index xx+=1 #Draw tooltip if self.lastslot!=None: slot=self.inventory.getslot(self.lastslot) if slot!=None: mx, my=pygame.mouse.get_pos() block=Engine.create_block(slot[0]) # create temp block #Draw tooltip background #pygame.draw.rect(screen, (64, 64, 64), \ # (mx, my, 128, 32), 0) #Draw item name color=(200, 200, 200) img=self.font.render(str(block.name), 1, color, (64, 64, 64)) px,py=mx+(64-img.get_size()[0]/2),my screen.blit(img, (px, py))
def alter(self): engine = Engine.getInstance() # the engine of the game player = engine.getPlayer() # the player # load these up now so there isn't a recursion error earlier on from Item import loadItem from Scenario import getRoom # go through the list of items to remove from the player for item in self.alterPlayer[0]: player.removeItem(loadItem(item)) # go through the list of items to add to the player for item in self.alterPlayer[1]: player.addItem(loadItem(item)) # go through the list of rooms to be altered for room in self.alterRooms.keys(): if room is not None: scene = getRoom(room) else: scene = engine.getScenario() # remove things from the rooms for n in self.alterRooms[room][0][0]: scene.objects.remove(loadItem(n)) for n in self.alterRooms[room][1][0]: scene.commands.remove(loadCommand(n)) for n in self.alterRooms[room][2][0]: scene.paths.remove(getRoom(n)) # add things to the rooms for n in self.alterRooms[room][0][1]: scene.objects.append(loadItem(n)) for n in self.alterRooms[room][1][1]: scene.commands.append(loadCommand(n)) for n in self.alterRooms[room][2][1]: scene.paths.append(getRoom(n)) print scene.objects print scene.commands print scene.paths
def generateReferences(basePath, platform, solutionDict): """ Goes through any of the dependencies, tries to resolve them and put the uuid references in the project file. """ try: deps = solutionDict['dependencies'] depspath = solutionDict['dependenciespaths'] except KeyError: return '' linkLibraries = 0 try: if int(solutionDict['linklibraries']): linkLibraries = 1 except KeyError: pass libraryOptions = '' if linkLibraries: libraryOptions = '\t\t\t<LinkLibraryDependencies>true</LinkLibraryDependencies>\n' dependencies = Engine.findDependencies( basePath, deps, depspath, platform, lambda x: x+'.bdgcfg' ) if len(dependencies) == 0: return '' result = '\t<ItemGroup>\n' for bdgcfg in dependencies: uuid = getGUIDByBdcfg(bdgcfg) vcxproj = os.path.splitext(bdgcfg)[0] + '.vcxproj' vcxproj = PathHelp.relative(basePath, vcxproj) result += '\t\t<ProjectReference Include="%s">\n\t\t\t<Project>{%s}</Project>\n%s\t\t</ProjectReference>\n' % (vcxproj, uuid, libraryOptions) result += '\t</ItemGroup>\n' return result
def start(thread=True): #print(thread) Engine.start(window, thread)
random.uniform(self.area[0], self.area[0] + self.area[2]), random.uniform(self.area[1], self.area[1] + self.area[3])]) self.frame = 0 elif self.movement_state == "waypoints": if len(self.remaining_waypoints) == 0: self.remaining_waypoints = self.waypoints.copy() self.walk_to_points = [self.remaining_waypoints.pop(0)] super().update(current_time, event) if __name__ == "__main__": pygame.init() clock = pygame.time.Clock() screen_info = pygame.display.Info() screen_size = [screen_info.current_w, screen_info.current_h] screen = pygame.display.set_mode(screen_size, RESIZABLE) chars = [] b = Engine(screen) b.load_tilemap("TheMap/map.floor", 0) b.load_obstaclemap("TheMap/map.obstacles", 0) montag = AICharacter(screen, "graphics/droids/blue_guard/atlas.txt", "graphics/droids/red_guard/config.txt", pathfinding_grid=b.obstacles.grid, pos=[3, 0], movement_state="random_walk", area=[5, 0, 10, 5]) while True: current_time = pygame.time.get_ticks() clock.tick(60) screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == VIDEORESIZE: screen_size = event.dict["size"] screen = pygame.display.set_mode(screen_size, RESIZABLE) else:
__author__ = 'dean' from sys import exit import Engine import Map start = Map('outside') game = Engine(start) game.play()
def stop(): Engine.stop()