def start(self): gameRunning = True print("Awaiting Players...") self.connectPlayers() # Connect 2 players print("Players connected.. starting game") counter = 1 while gameRunning: try: self.updateClients(Logic().displayBoard()) # Display the game board PLAYER_OBJECTS[counter]['playerObject'].send("Opponents turn...".encode()) # Opponents turn message counter = 1 - counter clientInput = self.getInput(PLAYER_OBJECTS[counter]['playerObject'], PLAYER_OBJECTS[counter]['playerName']) # Input request hasWon = Logic().placePiece(counter, int(clientInput)) if(hasWon): self.updateClients(Logic().displayBoard()) # Display final game board self.updateClients("\nGAME OVER\n{} has Won!".format(PLAYER_OBJECTS[counter]['playerName'])) # send game over message gameRunning = False except ConnectionResetError: gameRunning = False SERVER.close()
def setUp(self): self.since = Mock() self.until = Mock() state_mock = Mock() state_mock.get_electric_meters.return_value = {} self.db_mock = Mock() self.plugin_loader_mock = Mock() data_per_hour = 3600 self.logic = Logic(state_mock, self.db_mock, self.plugin_loader_mock, data_per_hour) self.meter_id = 10 self.meter = Mock() self.meter_dict = { 'name': 'Name', 'type': 'TEST_PLUGIN', 'custom': { 'key1': 'val1', 'key2': 100 } } state_mock.get_electric_meters.return_value = { self.meter_id: self.meter } state_mock.get_electric_meters_dict.return_value = { self.meter_id: self.meter_dict }
def ajax(sub): logger.debug('AJAX %s %s', package_name, sub) if sub == 'setting_save': try: ret = Logic.setting_save(request) return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) elif sub == 'scheduler': try: go = request.form['scheduler'] logger.debug('scheduler :%s', go) if go == 'true': Logic.scheduler_start() else: Logic.scheduler_stop() return jsonify(go) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) return jsonify('fail') elif sub == 'one_execute': try: ret = Logic.one_execute() return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) return jsonify('fail') # kthoom 에서 호출 elif sub == 'zip_list': try: ret = Logic.get_zip_list() return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) return jsonify('fail') elif sub == 'stop': try: ret = Logic.stop() return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) elif sub == 'reset_db': try: ret = Logic.reset_db() return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) elif sub == 'download_by_manga_id': try: ret = Logic.download_by_manga_id(request) return jsonify(ret) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc())
def custom_turn(): # Goal: all plays in the Area of L1 to L15 need bonus plays to be valid. # BUG: doesn't consider single letters along the way - investigate! # see also: Line 3378 in logic_new # S.reset() S.set_rack("ERNSTLUA") word_1 = D.Play("NEUTRAL", "F8", "x") L.execute_play(word_1) S.increase_turn() S.set_rack("ERNSTLUA") word_2 = D.Play("ANLAUTES", "K5", "y") L.execute_play(word_2) S.increase_turn() # S.set_rack("ERNSTLUA") S.set_rack("FASS") # Fass should be valid on L2 searching_area = D.Area("L1", "L15") possible_plays = Scratch.find_plays_for_area(searching_area) # pprint.pprint(possible_plays) max_length = len(searching_area.non_empty_letters) + len(S.get_rack()) + 1 for current_length in range(max_length, 2, -1): highest_length = [ item for item in possible_plays if len(item) == current_length ] print("Plays with a length of", current_length) pprint.pprint(highest_length) Display.print_board()
def play_finding_multiple(): # TODO: make this pass # input("Starting: play_finding_multiple") S.reset() S.set_rack("ERDE") play_erde = D.Play("ERDE", "G8", "X") L.execute_play(play_erde) S.increase_turn() S.set_rack("DEN") area_den = D.Area("K6", "K8") subturn_den = Game.SubTurn(area_den) # highest scoring play should be DEN, K6, Y with ERDEN as bonus. print("highest scoring play for Area of K6 to K8:") print(subturn_den.highest_scoring_play) # play_den = D.Play("DEN", "K6", "Y") L.execute_play(subturn_den.highest_scoring_play) # L.execute_play(play_den) S.increase_turn() S.set_rack("URNE") Display.print_board() parallel_area = D.Area("I9", "L9") affected_parallel_plays = parallel_area.contested_plays print("affected_parallel plays:") pprint.pprint(affected_parallel_plays) parallel_subturn = Game.SubTurn(parallel_area) print("highest scoring play:") # expected: Still URNE on I9, X # bonus, DU, ER, DENN pprint.pprint(parallel_subturn.highest_scoring_play) print("Plays possible on I9 to L9:") pprint.pprint(parallel_subturn.possible_plays)
def __init__(self): self.length = 50 # 1-10 poczatkawa gestosc losowo rozmieszczonych komorek self.density = 1 self.board = Board(self.length * 10) self.logic = Logic(self.length**2, self.density)
def build(self): self.logic = Logic() self.tabs = MasterLayout(do_default_tab=False, tab_width=Window.width / 3) self.logic.register_layout(self.tabs) return self.tabs
def __init__(self, rules): """Compile rules into internal lookup tables""" if isinstance(rules, basestring): rules = rules.splitlines() # --- parse and process rules --- P = Prover() for rule in rules: # XXX `a` is hardcoded to be always atom a, op, b = rule.split(None, 2) a = Logic.fromstring(a) b = Logic.fromstring(b) if op == '->': P.process_rule(a, b) elif op == '==': P.process_rule(a, b) P.process_rule(b, a) else: raise ValueError('unknown op %r' % op) # --- build deduction networks --- self.beta_rules = [] for bcond, bimpl in P.rules_beta: self.beta_rules.append( (set(_as_pair(a) for a in bcond.args), _as_pair(bimpl))) # deduce alpha implications impl_a = deduce_alpha_implications(P.rules_alpha) # now: # - apply beta rules to alpha chains (static extension), and # - further associate beta rules to alpha chain (for inference at runtime) impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta) # extract defined fact names self.defined_facts = set(_base_fact(k) for k in impl_ab.keys()) # build rels (forward chains) full_implications = defaultdict(set) beta_triggers = defaultdict(set) for k, (impl, betaidxs) in impl_ab.iteritems(): full_implications[_as_pair(k)] = set(_as_pair(i) for i in impl) beta_triggers[_as_pair(k)] = betaidxs self.full_implications = full_implications self.beta_triggers = beta_triggers # build prereq (backward chains) prereq = defaultdict(set) rel_prereq = rules_2prereq(full_implications) for k, pitems in rel_prereq.iteritems(): prereq[k] |= pitems self.prereq = prereq
def main(): establish_logger(logging.DEBUG) logic = Logic() logic.logging = logging client = Client("localhost", 6969, "DaKillers", logic) client.connect() client.join_game(logic.setup()) client._start_game()
def lambda_handler(event, context): dbPers = DBPersistence("config.yaml") twlogger = TweetLogger("config.yaml") logic = Logic(dbPers, twlogger) if (logic.IsGameFinished() is not True): logic.Update() else: print ("Game already finished") return 200
def Generate(): content = request.get_json() heroes = Logic.GetHeroes(int(content['numberOfHeroes'])) ship = Logic.GetShip() threat = Logic.GetThreat() return jsonify({ "heroes": '<br/>'.join(heroes), "ship": '<br/>'.join(ship), "threat": threat })
def get_messages(): def date_parser(date): return None if date is None else date.replace('_', ' ') bl = Logic() messages = bl.get_messages( args.user_name, time_start=date_parser(args.date_start), time_end=date_parser(args.date_end)) tu.export_messages(messages, args.output_file)
def __init__(self, app): Scene.__init__(self, app) self.hex_layout = None self.map = HexMap() self.map_image = None self.game_objects = None self.overlay = None self.logic = Logic(self)
def position_finding(): S.reset() S.set_rack("ERNSTL?") test_play_open = D.Play("LÜSTERN", "G8", "X") L.execute_play(test_play_open) S.increase_turn() Display.print_board() S.set_rack("BEDARF") test_play_perpendicular = D.Play("BEDARF,", "F3", "y") # also counts as extended, score for BEDARF and FLÜSTERN would be added L.execute_play(test_play_perpendicular) S.increase_turn() Display.print_board() S.set_rack("D") test_play_extended = D.Play("FLÜSTERND", "F8", "x") L.execute_play(test_play_extended) S.set_rack("RETEN") test_play_retten = D.Play("RETTEN", "J5", "y") L.execute_play(test_play_retten) S.increase_turn() Display.print_board() S.set_rack("USTRN") test_play_merge = D.Play("AUSTERN", "F6", "x") # this only counts as AUSTERN, since it doesn't extend any existing words L.execute_play(test_play_merge) S.increase_turn() Display.print_board() word_log = WL.read_log() # all_positions = word_log[0]['used_positions'] # types of plays: # open - ruler finds no fixed positions, except for the origin # also, all neighbors are open positions # example: LÜSTERN, G8, x # extended - ruler goes along a placed word to find letters to extend # in the same direction # example: LÜSTERND, G8, x # perpendicular - ruler finds a single letter to extend and places a word # along the perpendicular axis. # example: BEDARF, F3, y # extends LÜSTERND to FLÜSTERND # merging - ruler finds gaps with busy positions, tries to find a fitting # word to fill the gap # Iterate over all filled positions # merge overlapping positions # make plays according to the areas # TODO: Extend Area to consider its neighbors print("PASSED.")
def read_from_position(): S.reset() S.set_rack("ERDE") play_erde = D.Play("ERDE", "G8", "X") L.execute_play(play_erde) reader_word = L.suggestion_from_position("G8", "X") print("reader_word", reader_word) print("word equals the word in the previous play:", reader_word == play_erde.word) print("PASSED.")
def setUp(self): self.state_mock = Mock() self.state_mock.get_electric_meters_dict.return_value = {} self.state_mock.get_electric_meters.return_value = {} self.db_mock = Mock() self.plugin_loader_mock = Mock() self.data_per_hour = 3600 self.logic = Logic(self.state_mock, self.db_mock, self.plugin_loader_mock, self.data_per_hour) self.plugin_mock = Mock() self.plugin_loader_mock.get_plugin.return_value = self.plugin_mock
class MonologueApp(App): logic = ObjectProperty(None) tabs = ObjectProperty(None) def build(self): self.logic = Logic() self.tabs = MasterLayout(do_default_tab=False, tab_width=Window.width / 3) self.logic.register_layout(self.tabs) return self.tabs
def customers(): logic = Logic() base_url = "XXX" params = "?_limit=50" url = base_url + params response_deals = get_api_data(headers=headers, url=url) if len(response_deals) > 0: customer_stat = logic.group_customers(response_deals) return render_template('customer-status.html', customer_stat=customer_stat) else: msg = 'No deals found' return render_template('customer-status.html', msg=msg)
def averages(): logic = Logic() base_url = "XXX" params = "?_limit=50" url = base_url + params response_deals = get_api_data(headers=headers, url=url) if len(response_deals) > 0: average = logic.average_deal_value(response_deals) return render_template('averages.html', average=average) else: msg = 'No deals found' return render_template('overview.html', msg=msg)
def get_player_name(main_frame): global player,game_result player_name=tk.StringVar() if game_result is not None: global player1,player2 player_name.set(game_result) game_result=None player1=Logic("Player1") player2=Logic("Player2") else: player_name.set(f"{player}'s Turn") print(player_name.get()) tk.Label(main_frame,textvariable=player_name,bg='#d93253',font=("helvetica 12",12)).grid(row=7,column=1)
def test_tasks_work_in_parallel(logic_analyzer: Logic, target_data: AnalyzerData): """ Checks there are two toggling GPIOs driven by different tasks and toggling at 1Hz and 0.66 Hz """ channel_0 = logic_analyzer.get_toggle_frequency(target_data, Logic.Channel.CHANNEL_0) channel_1 = logic_analyzer.get_toggle_frequency(target_data, Logic.Channel.CHANNEL_1) LOGGER.info('freq mean = %f, %f', channel_0[0], channel_1[0]) LOGGER.info('freq stddev = %f, %f', channel_0[1], channel_1[1]) validate_frequency(channel_0, 0.666666666, 0.001) validate_frequency(channel_1, 1.0, 0.001)
class MonologueApp(App): logic = ObjectProperty(None) tabs = ObjectProperty(None) def build(self): self.logic = Logic() self.tabs = MasterLayout(do_default_tab = False, tab_width=Window.width/3) self.logic.register_layout(self.tabs) return self.tabs
def main_thread(): print("Welcome to the Atomic Swap application") if len(sys.argv) == 1: print_help() elif sys.argv[1] == "initiate": Logic().initiate([sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]]) elif sys.argv[1] == "redeem": Logic().redeem(sys.argv[2], sys.argv[3]) elif sys.argv[1] == "refund": Logic().refund(sys.argv[2]) elif sys.argv[1] == "test": Logic().Test() else: print_help()
def longest(string, filename="enable1.txt"): try: file = open(filename, "r") except: print("File Not Found") return None max_letter = "" for line in file.read().splitlines(): logic = Logic(string, line) if logic.match(): if len(max_letter) < len(line): max_letter = line return(max_letter)
def test_lexer(): file = "source/lexer-test-1.js" logic = Logic(file) excepted_result = [ "var", " ", "a", " ", "=", " ", "0", ";", "\r", "\n", "a", " ", "=", " ", "a", " ", "+", " ", "1", ";" ] lexer = logic.getLexer() tokens = logic.getTokens(lexer) result = True for i in range(len(tokens)): if tokens[i].text != excepted_result[i]: result = False assert result
def build(self): self.logic = Logic() self.tabs = MasterLayout(do_default_tab = False, tab_width=Window.width/3) self.logic.register_layout(self.tabs) return self.tabs
def __init__(self): super().__init__() ws = director.get_window_size() self.scale_x = ws[0] / window_original[0] self.scale_y = ws[1] / window_original[1] dynamic_layer = DynamicLayer() hud_layer = HUDLayer() wave_report = WaveReportLayer() wave_report.do(Hide()) self.logic = Logic(dynamic_layer, hud_layer, wave_report, self.win, self.lose) self.do(Repeat(CallFunc(self.logic.update) + Delay(update_delay))) wave_report.add(WaveReportMenu(self.logic)) self.add(GroundLayer(), z=0) self.add(StaticLayer(self.logic), z=1) self.add(dynamic_layer, z=2) self.add(CollisionLayer(self.logic), z=3) self.add(GUILayer(self.logic), z=4) self.add(hud_layer, z=6) self.add(wave_report, z=7)
def socketio_callback(cmd, data): if sid_list: running = "실행중" if Logic.is_running() else "실행중이 아닙니다." tmp = {'is_running': running, 'data': data} tmp = json.dumps(tmp, cls=AlchemyEncoder) tmp = json.loads(tmp) socketio.emit(cmd, tmp, namespace='/%s' % package_name, broadcast=True)
def kthroom_dp(path): tmp = path.split('/') real_path = os.path.join(Logic.get_setting_value('dfolder'), tmp[0], tmp[1]) real_path = real_path.replace(path_app_root, '')[1:].replace('\\', '/') logger.debug('load:%s', real_path) return send_from_directory('', real_path)
def __init__(self,item,ind_hosts,dif_countries,wte,sma,sessionid,slc,sl,srl,password,username): self.recent_parsing_list = [u'results_html',u'hovers',u'app_data',u'currency', u'success',u'start',u'pagesize',u'total_count',u'assets'] self.asset_parsing_list = ['currency','contextid','classid','instanceid','amount', 'status','original_amount','tradable', 'background_color','icon_url','icon_url_large','descriptions', 'name','name_color','type', 'market_name','market_actions','commodity','app_icon','owner','actions', 'market_tradable_restriction'] self.listinginfo_parsing_list = ['fee','publisher_fee_percent','currencyid','steam_fee','publisher_fee', 'converted_steam_fee','converted_price_per_unit', 'converted_fee_per_unit','converted_fee_per_unit', 'converted_publisher_fee_per_unit','price', 'publisher_fee_app','converted_steam_fee_per_unit'] self.listinginfo_asset_parsing_list = ['currency','contextid','amount','market_actions','appid'] self.item = item self.listinginfo_list = {} self.final_list_listings = {} self.final_list_assets = {} self.final_item = {} self.float100 = float(100) self.http = SteamBotHttp(wte,sma,sessionid,slc,sl,srl,password,username) self.log = Logic('item',ind_hosts,dif_countries,0) self.host_counter = 0 self.contaSim = 0 self.contaNao = 0
def __init__(self,items_list,wte,sma,sessionid,sls,sl,srl,password,username): self.recent_parsing_list = [u'results_html',u'hovers',u'last_listing',u'last_time',u'app_data',u'currency', u'success',u'more',u'purchaseinfo'] self.asset_parsing_list = ['currency','contextid','classid','instanceid','amount', 'status','original_amount','tradable', 'background_color','icon_url','icon_url_large', 'descriptions','name','name_color','type', 'market_name','market_actions','commodity','app_icon', 'owner','actions','market_tradable_restriction'] self.listinginfo_parsing_list = ['fee','publisher_fee_percent','steam_fee','publisher_fee', 'converted_steam_fee','converted_publisher_fee','converted_price_per_unit', 'converted_fee_per_unit','converted_fee_per_unit', 'converted_publisher_fee_per_unit','price', 'publisher_fee_app','converted_steam_fee_per_unit'] self.listinginfo_asset_parsing_list = ['currency','contextid','amount','market_actions','appid'] self.float100 = float(100) self.http = SteamBotHttp(wte,sma,sessionid,sls,sl,srl,password,username) #logic mode recent #logic mode item self.log = Logic('recent',0,0,items_list) self.last_listing_buy = '' self.dif_countries = self.log.dif_countries self.dif_hosts = self.log.dif_hosts_recent self.contaSim = 0 self.contaNao = 0 self.list_median_prices = {} self.timestamp_lock = threading.Lock() self.buy_lock = threading.Lock() self.sell_lock = threading.Lock() self.last_listing_buy_lock = threading.Lock() self.write_active_listings_lock = threading.Lock() self.timestamp = '' self.search_for_kenny_cobble = False
def play(self, r, c): if r < 0 or r > 18 or c < 0 or c > 18: print("Invalid position specified!") print("Player " + str(self.current_turn) + "'s turn!") return if not self.board.spot_empty(r, c): print("Position is occupied!") print("Player " + str(self.current_turn) + "'s turn!") return self.past_board = deepcopy(self.board) self.board.play(self.current_turn, r, c) self.board_verify() # Verify the current board if Logic.check_win(self.board, r, c, self.current_turn): print("Player " + str(self.current_turn) + ' wins!') self.winner = self.current_turn other_player = 1 if self.current_turn is 2 else 2 if self.agents[other_player] and self.agents[ other_player].is_learning: self.agents[other_player].update_heuristic_vals(self.board, self.winner, win=True) print("Game ended.") self.has_win = True return self.current_turn = 2 if self.current_turn is 1 else 1 if not self.run_game(): print("Player " + str(self.current_turn) + "'s turn!")
def game_loop(self): clock = pygame.time.Clock() #Initialize self.scoreboard = Scoreboard() self.timer = CountDown() self.control = Control() self.graphics = Graphics(self.scoreboard, self.timer); self.player = Player(self.graphics) self.world = World(self.graphics, self.player) self.logic = Logic(self.player, self.world, self.graphics, self.scoreboard, self.timer, self.control) while globalvars.run_game: delta = clock.tick(30) # fps # Catch input event for event in pygame.event.get(): if event.type == QUIT: return else: self.control.update(event) # Update self.logic.update(delta) self.world.update(delta) self.graphics.update(self.screen, delta) # Render self.graphics.draw(self.screen, delta); self.screen.blit(self.player.speedmsg, (0, 35)) self.screen.blit(self.player.rotmsg, (0, 55)) pygame.display.flip()
def test_context_change_overhead(logic_analyzer: Logic, target_data: AnalyzerData): """ Checks CPU context change overhead doesn't exceed the limit of 0.5% """ percentage = logic_analyzer.get_active_usage(target_data, Logic.Channel.CHANNEL_2) * 100 LOGGER.info('Context change overhead = %f %%', percentage) assert percentage < 0.5
def main(): argument_parser = get_argument_parser() arguments = argument_parser.parse_args() lnd = Lnd(arguments.lnddir, arguments.grpc) first_hop_channel_id = vars(arguments)['from'] to_channel = arguments.to if arguments.ratio < 1 or arguments.ratio > 50: print("--ratio must be between 1 and 50") sys.exit(1) channel_ratio = float(arguments.ratio) / 100 if arguments.incoming is not None and not arguments.list_candidates: print( "--outgoing and --incoming only work in conjunction with --list-candidates" ) sys.exit(1) if arguments.list_candidates: incoming = arguments.incoming is None or arguments.incoming if incoming: list_incoming_candidates(lnd, channel_ratio) else: list_outgoing_candidates(lnd, channel_ratio) sys.exit(0) if to_channel is None and first_hop_channel_id is None: argument_parser.print_help() sys.exit(1) percentage = arguments.percentage if percentage: if percentage < 1 or percentage > 100: print("--percentage must be between 1 and 100") argument_parser.print_help() sys.exit(1) # the 'to' argument might be an index, or a channel ID if to_channel and to_channel < 10000: # here we are in the "channel index" case index = int(to_channel) - 1 candidates = get_incoming_rebalance_candidates(lnd, channel_ratio) candidate = candidates[index] last_hop_channel = candidate else: # else the channel argument should be the channel ID last_hop_channel = get_channel_for_channel_id(lnd, to_channel) first_hop_channel = get_channel_for_channel_id(lnd, first_hop_channel_id) amount = get_amount(arguments, first_hop_channel, last_hop_channel) if amount == 0: print("Amount is 0, nothing to do") sys.exit(0) max_fee_factor = arguments.max_fee_factor excluded = arguments.exclude return Logic(lnd, first_hop_channel, last_hop_channel, amount, channel_ratio, excluded, max_fee_factor).rebalance()
async def api_create(request): msg = await request.json() Logic().serviceStart(port=msg["port"], instance=msg["instance"], ss_pass=msg["ss_pass"], ss_mode=msg["ss_mode"]) return JSONResponse({"message": "create ok!"})
def finding_usable_positions(): S.reset() S.set_rack("BEDARF") test_play_b = D.Play("BEDARF", "M3", "Y") print(test_play_b) # print(WS.find_execution(test_play_b)) print(test_play_b.find_execution()) L.execute_play(test_play_b) S.increase_turn() Display.print_board() S.set_rack("BEDARF") test_area = D.Area(position_list=WS.find_usable_positions("M3", "x")) starting_positions = WS.find_starting_position("FADER", test_area) print("starting positions for FARBE on M3, X:") print(starting_positions)
def build(self): self.title = 'PocketCosmos' self.calc_iconsize() self.settings = ConfigController('settings.json') self.sound_manager = SoundManager(settings=self.settings) self.logic = Logic( settings=self.settings, sound_manager=self.sound_manager ) self.screenmanager = ScreenManager() self.mainscreen = MainScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='main' ) # MenuScreen does not need logic self.menuscreen = MenuScreen(name='menu') self.settingsscreen = SettingsScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='settings' ) self.savegamescreen = SavegameScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='savegames' ) self.creditsscreen = CreditsScreen( iconsize=self.iconsize, name='credits' ) # order adding here reflects which screen is shown first! self.screenmanager.add_widget(self.menuscreen) self.screenmanager.add_widget(self.mainscreen) self.screenmanager.add_widget(self.settingsscreen) self.screenmanager.add_widget(self.savegamescreen) self.screenmanager.add_widget(self.creditsscreen) self.logic.apply_settings() return self.screenmanager
def start_game(self): global runRobot if runRobot!=True: logic_grid = self.ids.dnd.ids.grid_2 size = logic_grid.rows logic = [] self.collects = self.kivyrunner.level.getNumberOfCollectables() #everytime this number decreases -> play sound for y in xrange(size): logic.append([]) for x in xrange(size): logic[y].append(LogicBlock("","_")) index = size * size - 1 for child in logic_grid.children: if not child.children: picture = 'block_blank.png' blocktype = '_' logic_block = LogicBlock(picture, blocktype) else: picture = child.children[0].source blocktype = child.children[0].blocktype logic_block = LogicBlock(picture, blocktype) #print str(int(index/size)) + " y: "+ str(size - ((index%size) - 1)) logic[((index%size) )][int(index/size)] = logic_block index-=1 logicobject = Logic(size,self.kivyrunner.level) logicobject.data = logic logicobject.printBlocks() self.kivyrunner.setLogic(logicobject) dt = 0.6 global runRobot runRobot = True Clock.unschedule(self.iterate_game) Clock.schedule_interval(self.iterate_game, dt)
def __init__(self): ''' Initializes window, canvas, gameplay options and menus, loads resources (settings, images, dictionaries) and sets up debugging. ''' # Window self.size = Size(650, 650) self.root = self.createWindow(self.size) self.icon = self.loadIcon('icon.png') # Internal settings self.validState = False # Not ready to accept guesses self.DEBUG = tk.BooleanVar(value=False) # Print debug messages self.VERBOSE = tk.BooleanVar(value=True) # Print verbose debug messages # Logging self.messages = [] self.logger = Logger('Hangman') # Resources self.dictData = self.loadDictionaries('data/dicts/dictionaries.json') self.dictNames = [name for name in self.dictData.keys()] self.flags = self.loadFlags() # Gameplay settings self.restartDelay = 1500 # Delay before new round begins (ms) self.revealWhenLost = False # Reveal the word when the game is lost # TODO: Save reference to current dict (?) self.DICT = tk.StringVar(value=choice(self.dictNames)) # Select random dictionary self.characterSet = self.dictData[self.DICT.get()]['characters'] # TODO: Make this dictionary-dependent # Menus self.menubar = self.createMenus() # Events self.bindEvents() # Game play self.graphics = Graphics(self.root, *self.size, characterSet=self.characterSet) # Renderer self.logic = Logic(self.graphics.chances) # Logic self.wordFeed = self.createWordFeed(self.DICT.get()) # Provides a stream of words and hints self.chances = self.graphics.chances # Initial number of chances for each round self.word = None # Initialized later on self.hint = None # Initialized later on # Audio self.effects = self.loadAudio()
def print_schedule(request, group=None, teacher=None): template = 'schedule.html' context = RequestContext(request) logic = Logic() if group: context['schedule'] = logic.get_schedule_for_group(group) elif teacher: context['schedule'] = logic.get_schedule_for_teacher(teacher) else: context['schedule'] = logic.get_full_schedule() context['current_selection'] = logic.current_selection print logic.current_selection context['flag_updates'] = logic.updates context['on_date'] = logic.date context['groups'] = logic.get_all_groups() context['teachers'] = logic.get_all_teachers() return render_to_response(template, context)
class Game: def __init__(self, config, inputs, output): self._inputs = inputs self._output = output self._logic = Logic(config.get_board_size()) def run(self): self._output.show_welcome() while True: self._output.show_board(self._logic.get_board()) self.make_move() if not self._logic.if_end(): continue # END OF GAME self._output.show_board(self._logic.get_board()) w = self._logic.get_winner() if w is None: # DRAW. self._output.show_draw() else: self._output.show_winner(w) break def make_move(self): player = self._logic.get_player() while True: x, y = self._inputs[player].get_move() if self._logic.make_move(x, y) is False: self._output.show_move_error(player) continue break
def __init__(self, rules): """Compile rules into internal lookup tables""" if isinstance(rules, basestring): rules = rules.splitlines() # --- parse and process rules --- P = Prover() for rule in rules: # XXX `a` is hardcoded to be always atom a, op, b = rule.split(None, 2) a = Logic.fromstring(a) b = Logic.fromstring(b) if op == '->': P.process_rule(a, b) elif op == '==': P.process_rule(a, b) P.process_rule(b, a) else: raise ValueError('unknown op %r' % op) #P.print_proved('RULES') #P.print_beta('BETA-RULES') # --- build deduction networks --- # deduce alpha implications impl_a = deduce_alpha_implications(P.rules_alpha) # now: # - apply beta rules to alpha chains (static extension), and # - further associate beta rules to alpha chain (for inference at runtime) impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta) if 0: print '\n --- ALPHA-CHAINS (I) ---' for a,b in impl_a.iteritems(): print '%s\t-> α(%2i):%s' % (a,len(b),b) print ' - - - - - ' print if 0: print '\n --- ALPHA-CHAINS (II) ---' for a,(b,bb) in impl_ab.iteritems(): print '%s\t-> α(%2i):%s β(%s)' % (a,len(b),b, ' '.join(str(x) for x in bb)) print ' - - - - - ' print # extract defined fact names self.defined_facts = set() for k in impl_ab.keys(): if k[:1] == '!': k = k[1:] self.defined_facts.add(k) #print 'defined facts: (%2i) %s' % (len(self.defined_facts), self.defined_facts) # now split each rule into four logic chains # (removing betaidxs from impl_ab view) (XXX is this needed?) impl_ab_ = dict( (k,impl) for k, (impl,betaidxs) in impl_ab.iteritems()) rel_tt, rel_tf, rel_ft, rel_ff = split_rules_tt_tf_ft_ff(impl_ab_) # XXX merge me with split_rules_tt_tf_ft_ff ? rel_tbeta = {} rel_fbeta = {} for k, (impl,betaidxs) in impl_ab.iteritems(): if k[:1] == '!': rel_xbeta = rel_fbeta k = name_not(k) else: rel_xbeta = rel_tbeta rel_xbeta[k] = betaidxs self.rel_tt = rel_tt self.rel_tf = rel_tf self.rel_tbeta = rel_tbeta self.rel_ff = rel_ff self.rel_ft = rel_ft self.rel_fbeta = rel_fbeta self.beta_rules = P.rules_beta # build rels (forward chains) K = set (rel_tt.keys()) K.update(rel_tf.keys()) K.update(rel_ff.keys()) K.update(rel_ft.keys()) rels = {} empty= () for k in K: tt = rel_tt.get(k,empty) tf = rel_tf.get(k,empty) ft = rel_ft.get(k,empty) ff = rel_ff.get(k,empty) tbeta = rel_tbeta.get(k,empty) fbeta = rel_fbeta.get(k,empty) rels[k] = tt, tf, tbeta, ft, ff, fbeta self.rels = rels # build prereq (backward chains) prereq = {} for rel in [rel_tt, rel_tf, rel_ff, rel_ft]: rel_prereq = rules_2prereq(rel) for k,pitems in rel_prereq.iteritems(): kp = prereq.setdefault(k,[]) for p in pitems: list_populate(kp, p) self.prereq = prereq
from pygame.locals import * from display import DrawGameplay from events import Events from variables import MainVariables from logic import Logic # pygame init pygame.init() clock = pygame.time.Clock() var = MainVariables() draw = DrawGameplay(var) events = Events(var) logic = Logic(var) # try open save try: pickle.load(open('save')) var.saved = True except: var.saved = False # main loop while True: clock.tick(15) events.get() logic.game() draw.things()
def __init__(self, config, inputs, output): self._inputs = inputs self._output = output self._logic = Logic(config.get_board_size())
class SteamJsonItem: def __init__(self,item,ind_hosts,dif_countries,wte,sma,sessionid,slc,sl,srl,password,username): self.recent_parsing_list = [u'results_html',u'hovers',u'app_data',u'currency', u'success',u'start',u'pagesize',u'total_count',u'assets'] self.asset_parsing_list = ['currency','contextid','classid','instanceid','amount', 'status','original_amount','tradable', 'background_color','icon_url','icon_url_large','descriptions', 'name','name_color','type', 'market_name','market_actions','commodity','app_icon','owner','actions', 'market_tradable_restriction'] self.listinginfo_parsing_list = ['fee','publisher_fee_percent','currencyid','steam_fee','publisher_fee', 'converted_steam_fee','converted_price_per_unit', 'converted_fee_per_unit','converted_fee_per_unit', 'converted_publisher_fee_per_unit','price', 'publisher_fee_app','converted_steam_fee_per_unit'] self.listinginfo_asset_parsing_list = ['currency','contextid','amount','market_actions','appid'] self.item = item self.listinginfo_list = {} self.final_list_listings = {} self.final_list_assets = {} self.final_item = {} self.float100 = float(100) self.http = SteamBotHttp(wte,sma,sessionid,slc,sl,srl,password,username) self.log = Logic('item',ind_hosts,dif_countries,0) self.host_counter = 0 self.contaSim = 0 self.contaNao = 0 def getitemtotalready(self, item_full): self.recent_parsed = {} if type(item_full) == dict: for key in self.recent_parsing_list: if item_full.has_key(key): item_full.pop(key) else: item_full = {} #retorna um dict so com as keys assets e listinginfo self.recent_parsed = item_full #------------------------------------------------------------------------------------------------------------------- #-------------------------------------------ASSETS!!!!!!!!!!!!!!---------------------------------------------------- ''' #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getCleanAssetList(self): self.asset_list = {} if self.recent_parsed.has_key('assets'): self.asset_list = self.recent_parsed['assets'] if self.asset_list.has_key('730'): self.asset_list = self.asset_list['730'] self.asset_list = self.asset_list['2'] for key_item in self.asset_list: for key in self.asset_parsing_list: if key in self.asset_list[key_item]: self.asset_list[key_item].pop(key) else: return False else: return False #lista final dos assets = list2 = {'awp worm god':'231342342','ak47 redline':'432342342342',...} #nao executar, so no getfinallist() def getlistassets(self): try: self.final_list_assets = {} self.getCleanAssetList() for key_item in self.asset_list.keys(): if self.asset_list[key_item].has_key('market_hash_name'): self.final_list_assets[self.asset_list[key_item]['market_hash_name']] \ = self.asset_list[key_item]['id'] return True except: print "falha no parsing dos assets" return False ''' #------------------------------------------------------------------------------------------------------------------- #-------------------------------------------LISTINGS!!!!!!!!!!!-------------------------------------------------------- #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! #1 a ser executada def delNonCsgoListings(self): self.listinginfo_list = {} if self.recent_parsed.has_key('listinginfo'): temp_list = self.recent_parsed['listinginfo'] self.listinginfo_list = temp_list for k in self.listinginfo_list.keys(): if self.listinginfo_list[k]['asset']['appid'] != 730: self.listinginfo_list.pop(k) elif self.listinginfo_list[k]['asset']['amount'] == 0: self.listinginfo_list.pop(k) else: return False #2 a ser executada #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getCleanListinginfoListWithAsset(self): for key_item in self.listinginfo_list: for key in self.listinginfo_parsing_list: if self.listinginfo_list[key_item].has_key(key): self.listinginfo_list[key_item].pop(key) #3 a ser executada #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getcleanlistings(self): for key_item in self.listinginfo_list: for key in self.listinginfo_asset_parsing_list: if self.listinginfo_list[key_item]['asset'].has_key(key): self.listinginfo_list[key_item]['asset'].pop(key) #lista final dos listings: list1 = {'231342342':'2.45','432342342342':'12.76',... #nao executar, so no getfinallist() def getlistlistings(self): self.final_list_listings = {} if self.delNonCsgoListings() != False: self.getCleanListinginfoListWithAsset() self.getcleanlistings() for key_item in self.listinginfo_list.keys(): if self.listinginfo_list[key_item].has_key('converted_price') is False: self.listinginfo_list.pop(key_item) else: return False #except: #print "falha no parsing da lista de listings" #return False #------------------------------------------------------------------------------------------------------------------- def minpriceitem(self,dict): temp_simple = {} for keys in dict: temp_simple[keys] = dict[keys]['converted_price'] return min(temp_simple,key=temp_simple.get) def getfinalitem(self): self.final_item = {} if self.getlistlistings() == False: print 'falha no parsing dos listings, try again' return False else: min_price_key = self.minpriceitem(self.listinginfo_list) for k in self.listinginfo_list: if k == min_price_key: self.final_item[k] = self.listinginfo_list[k] return self.final_item def seeifindividualiteminlistbuy(self,item): if item == self.item: return True else: return False def buyingroutinesingleitem(self,median_price): temp_resp = [] try: id = self.final_item.keys()[0] except: temp_resp.append(False) return temp_resp try: temp_converted_price_math = float(decimal.Decimal(self.final_item[id]['converted_price']) / 100) temp_converted_fee_math = float(decimal.Decimal(self.final_item[id]['converted_fee'])/100) if float(float(median_price) - float((temp_converted_price_math+temp_converted_fee_math))) >= \ (0.275*float(median_price)): if (temp_converted_price_math+temp_converted_fee_math) <= (80*self.getwalletbalance()): if int(self.final_item[id]['converted_currencyid']) == 2003: if self.final_item['listingid'] != self.last_listing_buy: self.last_listing_buy = self.final_item['listingid'] try: if (float(median_price) - float(self.getlowestprice(self.item))) \ >= (0.15*float(median_price)): print "O PRECO LOWEST E MT MAIS BAIXO QUE O MEDIO, NAO VOU COMPRAR" temp_resp.append(False) return temp_resp except KeyError: temp_resp.append(False) return temp_resp except TypeError: temp_resp.append(False) return temp_resp temp = self.http.buyitem(self.final_item[id]['listingid'], self.final_item[id]['converted_price'], self.final_item[id]['converted_fee'], self.final_item[id]['converted_currencyid']) self.log.writetobuyfile(self.http.httputil.data_buy['subtotal'], self.http.httputil.data_buy['fee'], self.http.httputil.data_buy, self.final_item[id]['listingid'],self.item,temp[0],temp[1],0) if temp[0] == 200: if temp[1]['wallet_info'].has_key('wallet_balance'): if self.log.writetowallet(temp[1]['wallet_info']['wallet_balance']) == True: print "Ok COMPREI A: " + self.item + " ao preco: " + \ str(self.final_item[id]['converted_price'] + self.final_item[id]['converted_fee']) temp_resp.append(True) temp_resp.append(median_price) temp_resp.append(self.item) temp_resp.append(temp_converted_fee_math+temp_converted_price_math) return temp_resp else: print "Nao pude comprar item " + self.item print "erro ao comprar item" temp_resp.append(False) return temp_resp else: temp_resp.append(False) return temp_resp else: print "Nao pude comprar: " + self.item +" porque nao tenho fundos" temp_resp.append(False) return temp_resp else: print "THREAD " + str(0) + " nao pode comprar " + self.item + \ " porque margens nao sao suficientes. " \ "Preco medio: " + str(median_price) +\ ' Preco do item: ' + str(temp_converted_fee_math+temp_converted_price_math) temp_resp.append(False) return temp_resp except ValueError, KeyError: print "float not valid" temp_resp.append(False) return temp_resp temp_resp.append(False) return temp_resp
class Main: def __init__(self, width, height, caption): self.width = width self.height = height self.caption = caption self.drawer = Drawer(self) self.logic = Logic() def init(self): pygame.init() pygame.display.set_caption(self.caption) self.screen = pygame.display.set_mode((self.width, self.height)) self.drawer.init() # start game with clear surface self.drawer.clear() self.draw_info() pygame.display.flip() # spwn number in one second after game start pygame.time.set_timer(SPAWN, 1000) def quit(self): pygame.quit() def loop(self): running = True while running: event = pygame.event.wait() if event.type == pygame.QUIT: running = False elif event.type == SPAWN: self.spawn() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False else: self.submit(event.key) def spawn(self): pygame.time.set_timer(SPAWN, 0) self.logic.start_test() transform = self.logic.current_transform self.drawer.draw(transform) self.draw_info() pygame.display.flip() def submit(self, key): if key in (pygame.K_SPACE, pygame.K_r, pygame.K_f): # neither rotated nor flipped if key == pygame.K_SPACE: self.logic.submit_result(False, False) elif key == pygame.K_r: self.logic.submit_result(True, False) else: # key == pygame.K_f self.logic.submit_result(False, True) # make number disappear self.drawer.clear() self.draw_info() pygame.display.flip() # spawn another test in one second pygame.time.set_timer(SPAWN, 1000) def draw_info(self): text = "Tests Completed: %d\nTests Failed: %d\nAverage Time: %f sec" % (self.logic.tests_completed, self.logic.tests_failed, (float(self.logic.average_time)/1000.0)) self.drawer.render_text(text, False) self.drawer.render_text("Press R if rotated\nPress F if flipped\nPress SPACE if neither apply", True)
def __init__(self, width, height, caption): self.width = width self.height = height self.caption = caption self.drawer = Drawer(self) self.logic = Logic()
class Shapescape: # Initialize the boid view def __init__(self): self.win_width = 1024 self.win_height = 768 pygame.init() self.init_window() #title screen title_screen = TitleScreen(self.screen) title_screen.do_loop() self.game_loop() #gameover screen if globalvars.failed: gameover_screen = GameOver(self.screen, self.scoreboard) gameover_screen.do_loop() # Prepares the boid view def init_window(self): # Initialize window self.screen = pygame.display.set_mode((self.win_width, self.win_height)) pygame.display.set_caption('Shapescape') pygame.mouse.set_visible(1) # Continuesly renders the boid swarm def game_loop(self): clock = pygame.time.Clock() #Initialize self.scoreboard = Scoreboard() self.timer = CountDown() self.control = Control() self.graphics = Graphics(self.scoreboard, self.timer); self.player = Player(self.graphics) self.world = World(self.graphics, self.player) self.logic = Logic(self.player, self.world, self.graphics, self.scoreboard, self.timer, self.control) while globalvars.run_game: delta = clock.tick(30) # fps # Catch input event for event in pygame.event.get(): if event.type == QUIT: return else: self.control.update(event) # Update self.logic.update(delta) self.world.update(delta) self.graphics.update(self.screen, delta) # Render self.graphics.draw(self.screen, delta); self.screen.blit(self.player.speedmsg, (0, 35)) self.screen.blit(self.player.rotmsg, (0, 55)) pygame.display.flip()
def __init__(self, rules): """Compile rules into internal lookup tables""" if isinstance(rules, basestring): rules = rules.splitlines() # --- parse and process rules --- P = Prover() for rule in rules: # XXX `a` is hardcoded to be always atom a, op, b = rule.split(None, 2) a = Logic.fromstring(a) b = Logic.fromstring(b) if op == '->': P.process_rule(a, b) elif op == '==': P.process_rule(a, b) P.process_rule(b, a) else: raise ValueError('unknown op %r' % op) # --- build deduction networks --- # deduce alpha implications impl_a = deduce_alpha_implications(P.rules_alpha) # now: # - apply beta rules to alpha chains (static extension), and # - further associate beta rules to alpha chain (for inference at runtime) impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta) # extract defined fact names self.defined_facts = set() for k in impl_ab.keys(): if k[:1] == '!': k = k[1:] self.defined_facts.add(k) # now split each rule into four logic chains # (removing betaidxs from impl_ab view) (XXX is this needed?) impl_ab_ = dict( (k,impl) for k, (impl,betaidxs) in impl_ab.iteritems()) rel_tt, rel_tf, rel_ft, rel_ff = split_rules_tt_tf_ft_ff(impl_ab_) rel_tbeta = {} rel_fbeta = {} for k, (impl,betaidxs) in impl_ab.iteritems(): if k[:1] == '!': rel_xbeta = rel_fbeta k = name_not(k) else: rel_xbeta = rel_tbeta rel_xbeta[k] = betaidxs self.rel_tt = rel_tt self.rel_tf = rel_tf self.rel_tbeta = rel_tbeta self.rel_ff = rel_ff self.rel_ft = rel_ft self.rel_fbeta = rel_fbeta self.beta_rules = P.rules_beta # build rels (forward chains) K = set (rel_tt.keys()) K.update(rel_tf.keys()) K.update(rel_ff.keys()) K.update(rel_ft.keys()) rels = {} empty= () for k in K: tt = rel_tt[k] tf = rel_tf[k] ft = rel_ft[k] ff = rel_ff[k] tbeta = rel_tbeta.get(k,empty) fbeta = rel_fbeta.get(k,empty) rels[k] = tt, tf, tbeta, ft, ff, fbeta self.rels = rels # build prereq (backward chains) prereq = defaultdict(set) for rel in [rel_tt, rel_tf, rel_ff, rel_ft]: rel_prereq = rules_2prereq(rel) for k, pitems in rel_prereq.iteritems(): prereq[k] |= pitems self.prereq = prereq
class SteamJsonRecentThreading: def __init__(self,items_list,wte,sma,sessionid,sls,sl,srl,password,username): self.recent_parsing_list = [u'results_html',u'hovers',u'last_listing',u'last_time',u'app_data',u'currency', u'success',u'more',u'purchaseinfo'] self.asset_parsing_list = ['currency','contextid','classid','instanceid','amount', 'status','original_amount','tradable', 'background_color','icon_url','icon_url_large', 'descriptions','name','name_color','type', 'market_name','market_actions','commodity','app_icon', 'owner','actions','market_tradable_restriction'] self.listinginfo_parsing_list = ['fee','publisher_fee_percent','steam_fee','publisher_fee', 'converted_steam_fee','converted_publisher_fee','converted_price_per_unit', 'converted_fee_per_unit','converted_fee_per_unit', 'converted_publisher_fee_per_unit','price', 'publisher_fee_app','converted_steam_fee_per_unit'] self.listinginfo_asset_parsing_list = ['currency','contextid','amount','market_actions','appid'] self.float100 = float(100) self.http = SteamBotHttp(wte,sma,sessionid,sls,sl,srl,password,username) #logic mode recent #logic mode item self.log = Logic('recent',0,0,items_list) self.last_listing_buy = '' self.dif_countries = self.log.dif_countries self.dif_hosts = self.log.dif_hosts_recent self.contaSim = 0 self.contaNao = 0 self.list_median_prices = {} self.timestamp_lock = threading.Lock() self.buy_lock = threading.Lock() self.sell_lock = threading.Lock() self.last_listing_buy_lock = threading.Lock() self.write_active_listings_lock = threading.Lock() self.timestamp = '' self.search_for_kenny_cobble = False def getRecentTotalReady(self, recent_full): self.recent_parsed = {} if self.search_for_kenny_cobble is True: self.searchkenny(recent_full) if type(recent_full) == dict: for key in self.recent_parsing_list: if recent_full.has_key(key): recent_full.pop(key) else: recent_full = {} #retorna um dict so com as keys assets e listinginfo return recent_full #------------------------------------------------------------------------------------------------------------------- #-------------------------------------------ASSETS!!!!!!!!!!!!!!---------------------------------------------------- #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getCleanAssetList(self,recent_parsed): if recent_parsed.has_key('assets'): asset_list = recent_parsed['assets'] if asset_list.has_key('730'): asset_list = asset_list['730'] asset_list = asset_list['2'] for key_item in asset_list: for key in self.asset_parsing_list: if key in asset_list[key_item]: asset_list[key_item].pop(key) else: return False else: return False return asset_list #lista final dos assets = list2 = {'awp worm god':'231342342','ak47 redline':'432342342342',...} #nao executar, so no getfinallist() def getlistassets(self,asset_list): if asset_list == False: return False else: final_list_assets = {} for key_item in asset_list.keys(): if asset_list[key_item].has_key('market_hash_name'): final_list_assets[asset_list[key_item]['market_hash_name']] \ = asset_list[key_item]['id'] return final_list_assets #------------------------------------------------------------------------------------------------------------------- #-------------------------------------------LISTINGS!!!!!!!!!!!-------------------------------------------------------- #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! #1 a ser executada def delNonCsgoListings(self, recent_parsed): listinginfo_list = {} if recent_parsed.has_key('listinginfo'): temp_list = recent_parsed['listinginfo'] listinginfo_list = temp_list for k in listinginfo_list.keys(): if listinginfo_list[k]['asset']['appid'] != 730: listinginfo_list.pop(k) elif listinginfo_list[k]['asset']['amount'] == 0: listinginfo_list.pop(k) else: return False return listinginfo_list #2 a ser executada #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getCleanListinginfoListWithAsset(self,listinginfo_list): temp_dict = listinginfo_list if temp_dict == False: return False else: for key_item in temp_dict: for key in self.listinginfo_parsing_list: if temp_dict[key_item].has_key(key): temp_dict[key_item].pop(key) return temp_dict #3 a ser executada #NAO EXECUTAR MANUALMENTE!!!!!!!!!!!!!!!!!!!! def getcleanlistings(self,listinginfo_list): temp_dict = listinginfo_list if temp_dict == False: return False else: for key_item in temp_dict: for key in self.listinginfo_asset_parsing_list: if temp_dict[key_item]['asset'].has_key(key): temp_dict[key_item]['asset'].pop(key) return temp_dict #lista final dos listings: list1 = {'231342342':'2.45','432342342342':'12.76',... #nao executar, so no getfinallist() def getlistlistings(self,listinginfo_list): final_list_listings = listinginfo_list if final_list_listings != False: for key_item in final_list_listings.keys(): if final_list_listings[key_item].has_key('converted_price') == False: final_list_listings.pop(key_item) else: return False return final_list_listings #except: #print "falha no parsing da lista de listings" #return False #------------------------------------------------------------------------------------------------------------------- def getfinalrecentlist(self,asset_clean,listing_clean): final_list = {} if type(listing_clean) == dict: listing_clean_this = listing_clean else: print 'falha no parsing dos listings, try again' return False if type(asset_clean) == dict: asset_clean_this = asset_clean else: print 'falha no parsing dos assets, try again' return False for k in listing_clean_this: for k2 in asset_clean_this: if asset_clean_this.get(k2) == listing_clean_this[k]['asset']['id']: final_list[k2] = listing_clean_this.get(k) return final_list def seeifrecentiteminlistbuy(self,item): for temp in self.log.list_items_to_buy: if item == temp: return True #This function analizes if an item found on a RECENT_LISTING response from Steam belongs in the item list that the #user defined and if so it analizes if its worth buying # #Returns False if anything goes wrong def buyingroutine(self,final_list,t_name,host): temp_resp = [] if final_list == False: temp_resp.append(False) return temp_resp else: final_list_this = final_list for key in final_list_this: if key in self.log.list_items_to_buy_unicode: if self.list_median_prices.has_key(key): temp_converted_price_math = float(decimal.Decimal(final_list_this[key]['converted_price'])/100) temp_converted_fee_math = float(decimal.Decimal(final_list_this[key]['converted_fee'])/100) if float(float(self.list_median_prices[key]) - float((temp_converted_price_math+temp_converted_fee_math))) >= \ (0.275*(float(self.list_median_prices[key]))): if (temp_converted_price_math+temp_converted_fee_math) <= \ float((95*self.getwalletbalancefromvar())): if int(final_list_this[key]['converted_currencyid']) == 2003: if final_list_this[key]['listingid'] != self.last_listing_buy: self.last_listing_buy_lock.acquire() self.last_listing_buy = final_list_this[key]['listingid'] self.last_listing_buy_lock.release() print 'Estou prestes a entrar no acquire dos buys ON THREAD ' + str(t_name) self.buy_lock.acquire() print 'Entrei no acquire dos buys ON THREAD ' + str(t_name) try: if (float(self.list_median_prices[key]) - float(self.getlowestprice(key))) \ >= (0.15*float(self.list_median_prices[key])): print "O PRECO LOWEST E MT MAIS BAIXO QUE O MEDIO, NAO VOU COMPRAR" print 'sai do lock dos buys ON THREAD ' + str(t_name) self.buy_lock.release() temp_resp.append(False) return temp_resp except (TypeError,KeyError): self.buy_lock.release() temp_resp.append(False) return temp_resp temp = self.http.buyitem(final_list_this[key]['listingid'], final_list_this[key]['converted_price'], final_list_this[key]['converted_fee'], final_list_this[key]['converted_currencyid'],host) self.log.writetobuyfile(self.http.httputil.data_buy['subtotal'], self.http.httputil.data_buy['fee'], self.http.httputil.data_buy, final_list_this[key]['listingid'], key,temp[0],temp[1],t_name) if temp[0] == 200: if temp[1]['wallet_info'].has_key('wallet_balance'): if self.log.writetowallet(temp[1]['wallet_info']['wallet_balance']) == True: print "Ok COMPREI A: " + key + " ao preco: " + \ str(final_list_this[key]['converted_price'] + final_list_this[key]['converted_fee']) temp_resp.append(True) temp_resp.append(self.list_median_prices[key]) temp_resp.append(key) temp_resp.append(temp_converted_fee_math+temp_converted_price_math) self.buy_lock.release() print 'sai do lock dos buys ON THREAD ' + str(t_name) return temp_resp else: print "Nao pude comprar item " + key print "erro ao comprar item" self.buy_lock.release() print 'sai do lock dos buys ON THREAD ' + str(t_name) temp_resp.append(False) return temp_resp else: temp_resp.append(False) return temp_resp else: print "Nao pude comprar: " + key +" porque nao tenho fundos On THREAD " + str(t_name) temp_resp.append(False) return temp_resp else: print "THREAD " + str(t_name) + " nao pode comprar " + key + \ " porque margens nao sao suficientes. " \ "Preco medio: " + str(self.list_median_prices[key]) +\ ' Preco do item: ' + str(temp_converted_fee_math+temp_converted_price_math) temp_resp.append(False) return temp_resp else: temp_resp.append(False) return temp_resp temp_resp.append(False) return temp_resp #----------------------------------------------AUX FUNCTIONS----------------------------------------------------------- #Calls the querie recent function on the HTTP class def queryrecent(self,thread): lista = [] lista.append(self.http.queryrecent('steamcommunity.com',thread)) lista.append('steamcommunity.com') return lista #Calls the querie recent function on the HTTP class with diferent country codes! def queryrecentdifcountries(self,thread): country = random.choice(self.log.list_countries) lista = [] lista.append(self.http.urlqueryrecentwithcountry('steamcommunity.com',country,thread)) lista.append('steamcommunity.com') return lista #Calls the querie recent function on the HTTP class with diferent hosts def queryrecentdifhosts(self,thread): host = random.choice(self.log.list_hosts) lista = [] lista.append(self.http.queryrecent(host,thread)) lista.append(host) return lista #Calls the querie recent function on the HTTP class with diferent hosts and country codes def queryrecentdifhostsdifcountries(self,thread): host = random.choice(self.log.list_hosts) country = random.choice(self.log.list_countries) lista = [] lista.append(self.http.urlqueryrecentwithcountry(host,country,thread)) lista.append(host) return lista #Returns the id of the item with the number 1 position on your inventory or False if anything goes wrong def getpositiononeiteminv(self): return self.http.getpositiononeiteminv() def sellitem(self,assetid,price): return self.http.sellitem(assetid,price) def exportJsonToFile(self,json,file): try: with open('util/'+file+'.json', 'w') as outfile: ujson.dump(json, outfile) outfile.close() except ValueError: return False return True def writeInItemsTxt(self,item): return self.log.writeInItemsTxt(item) def delInItemsTxt(self,item): return self.log.delInItemsTxt(item) def getlistbuyitems(self): return self.log.list_items_to_buy #Returns the balance from the VAR in log.wallet_balance def getwalletbalancefromvar(self): return float(self.log.wallet_balance) #Loads the median prices from the file median_prices.json #Return false in case of error def loadmedianpricesfromfile(self): try: file = open('util/median_prices.json','r') self.list_median_prices = ujson.load(file) file.close() except ValueError: return False return self.list_median_prices def writetosellfile(self,status,content,item,price,thread_n,price_no_fee): return self.log.writetosellfile(status,content,item,price,thread_n,price_no_fee) def writetobuyfile(self,subtotal,fee,data_buy,listingid,key,responsecode,responsedict,thread_n): return self.log.writetobuyfile(subtotal,fee,data_buy,listingid,key,responsecode,responsedict,thread_n) def sellitemtest(self,assetid,price): return self.http.sellitem(assetid,price) #Writes to the wallet file the balance that is currently stored in the var Walletbalance #IT DOES NOT RETURN OR WRITE THE BALANCE DIRECTLY FROM STEAM def writetowalletadd(self,amount_add): temp = float(amount_add) + float(self.getwalletbalancefromvar()) temp = temp*100 return self.log.writetowallet(int(temp)) #Returns the lowest price for the item directly from Steam #In case of error returns False def getlowestprice(self,item): temp_item_priceover = self.http.querypriceoverview(item) if type(temp_item_priceover) == int: print "Erro ao obter preco mais baixo actualmente de " + item print "Status code da querie: " + str(temp_item_priceover) return False if type(temp_item_priceover) == bool: return False elif temp_item_priceover.has_key('lowest_price'): temp_lowest_price = temp_item_priceover['lowest_price'] if isinstance(temp_lowest_price, basestring): temp_lowest_price = temp_lowest_price.replace('€ ','').replace(',','.').replace('-','0') temp_lowest_price = "{0:.2f}".format(float(temp_lowest_price)) print temp_lowest_price return temp_lowest_price def buyitemtest(self,listing,subtotal,fee,currency,host): temp = self.http.buyitemTEST(listing,subtotal,fee,currency,host) print str(temp[0]) + '\n' print temp[1] #returns the median price for every item on the list that the user chooses at the start of the program #In case of error for any item, you will not get that item median price def getmedianitemlist(self): self.list_median_prices = {} for key in self.log.list_items_to_buy_unicode: temp_item_priceover = {} temp_item_priceover = self.http.querypriceoverview(key.encode('utf-8')) if type(temp_item_priceover) == int: print "Erro ao obter preco medio de " + key print "Status code da querie: " + str(temp_item_priceover) elif type(temp_item_priceover) == bool: print "Erro ao obter preco medio de " + key print "Status code da querie: " + str(temp_item_priceover) elif temp_item_priceover.has_key('median_price'): temp_median_price = temp_item_priceover['median_price'] if isinstance(temp_median_price, basestring): temp_median_price = temp_median_price.decode('unicode_escape').encode('ascii','ignore') temp_median_price = temp_median_price.replace(',','.').replace('-','0') temp_median_price = "{0:.2f}".format(float(temp_median_price)) self.list_median_prices[key] = float(temp_median_price) if self.list_median_prices.has_key(key): print 'O preco medio de ' + key + ' e: ' + str(self.list_median_prices[key]) return self.list_median_prices #returns wallet balance from steam website in float format def parsewalletbalance(self): soup = BeautifulSoup(self.http.getsteamwalletsite(),'html.parser') balance_soup = soup.find('span',{'id':'marketWalletBalanceAmount'}) if balance_soup != None: balance_soup = balance_soup.get_text() balance_str = balance_soup.encode('ascii','ignore').replace(',','.').replace('-','0') return float(balance_str) else: print "ERROR GETTING WALLET BALANCE, TRY TO LOGIN AGAIN!" return False #Vai buscar o valor o balance da minha carteira ao Steam diretamente #e se encontrar, atualiza a var wallet_balance def parsewalletbalanceandwrite(self): soup = BeautifulSoup(self.http.getsteamwalletsite(),'html.parser') balance_soup = soup.find('span',{'id':'marketWalletBalanceAmount'}) if balance_soup != None: balance_soup = balance_soup.get_text() balance_str = balance_soup.encode('ascii','ignore').replace(',','.').replace('-','0') self.log.writetowallet(float(balance_str)*100) return float(balance_str) else: print "ERROR GETTING WALLET BALANCE, MAYBE FAZER LOGIN RESOLVE ESTE PROBLEMA" return False #faz uma querie para ver as active listings que a conta tem #retorna as active_listings actuais ou false def getactivelistingsparsed(self): active_listings = self.http.getmyactivelistingsraw() active_listings_list = [] if type(active_listings) == dict: if active_listings.has_key('assets'): if type(active_listings['assets']) == dict: if active_listings['assets'].has_key('730'): active_listings = active_listings['assets']['730']['2'] for id in active_listings: active_listings_list.append(id) print type(active_listings_list) return active_listings_list else: return False else: return False #returns new active listings list or False def updateactivelistings(self): temp = self.getactivelistingsparsed() if temp != False: if type(self.log.writenewactivelistings(temp)) == list: print "NEW ACTIVE LISTINGS: \n" return self.log.ids_active_listings else: return False #ver se algum item nas active_listings vendeu #retorna uma nova active listings se sim #return a active listings se nao def seeifanyitemsold(self): active_listings = self.getactivelistingsparsed() if active_listings != False: if self.log.ids_active_listings != active_listings: self.log.writenewactivelistings(active_listings) print 'VENDI ITEMS!' return True else: print "ERROR" return False #todo def selltestfirst(self,item_name,id,price,trys): print 'selling item ' + item_name + ' with id ' + str(id) file_languages = open('util/languages.txt','r') languages = [line.rstrip('\n') for line in file_languages] sell_response = self.http.sellitem(id,float(price)) if sell_response[0] is 200: print 'sold item' i = 0 while i < trys: host = random.choice(self.log.list_hosts) recent_response = self.http.urlqueryrecentwithcountry(host,'US',0) language = random.choice(languages) item_response = self.http.urlqueryspecificitemind(host,item_name,language) if type(recent_response) is dict: try: for ids in recent_response['assets']['730']['2']: if id == ids: print "ENCONTREI O MEU ITEM NO RECENT COM O ID" + str(ids) except (KeyError,ValueError): print 'Error in finding the item on recent!' print if type(item_response) is dict: try: for ids in recent_response['assets']['730']['2']: if id == ids: print "ENCONTREI O MEU ITEM NO ITEM MODE COM O ID" + str(ids) except (KeyError,ValueError): print 'Error in finding the item on item mode!' i += 1 else: print 'failed to sell item!' print sell_response[0] print '\n' print sell_response[1] #Searches for kennyS cooblestone cases on the newly listed #If it finds one it trys to buy it if not nothing happens def searchkenny(self,recent): try: if recent.has_key('assets'): if recent['assets'].has_key('730'): for item_id in recent['assets']['730']['2']: if recent['assets']['730']['2'][item_id]['market_hash_name'] \ == 'ESL One Cologne 2015 Cobblestone Souvenir Package': if 'Kenny' in recent['assets']['730']['2'][item_id]['descriptions']['2']['value']: for listing_id in recent['listinginfo']: if recent['listinginfo'][listing_id]['asset']['id'] == item_id: if int(recent['listinginfo'][listing_id]['converted_currencyid']) == 2003: if int(recent['listinginfo'][listing_id]['converted_fee']) + \ int(recent['listinginfo'][listing_id]['converted_price']) <= 70000: if recent['listinginfo'][listing_id]['listingid'] != self.last_listing_buy: self.last_listing_buy_lock.acquire() self.last_listing_buy = recent['listinginfo'][listing_id]['listingid'] self.last_listing_buy_lock.release() print 'Estou prestes a entrar no acquire dos buys ON THREAD ' + str(0) self.buy_lock.acquire() try: print 'Entrei no acquire dos buys ON THREAD ' + str(0) temp = self.http.buyitem(recent['listinginfo'][listing_id]['listingid'], recent['listinginfo'][listing_id]['converted_price'], recent['listinginfo'][listing_id]['converted_fee'], recent['listinginfo'][listing_id]['converted_currencyid']) self.log.writetobuyfile(self.http.httputil.data_buy['subtotal'], self.http.httputil.data_buy['fee'], self.http.httputil.data_buy, recent['listinginfo'][listing_id]['listingid'], recent['assets']['730']['2'] [item_id]['market_hash_name'] ,temp[0],temp[1],0) self.buy_lock.release() print 'sai do lock dos buys ON THREAD ' + str(0) except: print "something went wrong buying a kennys case, f**k me!" self.buy_lock.release() except (ValueError,KeyError): print "Error in the kennyS function!" #----------------------------------------------THREADING----------------------------------------------------------- #Gets the retrieved JSON all ready for the buying routine def getfinallistfromrecent(self,recent_full): temp_full = self.getRecentTotalReady(recent_full) temp1_assets = self.getCleanAssetList(temp_full) temp2_assets = self.getlistassets(temp1_assets) temp1_listings = self.delNonCsgoListings(temp_full) temp2_listings = self.getCleanListinginfoListWithAsset(temp1_listings) temp3_listings = self.getcleanlistings(temp2_listings) temp4_listings = self.getlistlistings(temp3_listings) temp_final = self.getfinalrecentlist(temp2_assets,temp4_listings) return temp_final #This function is a thread def recentthread(self,http_interval,name): counter = 0 times = [] while True: time.sleep(http_interval) if self.dif_hosts == 'yes': if self.dif_countries == 'yes': recent = self.queryrecentdifhostsdifcountries(name) else: recent = self.queryrecentdifhosts(name) elif self.dif_hosts == 'no': if self.dif_countries == 'yes': recent = self.queryrecentdifcountries(name) else: recent = self.queryrecent(name) if recent[0] == False: print "CONN REFUSED ON THREAD " + str(name) +", sleeping..." time.sleep(30) pass elif recent[0] == -1: time.sleep(http_interval) elif recent[0] == -2: sleepe = random.randint(16,31) print 'TIMEOUT NA THREAD ' + str(name) + ' SLEEPING FOR ' + str(sleepe) + ' SECS' time.sleep(sleepe) elif type(recent[0]) == dict: buygoodresp = self.buyingroutine(self.getfinallistfromrecent(recent[0]),name,recent[1]) if buygoodresp[0] is True: id_item_pos_one = self.getpositiononeiteminv() lowest_price = self.getlowestprice(buygoodresp[2]) if ((float(lowest_price)+(0.02*float(lowest_price)))/float(buygoodresp[3])) >= 1.07: price_sell = float(lowest_price) price_sell_str = "{0:.2f}".format(price_sell) print price_sell else: price_sell = float(buygoodresp[1] * 0.94) price_sell_str = "{0:.2f}".format(price_sell) print price_sell price_sell_without_fee = price_sell/1.15 print price_sell_without_fee sell_response = self.sellitem(id_item_pos_one,float(price_sell_without_fee)) print 'Estou prestes a entrar no acquire dos sells on THREAD ' + str(name) self.sell_lock.acquire() print 'entrei no lock dos sells' if sell_response[0] == 200: self.log.writetosellfile(sell_response[0],sell_response[1],buygoodresp[2], price_sell_str,name,price_sell_without_fee) elif sell_response[0] == 502: self.log.writetosellfile(sell_response[0],sell_response[1],buygoodresp[2], price_sell_str,name,price_sell_without_fee) self.sell_lock.release() print 'sai do lock dos sells ON THREAD ' + str(name) counter += 1 if counter % 10 == 0: print 'A THREAD ' + str(name) + ' ESTA OK!!!!!!!!!!!!!!!!!!!!!!' elif counter % 250 == 0: self.write_active_listings_lock.acquire() if self.seeifanyitemsold(): self.parsewalletbalanceandwrite() self.write_active_listings_lock.release() print "CHEGUEI AS " + str(counter) + ' SLEEPING NOW!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' time.sleep(random.randint(10,20)) else: counter += 1 if counter % 10 == 0: print 'A THREAD ' + str(name) + ' ESTA OK!!!!!!!!!!!!!!!!!!!!!!' elif counter % 250 == 0: self.write_active_listings_lock.acquire() if self.seeifanyitemsold(): self.parsewalletbalanceandwrite() self.write_active_listings_lock.release() print "CHEGUEI AS " + str(counter) + ' SLEEPING NOW!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' time.sleep(random.randint(10,20)) time.sleep(http_interval) def executethreads(self,n_threads,http_interval): list_threads = [] for i in range(1,int(n_threads)+1): name = i t = threading.Thread(target=self.recentthread, args=(http_interval,name)) t.start() list_threads.append(t) while True: for thread in list_threads: if not thread.is_alive(): list_threads.remove(thread) print "Removed thread " + str(thread) time.sleep(900)
class Hangman: ''' This class provides the context for the graphics and logic modules, as well as handling input, menus, events and resources. The original intent was to let it serve as a model-view controller, where Logic represented the model and Graphics the main view. ''' def __init__(self): ''' Initializes window, canvas, gameplay options and menus, loads resources (settings, images, dictionaries) and sets up debugging. ''' # Window self.size = Size(650, 650) self.root = self.createWindow(self.size) self.icon = self.loadIcon('icon.png') # Internal settings self.validState = False # Not ready to accept guesses self.DEBUG = tk.BooleanVar(value=False) # Print debug messages self.VERBOSE = tk.BooleanVar(value=True) # Print verbose debug messages # Logging self.messages = [] self.logger = Logger('Hangman') # Resources self.dictData = self.loadDictionaries('data/dicts/dictionaries.json') self.dictNames = [name for name in self.dictData.keys()] self.flags = self.loadFlags() # Gameplay settings self.restartDelay = 1500 # Delay before new round begins (ms) self.revealWhenLost = False # Reveal the word when the game is lost # TODO: Save reference to current dict (?) self.DICT = tk.StringVar(value=choice(self.dictNames)) # Select random dictionary self.characterSet = self.dictData[self.DICT.get()]['characters'] # TODO: Make this dictionary-dependent # Menus self.menubar = self.createMenus() # Events self.bindEvents() # Game play self.graphics = Graphics(self.root, *self.size, characterSet=self.characterSet) # Renderer self.logic = Logic(self.graphics.chances) # Logic self.wordFeed = self.createWordFeed(self.DICT.get()) # Provides a stream of words and hints self.chances = self.graphics.chances # Initial number of chances for each round self.word = None # Initialized later on self.hint = None # Initialized later on # Audio self.effects = self.loadAudio() def play(self): ''' Starts the game ''' self.restart() self.root.mainloop() def createWindow(self, size): ''' As per the title ''' root = tk.Tk() root.resizable(width=False, height=False) root.title('Hangman') return root def createMenus(self): ''' As per the title ''' # TODO: Nested dict or JSON menu definition (?) # TODO: Desperately needs a clean-up (...) menubar = tk.Menu(self.root) # New game menubar.add_command(label='New', command=self.restart) # Settings settings = tk.Menu(menubar, tearoff=0) settings.add_command(label='Difficulty', command=lambda: print('Moderate')) # Languages languages = tk.Menu(settings, tearoff=0) self.DICT.trace('w', lambda *args, var=self.DICT: self.setDictionary(var.get())) # TODO: Extract traces # TODO: Use appropriate flag for N, name in enumerate(self.dictData.keys()): code = self.dictData[name]['iso'] # Language code languages.add_radiobutton(label=name, image=self.flags[code], compound='left', var=self.DICT, value=name) else: self.logger.log('Found %d dictionaries.' % (N+1), kind='log') settings.add_cascade(label='Language', menu=languages) menubar.add_cascade(label='Settings', menu=settings) # About box menubar.add_command(label='About', command=self.about) # Dev menu debug = tk.Menu(menubar, tearoff=0) debug.add_checkbutton(label='Debug', onvalue=True, offvalue=False, variable=self.DEBUG) debug.add_checkbutton(label='Verbose', onvalue=True, offvalue=False, variable=self.VERBOSE) menubar.add_cascade(label='Dev', menu=debug) # Quit menubar.add_command(label='Quit', command=self.quit) # Attach to window self.root.config(menu=menubar) return menubar def bindEvents(self): ''' Binds callbacks to events ''' self.root.bind('<Escape>', lambda e: self.quit()) self.root.bind('<Key>', lambda e: self.onKeyDown(e)) def onKeyDown(self, event): ''' Responds to key presses ''' # TODO: Make sure guesses can't be made in a transitory state (✓) # TODO: Tidy up # TODO: Shortcuts, key bindings with JSON (?) # Validate the guess # Make sure the game is in a valid state (eg. not between to rounds) if not self.validState: self.logger.log('Cannot accept guesses right now', kind='log') return elif not self.validGuess(event.char): return else: self.guess(event.char) def about(self): ''' Shows an about box ''' messagebox.askokcancel('About', 'Hangman\nJonatan H Sundqvist\nJuly 2014') def loadAudio(self): ''' Initializes mixer and loads sound effects ''' mixer.init() files = ['strangled.wav', 'ding.wav'] return namedtuple('Effects', ['lose', 'win'])(*map(lambda fn: mixer.Sound('data/audio/%s' % fn), files)) def loadFlags(self): ''' Loads all flag files and creates a map between those and their respective ISO language codes ''' codes = [('en-uk', 'UK.png'), ('es-es', 'Spain.png'), ('in', 'India.png'), ('sv-sv', 'sv.png'), ('en-us', 'USA.png')] # Maps language codes to flags flags = {} for iso, fn in codes: image = Image.open('data/flags/%s' % fn) image.thumbnail((16,16), Image.ANTIALIAS) flags[iso] = ImageTk.PhotoImage(image) return flags def loadIcon(self, fn): ''' Loads and sets the title bar icon ''' icon = ImageTk.PhotoImage(Image.open(fn)) self.root.call('wm', 'iconphoto', self.root._w, icon) return icon def loadDictionaries(self, fn): ''' Loads JSON dictionary meta data ''' # TODO: Dot notation # TODO: Load associated resources for convenience (?) with open(fn, 'r', encoding='utf-8') as dicts: return json.load(dicts) def setDictionary(self, name): ''' Sets the dictionary specified by the name and restarts ''' self.logger.log('Changing dictionary to %s' % name, kind='log') self.wordFeed = self.createWordFeed(name) self.characterSet = self.dictData[name]['characters'] self.graphics.changeCharacterSet(self.characterSet) self.restart() # TODO: Research Python annotation syntax # TOOD: Check if ST3 has support for the same #def guess(self : str, letter : str) -> None: def guess(self, letter): ''' Guesses one letter ''' # TODO: Write a slightly more helpful docstring # TODO: Clean this up result = self.logic.guess(letter) self.logger.log('\'%s\' is a %s!' % (letter.upper(), result), kind='log') self.graphics.guess(letter, result in ('MATCH', 'WIN'), str(self.logic)), # TODO: Let Graphics take care of the representation for us (?) # TODO: Clean up the 'switch' logic #{'WIN': self.win, 'LOSE': self.lose}.get(result, lambda: None)() # return { ('MATCH', 'WIN'): } if result == 'WIN': self.win() elif result == 'LOSE': self.lose() def validGuess(self, letter): ''' Determines if a letter is a valid guess ''' # TODO: Make this configurable (list of requirements?) # Normalize input letter = letter.upper() # Check all requirements if letter not in self.characterSet: # Make sure the character is a guessable letter self.logger.log('\'%s\' is not in the character set!' % letter, kind='log') return False elif len(letter) != 1: # Make sure the guess is only one letter self.logger.log('\'%s\' does not have exactly one letter!' % letter, kind='log') return False elif self.logic.hasGuessed(letter): # Make sure it's not a repeat guess self.logger.log('\'%s\' has already been guessed!' % letter, kind='log') return False else: return True def win(self): ''' Victorious feedback, schedules the next round ''' self.logger.log('Phew. You figured it out!', kind='log') self.effects.win.play() self.scheduleRestart() def lose(self): ''' Failure feedback, schedules the next round ''' # TODO: Show correct word before restarting (?) self.logger.log('You\'ve been hanged. Requiescat in pace!', kind='log') self.effects.lose.play() if self.revealWhenLost: self.graphics.setWord(self.word) # Reveal answer self.scheduleRestart() def scheduleRestart(self): ''' Schedules a new round and disables guessing in the interim ''' self.validState = False # Disable guessing between rounds self.root.after(self.restartDelay, self.restart) def restart(self): ''' Starts a new game ''' self.logger.log('\n{0}\n{1:^40}\n{0}\n'.format('-'*40, 'NEW GAME'), kind='log', identify=False) # TODO: Enable identify options in Logger.log self.word, self.hint = next(self.wordFeed) self.graphics.showHint(self.hint) self.logic.new(self.word) self.graphics.play(str(self.logic)) self.validState = True # Ready to accept guesses again def quit(self, message=None, prompt=False): ''' Exits the application ''' # TODO: Find a way to close Python #print('\n'.join(self.messages)) self.root.quit() def createWordFeed(self, name): ''' Creates a word feed from the dictionary specified by the name ''' # TODO: Give class a reference to words (?) # TODO: Wise to hard-code path (?) # TODO: Handle incorrectly structured dictionaries self.logger.log('Creating word feed from \'{name}\'.'.format(name=name), kind='log') fn = self.dictData[name]['file'] with open('data/dicts/%s' % fn, 'r', encoding='utf-8') as wordFile: words = wordFile.read().split('\n') while True: try: line = choice(words) word, hint = line.split('|') # Word|Hint yield word, hint except ValueError as e: words.remove(line) # Remove the culprit from the word feed self.logger.log('Removing invalid definition ({0}).'.format(line), kind='error')
class PlanetApp(App): # SCREENS AND SCREENMANAGER screenmanager = ObjectProperty(None) mainscreen = ObjectProperty(None) menuscreen = ObjectProperty(None) settingsscreen = ObjectProperty(None) savegamescreen = ObjectProperty(None) creditsscreen = ObjectProperty(None) logic = ObjectProperty(None) def build(self): self.title = 'PocketCosmos' self.calc_iconsize() self.settings = ConfigController('settings.json') self.sound_manager = SoundManager(settings=self.settings) self.logic = Logic( settings=self.settings, sound_manager=self.sound_manager ) self.screenmanager = ScreenManager() self.mainscreen = MainScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='main' ) # MenuScreen does not need logic self.menuscreen = MenuScreen(name='menu') self.settingsscreen = SettingsScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='settings' ) self.savegamescreen = SavegameScreen( logic=self.logic, iconsize=self.iconsize, iconratio_x=self.iconratio_x, iconratio_y=self.iconratio_y, name='savegames' ) self.creditsscreen = CreditsScreen( iconsize=self.iconsize, name='credits' ) # order adding here reflects which screen is shown first! self.screenmanager.add_widget(self.menuscreen) self.screenmanager.add_widget(self.mainscreen) self.screenmanager.add_widget(self.settingsscreen) self.screenmanager.add_widget(self.savegamescreen) self.screenmanager.add_widget(self.creditsscreen) self.logic.apply_settings() return self.screenmanager def on_start(self): self.load_game() def on_stop(self): self.settings.save() self.save_game() def load_game(self, slot='current'): save_name = 'save_{slot}.json'.format(slot=slot) save_exists = os.path.exists(save_name) if save_exists: self.logic.reset_planets(self) with open(save_name, 'r') as save_file: json_d = save_file.readline() planets_d = json.loads(json_d) for planet_d in planets_d.values(): # make tuples from pos and vel pos = (planet_d['position_x'], planet_d['position_y']) vel = (planet_d['velocity_x'], planet_d['velocity_y']) self.logic.add_body(pos=pos, vel=vel, **planet_d) def save_game(self, slot='current'): # make deepcopy to avoid deleting widget ref from actual logic.planets #planets_d = copy.deepcopy(self.logic.planets) planets_d = { index: { key: value for key, value in item.items() if key != 'widget' } for index, item in self.logic.planets.items() } # delete widget reference, it's not needed in savegames ''' for index in planets_d: planets_d[index].pop('widget') ''' json_d = json.dumps(planets_d) with open('save_{}.json'.format(slot), 'w') as save_file: save_file.write(json_d) def scan_savegames(self): save_mtimes = {} for i in range(1, 6): save_name = 'save_{}.json'.format(i) save_exists = os.path.exists(save_name) if save_exists: time_raw = os.path.getmtime(save_name) time_save = time.ctime(time_raw) save_mtimes[i] = str(time_save) else: save_mtimes[i] = '<Empty>' return save_mtimes def calc_iconsize(self): # TODO: is this neccessary? icon_count = 8 window_height = Window.height window_width = Window.width iconsize = window_height / icon_count self.iconratio_y = float(iconsize) / window_height self.iconratio_x = float(iconsize) / window_width self.iconsize = iconsize def build_config(self, config): config.setdefaults('graphics', { 'maxfps': '30' })
def main() : env = Logic(SCREEN_SIZE, SCREEN_CAPTION) env.run()
@author: Gabriel E. Muñoz - [email protected] """ """ The Requests class will handle HTTP requests. """ import SimpleHTTPServer import re from variables import SERIAL_PORT from logic import Logic logic = Logic(SERIAL_PORT) logic.initialize() class Requests(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): path = self.path pathSplitted = re.split("/", path) good_path = True response = "" if len(pathSplitted) == 2 and pathSplitted[1] != "": verb = pathSplitted[1] if verb == "more_x":