def getHistoryResp(self, state, data): # On vérifie qu'il n'y a pas eu d'erreur technique if state == 1: if self.verifyResponse(data[:4]): data = data[4:] try: from Manager.GameManager import GameManager # On récupère les informations des games while len(data) >= calcsize("=i50siii?"): response = struct.unpack('=i50siii?', data) game = Game() game.id = response[0] game.opponent = response[1] game.created = response[2] game.victory = response[7] self.app.gameManager.user.games.append(game) data = data[calcsize("=i50siii?"):] self.app.gameManager.nbLoading -= 1 except Exception as ex: raise Exception("Impossible de lire les données : " + ex.message) else: raise Exception("La récupèration des informations a échoué") else: raise Exception("La récupèration des informations a échoué")
def __init__(self): self.game = Game() self.snake_ctrl = ControlSnake() self.food_ctrl = ControlFood() self.score = self.game.score self.speed = self.game.speed self.level = self.game.level
class Controller(object): def __init__(self): self.game = Game() def startGame(self): self.game.start() def getCurrentPlayersHand(self): return self.game.getCurrentPlayersHand()
def __init__(self, io_controller=None, delay=None): self.handler = ErrorHandler(method="__init__", module="AbstractController") self.handler.log(message="Validating IO Controller") self.check_controller_defined(io_controller=io_controller) self.handler.log(message="Initializing variables") self.available_modes = None self.game_ready = False self.delay = delay or 0 self.io_controller = io_controller self.handler.log(message="Instantiating Game object") self.game = Game(callback_notifier=self.io_controller.report_status)
def get_keyed_data(self, persist_data, key): ret = {} profile = None game = None try: profile = Profile.select().where( (Profile.id == persist_data["profileid"])).get() game = Game.select().where( (Game.id == persist_data["game_id"])).get() except (PersistKeyedData.DoesNotExist, Profile.DoesNotExist) as e: pass try: where = (PersistKeyedData.key_name == key) & ( PersistKeyedData.data_index == persist_data["data_index"]) & ( PersistKeyedData.persist_type == persist_data["data_type"] ) & (PersistKeyedData.profileid == profile.id) & (PersistKeyedData.gameid == game.id) if "modified_since" in persist_data: where = (where) & (PersistKeyedData.modified > persist_data["modified_since"]) data_entry = PersistKeyedData.select().where(where).get() ret = model_to_dict(data_entry) ret["modified"] = calendar.timegm(ret["modified"].utctimetuple()) del ret["profile"] except (PersistKeyedData.DoesNotExist) as e: pass return ret
def set_persist_raw_data(self, persist_data): profile = None game = None try: profile = Profile.select().where( (Profile.id == persist_data["profileid"])).get() game = Game.select().where( (Game.id == persist_data["game_id"])).get() except (PersistKeyedData.DoesNotExist, Profile.DoesNotExist) as e: pass try: data_entry = PersistData.select().where( (PersistData.data_index == persist_data["data_index"]) & (PersistData.persist_type == persist_data["data_type"]) & (PersistData.profileid == profile.id) & (PersistData.gameid == game.id)).get() data_entry.base64Data = persist_data["data"] data_entry.modified = datetime.utcnow() data_entry.save() except (PersistData.DoesNotExist) as e: data_entry = PersistData.create( base64Data=persist_data["data"], data_index=persist_data["data_index"], persist_type=persist_data["data_type"], modified=datetime.utcnow(), profileid=persist_data["profileid"], gameid=persist_data["game_id"]) ret = model_to_dict(data_entry) del ret["profile"] ret["modified"] = calendar.timegm(ret["modified"].utctimetuple()) return ret
def gog_id_exists(self, gog_id): db = sqlite3.connect(self.dataFile) c = db.cursor() c.execute( 'SELECT title, description, run_platforms, genres, store, storepage, steam_appid, gog_id, game_internal_id, category_id from games where gog_id = ?', (gog_id, )) games_raw = c.fetchall() c.close() if (games_raw and len(games_raw) > 0): g = games_raw[0] game = Game(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8]) game.set_category(g[9]) return game else: return None
def graficar(): if input_n.get_value().isdigit() and input_N.get_value().isdigit() \ and input_m.get_value().isdigit(): n = int(input_n.get_value()) N = int(input_N.get_value()) m = int(input_m.get_value()) if n > 1 and N < n * n and m > 1: if n <= 300: num_gens = np.arange(1, m + 1) num_vivos = np.zeros(m, dtype=int) num_nacim = np.zeros(m, dtype=int) num_muertes = np.zeros(m, dtype=int) juego = Game(n, N) iterador = iter(juego) num_vivos[0] = len(juego.inicio.vivos()) num_nacim[0] = len(juego.inicio.nacimientos()) num_muertes[0] = len(juego.inicio.muertes()) k = 1 while k < m: try: generacion = next(iterador) num_vivos[k] = len(generacion.vivos()) num_nacim[k] = len(generacion.nacimientos()) num_muertes[k] = len(generacion.muertes()) except StopIteration: break k += 1 plt.style.use('fivethirtyeight') plt.plot(num_gens, num_vivos, color='g', label='Vivos') plt.plot(num_gens, num_nacim, color='y', label='Nacimientos') plt.plot(num_gens, num_muertes, color='r', label='Muertes') plt.xlabel('Número de generaciones') plt.ylabel('Frecuencia') plt.title('Análisis del Juego de la Vida por generación') plt.legend() plt.tight_layout() plt.show() else: thorpy.launch_blocking_alert( title='Error', text= '¡Lo sentimos! El tamaño del tablero no puede ser mayor a 300.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text= 'Los valores intruducidos deben ser positivos mayores a 1. ' 'Además, el número de células iniciales (N) debe ser menor a n^2.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text='Los valores introducidos deben ser numéricos.', parent=None)
def handle_delete_group(self, request): group_data = request["group"] game = Game.select().where(Game.id == group_data["gameid"]).get() count = GameGroup.delete().where( GameGroup.groupid == group_data["groupid"]).execute() self.redis_group_ctx.delete("{}:{}:".format(game.gamename, group_data["groupid"])) self.redis_group_ctx.delete("{}:{}:custkeys".format( game.gamename, group_data["groupid"])) return {"success": True, "count": count}
def handle_update_game(self, request): game_data = request["game"] game = Game.select().where(Game.id == game_data["id"]).get() old_data = model_to_dict(game) for key in game_data: if key != "id": setattr(game, key, game_data[key]) game.save() self.sync_game_to_redis(model_to_dict(game), old_data) return {"success": True}
def on_ok(self): #platforms = self.gameplatforms._contained_widget.get_selected_objects(self.gameplatforms); if not self.gametitle.value: npyscreen.notify_confirm("Title is required", "Error") else: platformString = "" #all_platforms = self.parentApp.gamedata.platforms; platform_selections = self.gameplatforms._contained_widget.get_selected_objects( self.gameplatforms) if (platform_selections and len(platform_selections) > 0): for pselection in platform_selections: platformString += str(pselection.platform_id) + "," storesString = "" stores_selections = self.gamestores._contained_widget.get_selected_objects( self.gamestores) if (stores_selections and len(stores_selections) > 0): for sselection in stores_selections: storesString += str(sselection.store_id) + "," description = '\n'.join(self.gamedescription.values) storepage = self.gamestorepage.value genres = self.unique(self.gamegenre.values) genres = '\n'.join(genres) category = self.gamecategory._contained_widget.get_selected_objects( self.gamecategory)[0].category_id if (not self.value): game = Game(self.gametitle.value, description, platformString, genres, storesString, storepage, None, None, None) game.set_category(category - 1) self.parentApp.gamedata.add_game(game) else: game_old = self.value game_new = Game(self.gametitle.value, description, platformString, genres, storesString, storepage, game_old.steam_appid, game_old.gog_id, game_old.record_id) game_new.set_category(category - 1) self.parentApp.gamedata.update_game(game_new) self.parentApp.gamedata.load_games() self.parentApp.switchFormPrevious()
def sync_group_to_redis(self, new_data, old_data): new_game = Game.select().where(Game.id == new_data["gameid"]).get() old_game = Game.select().where(Game.id == old_data["gameid"]).get() self.redis_group_ctx.delete("{}:{}:".format(old_game.gamename, old_data["groupid"])) self.redis_group_ctx.delete("{}:{}:custkeys".format( old_game.gamename, old_data["groupid"])) redis_key = "{}:{}:".format(new_game.gamename, new_data["groupid"]) self.redis_group_ctx.hset(redis_key, "gameid", new_data["gameid"]) self.redis_group_ctx.hset(redis_key, "groupid", new_data["groupid"]) self.redis_group_ctx.hset(redis_key, "maxwaiting", new_data["maxwaiting"]) self.redis_group_ctx.hset(redis_key, "password", 0) self.redis_group_ctx.hset(redis_key, "numwaiting", 0) other_str = new_data["other"] other_data = other_str.split("\\")[1::] it = iter(other_data) for x in it: key = x val = next(it) self.redis_group_ctx.hset("{}custkeys".format(redis_key), key, val)
def get_data_from_table_row(row): row_data = list(filter(lambda x: x != "\n", row.contents)) if len(row_data) != 4: return None game = Game() game.name, game.link = get_name_link(row_data[0]) game.dev, game.publisher = get_dev_pub(row_data[1]) game.dates = get_dates(row_data[2]) game.trailer_link = get_trailer_link(row_data[3]) return game
def handle_get_games(self, request): ret = [] where_statement = 1 == 1 if "where" in request: where_req = request["where"] if "id" in where_req: where_statement = (where_statement) & (Game.id == int( where_req["id"])) elif "gamename" in where_req: where_statement = where_statement & (Game.gamename == where_req["gamename"]) games = Game.select().where(where_statement) for game in games: ret.append(model_to_dict(game)) return ret
def load_games(self, ): db = sqlite3.connect(self.dataFile) c = db.cursor() c.execute( 'SELECT title, description, run_platforms, genres, store, storepage, steam_appid, gog_id, game_internal_id, category_id, created_at, updated_at from games ORDER BY title ASC' ) games_raw = c.fetchall() c.close() games_new = [] for g in games_raw: new_game = Game(g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8]) new_game.set_category(g[9]) new_game.set_created(g[10]) new_game.set_updated(g[11]) games_new.append(new_game) self.games = games_new
class ControlGame: def __init__(self): self.game = Game() self.snake_ctrl = ControlSnake() self.food_ctrl = ControlFood() self.score = self.game.score self.speed = self.game.speed self.level = self.game.level def start(self): self.game.start() def quit(self): self.game.quit() def up_fps(self): self.game.set_fps(self.speed) def move(self, way): self.snake_ctrl.moviment(way) def chk_move(self, view): if self.snake_ctrl.chk_moviment(self.food_ctrl.check_food()): self.food_ctrl.set_devoured(view) self.score += 1 if self.snake_ctrl.chk_level(self.speed, self.level): self.level += 1 self.speed += 1 self.up_fps() return True def chk_clash(self): return self.snake_ctrl.clash() def draw(self, view): self.snake_ctrl.draw(view) self.food_ctrl.draw(view) def lose(self): self.game.lose()
def validate_request(self, xml_tree): request_info = {"success": False} game_id = xml_tree.find("{http://gamespy.net/sake}gameid").text secretkey = xml_tree.find("{http://gamespy.net/sake}secretKey").text loginTicket = xml_tree.find( "{http://gamespy.net/sake}loginTicket").text #gameid = xml_tree.find() #print("GameID: {}\n".format(game_id)) game = Game.select().where(Game.id == game_id).get() profile = Profile.select().where(Profile.id == 10000).get() #print("Profile: {}\nGame: {}\n{} - {}\n".format(profile,game, game.secretkey, secretkey)) if game.secretkey != secretkey: return request_info request_info["success"] = True request_info["game"] = game request_info["profile"] = profile return request_info
def empezar_onclick(): nonlocal n, N, LARGO, ALTO, DIMENSION_VENTANA, juego, \ generacion, pantalla, is_paused, pause_play, iterator, list if input_n.get_value().isdigit() and input_N.get_value().isdigit(): _n = int(input_n.get_value()) _N = int(input_N.get_value()) if _n > 1 and _N < _n * _n: if _n <= 300: n = _n N = _N LARGO = ALTO = (601 - (n + 1)) // n # Se actualiza la dimension de la ventana a la necesaria. DIMENSION_VENTANA = [900, n * LARGO + (n + 1) * MARGEN] juego = Game(n, N) pantalla = pygame.display.set_mode(DIMENSION_VENTANA) is_paused = True pause_play = pygame.image.load( '../img/play.png').convert_alpha() iterator = iter(juego) list = juego.inicio.vivos() else: thorpy.launch_blocking_alert( title='Error', text= '¡Lo sentimos! El tamaño del tablero no puede ser mayor a 300.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text= 'Los valores intruducidos deben ser positivos mayores a 1.' ' Además, el número de células iniciales (N) debe ser menor a n^2.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text='Los valores introducidos deben ser numéricos.', parent=None)
def update_or_create_keyed_data(self, persist_data, key, value): profile = None game = None try: profile = Profile.select().where( (Profile.id == persist_data["profileid"])).get() game = Game.select().where( (Game.id == persist_data["game_id"])).get() except (Profile.DoesNotExist, Game.DoesNotExist) as e: pass try: data_entry = PersistKeyedData.select().where( (PersistKeyedData.key_name == key) & (PersistKeyedData.data_index == persist_data["data_index"]) & (PersistKeyedData.persist_type == persist_data["data_type"]) & (PersistKeyedData.profileid == profile.id) & (PersistKeyedData.gameid == game.id)).get() data_entry.key_value = value data_entry.modified = datetime.utcnow() data_entry.save() except (PersistKeyedData.DoesNotExist) as e: data_entry = PersistKeyedData.create( key_name=key, key_value=value, data_index=persist_data["data_index"], persist_type=persist_data["data_type"], modified=datetime.utcnow(), profileid=persist_data["profileid"], gameid=persist_data["game_id"]) ret = model_to_dict(data_entry) del ret["profile"] ret["modified"] = calendar.timegm(ret["modified"].utctimetuple()) return ret
def run(self): while self.thread_run: content = self.get_games() total_count = content["total_count"] games = content["games"] current_count = 0 for meta_game in games: current_count = current_count + 1 temp_game = self.get_game(meta_game["appid"]) if(not temp_game): continue title = temp_game['name'] description = temp_game['short_description'] src_platforms = temp_game['platforms'] platforms = self.gamedata.platforms run_platforms = [] for platform in platforms: key = platform.name.lower() if('linux' in key): key = 'linux' if('mac' in key): key = 'mac' if(key in src_platforms): if src_platforms[key]: run_platforms.append(str(platform.platform_id)) run_platforms = ','.join(run_platforms) genres = [] if('genres' in temp_game): src_genres = temp_game['genres'] for genre in src_genres: if ('description' in genre): genres.append(genre['description']) if('categories' in temp_game): src_categories = temp_game['categories'] for category in src_categories: genres.append(category['description']) genres = '\n'.join(genres) # Get steam store = "" for st in self.gamedata.stores: if(st.name.lower() == 'steam'): store = st.store_id # create steampage: storepage = 'https://store.steampowered.com/app/' + \ str(meta_game["appid"]) steam_appid = str(meta_game["appid"]) game = Game(title, description, run_platforms, genres, store, storepage, steam_appid, None, None) game.set_category(0) record = self.gamedata.steam_appid_exists(steam_appid) if(record): game.record_id = record.record_id game.set_category(record.category); self.gamedata.update_game(game) else: self.gamedata.add_game(game) percentage = (current_count / total_count) * 100 self.loader.set_value(percentage) self.loader.update() self.refresh() self.thread_run = False
def start(): def dibujar_tablero(elementos): for row in range(n): for col in range(n): pygame.draw.rect(pantalla, BLANCO, [ MARGEN + (MARGEN + LARGO) * col, MARGEN + (MARGEN + ALTO) * row, LARGO, ALTO ]) for tupla in elementos: fila, columna = tupla pygame.draw.rect(pantalla, ROJO, [ MARGEN + (MARGEN + LARGO) * columna, MARGEN + (MARGEN + ALTO) * fila, LARGO, ALTO ]) def empezar_onclick(): nonlocal n, N, LARGO, ALTO, DIMENSION_VENTANA, juego, \ generacion, pantalla, is_paused, pause_play, iterator, list if input_n.get_value().isdigit() and input_N.get_value().isdigit(): _n = int(input_n.get_value()) _N = int(input_N.get_value()) if _n > 1 and _N < _n * _n: if _n <= 300: n = _n N = _N LARGO = ALTO = (601 - (n + 1)) // n # Se actualiza la dimension de la ventana a la necesaria. DIMENSION_VENTANA = [900, n * LARGO + (n + 1) * MARGEN] juego = Game(n, N) pantalla = pygame.display.set_mode(DIMENSION_VENTANA) is_paused = True pause_play = pygame.image.load( '../img/play.png').convert_alpha() iterator = iter(juego) list = juego.inicio.vivos() else: thorpy.launch_blocking_alert( title='Error', text= '¡Lo sentimos! El tamaño del tablero no puede ser mayor a 300.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text= 'Los valores intruducidos deben ser positivos mayores a 1.' ' Además, el número de células iniciales (N) debe ser menor a n^2.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text='Los valores introducidos deben ser numéricos.', parent=None) # Definimos algunos colores NEGRO = (0, 0, 0) BLANCO = (255, 255, 255) VERDE = (0, 255, 0) ROJO = (255, 0, 0) # Establecemos un tamaño del tablero n*n (max = 300) n = 10 # Establecemos un número de células iniciales N = 30 # Establecemos el LARGO y ALTO de la pantalla DIMENSION_VENTANA = [900, 601] # Establecemos el margen entre las celdas. MARGEN = 1 # Calculamos el LARGO y ALTO de cada celda de la retícula. LARGO = ALTO = (DIMENSION_VENTANA[1] - (n + 1)) // n # Se actualiza la dimension de la ventana a la necesaria. DIMENSION_VENTANA = [900, n * LARGO + (n + 1) * MARGEN] juego = Game(n, N) # Inicializamos pygame pygame.init() # Centramos la ventana os.environ['SDL_VIDEO_CENTERED'] = '1' pantalla = pygame.display.set_mode(DIMENSION_VENTANA) # Establecemos el título de la ventana. pygame.display.set_caption('Juego de la vida de Conway') # Iteramos hasta que el usuario pulse el botón de salir. done = False # Lo usamos para establecer cuán rápido se refresca la pantalla. reloj = pygame.time.Clock() # Establecemos el fondo de pantalla. pantalla.fill(NEGRO) # Creamos imagen (convert_alpha: fondo transparente) pause_play = pygame.image.load('../img/play.png').convert_alpha() rect_pause_play = pantalla.blit(pause_play, (700, 260)) nextt = pygame.image.load('../img/next.png').convert_alpha() rect_next = pantalla.blit(nextt, (750, 260)) is_paused = True # ThorPy elements text = thorpy.make_text('Digite los valores de entrada:') input_n = thorpy.Inserter(name='Tamaño de tablero (n): ', value=str(n)) input_N = thorpy.Inserter(name='Núm. células iniciales (N): ', value=str(N)) button = thorpy.make_button('Empezar', func=empezar_onclick) box = thorpy.Box(elements=[text, input_n, input_N, button]) # we regroup all elements on a menu, even if we do not launch the menu menu = thorpy.Menu(box) # important : set the screen as surface for all elements for element in menu.get_population(): element.surface = pantalla # use the elements normally... box.set_topleft((620, 40)) box.blit() box.update() iterator = iter(juego) list = juego.inicio.vivos() pygame.display.flip() # -------- Ciclo Principal del Programa----------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: # El usuario presiona el ratón. Se obtiene su posición. pos = pygame.mouse.get_pos() if rect_pause_play.collidepoint(pos): if is_paused: pause_play = pygame.image.load( '../img/pause.png').convert_alpha() else: pause_play = pygame.image.load( '../img/play.png').convert_alpha() is_paused = not is_paused elif rect_next.collidepoint(pos): try: generacion = next(iterator) list = generacion.vivos() except StopIteration: pass menu.react(event) # the menu automatically integrate your elements pantalla.fill(NEGRO) if not is_paused: try: generacion = next(iterator) list = generacion.vivos() except StopIteration: pass dibujar_tablero(list) rect_pause_play = pantalla.blit(pause_play, (700, 260)) rect_next = pantalla.blit(nextt, (750, 260)) box.blit() box.update() # Avanzamos y actualizamos la pantalla con lo que hemos dibujado. pygame.display.flip() # Limitamos a 5 fotogramas por segundo. reloj.tick(5) # Cerramos la ventana y salimos. pygame.quit() Menu.start()
def __init__(self): self.game = Game()
def gog_update(self, platforms, store_id): media_type = GOG_MEDIA_TYPE_GAME items = [] i = 0 self.load_cookies() api_url = GOG_ACCOUNT_URL api_url += "/getFilteredProducts" done = False while not done: i += 1 url = api_url + "?" + urlencode({'mediaType': media_type, 'sortBy': 'title', 'page': str(i)}) with self.request(url, delay=0) as data_request: reader = codecs.getreader("utf-8") try: json_data = json.load(reader(data_request)) except ValueError: raise SystemExit(1) for item_json_data in json_data['products']: if item_json_data.get('isHidden', False) is True: continue gog_id = str(item_json_data['id']) title = item_json_data['title'] description = item_json_data['slug'] genre = item_json_data['category'] store_url = "https://www.gog.com" + item_json_data['url'] src_platforms = item_json_data['worksOn'] run_platforms = [] for platform in platforms: key = platform.name.lower() if('linux' in key): key = 'linux' if('mac' in key): key = 'mac' lower_src_platforms = dict( (k.lower(), v) for k, v in src_platforms.items()) if(key in lower_src_platforms): if lower_src_platforms[key]: run_platforms.append(str(platform.platform_id)) run_platforms = ','.join(run_platforms) game = Game(title, description, run_platforms, genre, store_id, store_url, None, gog_id, None) game.set_category(0) items.append(game) if i >= json_data['totalPages']: done = True return items
class AbstractController(ABC): SIGNAL_ERROR = -2 SIGNAL_BREAK = -1 SIGNAL_SUCCESS = 0 SIGNAL_FINISH = 1 def __init__(self, io_controller=None, delay=None): self.handler = ErrorHandler(method="__init__", module="AbstractController") self.handler.log(message="Validating IO Controller") self.check_controller_defined(io_controller=io_controller) self.handler.log(message="Initializing variables") self.available_modes = None self.game_ready = False self.delay = delay or 0 self.io_controller = io_controller self.handler.log(message="Instantiating Game object") self.game = Game(callback_notifier=self.io_controller.report_status) # # Abstract Methods # @abc.abstractmethod def play(self): self.handler.method = "play" self.handler.log(message="Playing game") self.handler.log(message="Validating IO Controller") self.check_controller_defined(io_controller=self.io_controller) self.handler.log(message="Show instructions") self.io_controller.instructions() self.handler.log(message="Construct any IO structures") self.io_controller.construct(callback=self) self.handler.log(message="Draw the screen") self.io_controller.update_screen() # Ask if the user wants to execute self.handler.log(message="Asking user if they want to play.") if not self.io_controller.want_to_play(): # At this point, the user has said they don't want to execute. So # give a farewell and then return control to app.py. self.handler.log(message="User did not want to play.") self.io_controller.finish("Okay, come back soon!") return self.SIGNAL_BREAK self.io_controller.report_status("Connecting to the game server...") # The user has started a game, so ask the Game model to create a new # game object; note, no game is started yet, that only happens when # a call to game.get_game is made. Also, a callback notifier is # passed to enable the object to perform user AbstractView. # game = Game(callback_notifier=self.io_controller.report_status) # sleep(self.delay) # Get the Game model to check if the server is ready. It will take # configuration from os environment variables. See Game.py for more # information. if not self.game.check_game_server_ready(): # The Game model couldn't reach the server or did not receive # a ready response, so report to the user and return control # to app.py. self.io_controller.report_error( "Sorry, the cowbull game isn't available right now; " "please come back later. The issue has been logged.") return self.io_controller.report_status( "Connected to game server. Fetching available game modes...") sleep(self.delay) # Ask the Game model to get a list of available modes. The Game # servers may have different modes, so the Game model always # checks. modes, error_detail = self.game.get_modes() sleep(self.delay) if not modes: # For some reason (contained in the error detail), the modes # weren't returned properly; therefore, the game cannot execute. self.io_controller.report_error(error_detail) return self.available_modes = [str(i['mode']) for i in modes] self.io_controller.report_status( "{} ready; modes available are: {}".format( self.game.game_server["host"], ', '.join(self.available_modes))) self.game_ready = True @abc.abstractmethod def make_guess(self, line_number=None): self.check_controller_defined(io_controller=self.io_controller) self.check_game_in_play() # Get the guesses from the user. input_list = self.io_controller.get_guess( game_digits=self.game.game_digits, default_answer=self.game.list_of_digits()) # If a sentinel (-1) is returned, then the user typed quit # during entering the numbers. if input_list == self.SIGNAL_BREAK: # Capture sentinel return self.SIGNAL_BREAK, None # Pass the numbers guessed by the user to the game model and # ask it to take a turn. status, turn_output = self.game.take_turn(input_list) finished = status in [self.game.WON, self.game.LOST] # Check the status of the turn and find out if there was an # error, e.g. the user type x, y, z when numbers were expected. # If there's an error, show the error details and then continue # looping. if status == self.game.ERROR: self.io_controller.report_error(turn_output) return self.SIGNAL_ERROR, turn_output served_by = None if 'served-by' in turn_output: served_by = turn_output["served-by"] self.io_controller.report_status( message="{}: Your guess analysis is above".format(served_by)) self.io_controller.update_result( line_number=line_number, result=turn_output["outcome"]["analysis"], numbers_guessed=input_list, finished=finished) # Check if the user won or lost the game. if finished: self.io_controller.finish( finish_message="{}".format(turn_output["outcome"]["status"])) return self.SIGNAL_FINISH, turn_output return self.SIGNAL_SUCCESS, turn_output # # Static Methods # @staticmethod def check_controller_defined(io_controller=None): if not io_controller: raise ValueError( "IO Controller is not set. Game cannot be played.") if not isinstance(io_controller, AbstractView): raise TypeError("IO Controller is not an instance of AbstractView") def check_game_in_play(self): if not self.game: raise ValueError("Game has not been instantiated!")