async def handle_auth_challenge(request): ''' challenge, qr daki veri { "nonce": "deneme_nonce", "s_did": "server_did", } callback yapmaya gerek yok challenge in nereye gidecegi belli GET /auth/challenge - challenge jsonu doner. ve terminalde bastirir ''' print_warn("handle auth challenge starting") challenge = {} print_ok(indy_config['steward_did']) challenge['sdid'] = indy_config['steward_did'] # 1. generate nonce nonce = secrets.token_hex(16) print_ok(f"nonce: {nonce}, len: {len(nonce)}") challenge['nonce'] = nonce app['nonces'][nonce] = False qr = pyqrcode.create(json.dumps(challenge), version=8) print(qr.terminal(quiet_zone=1)) return json_response(challenge)
async def did_auth(): wallet_config = json.dumps({"id": "client_wallet"}) wallet_credentials = json.dumps({"key": "very_secret_key"}) wallet_handle = await wallet.open_wallet(wallet_config, wallet_credentials) pool_handle = await pool.open_pool_ledger(config_name='sandbox', config=None) dids = await did.list_my_dids_with_meta(wallet_handle) # print(type(dids)) dids = json.loads(dids) my_did_verkey = dids[0]['verkey'] my_did = dids[0]['did'] print(f"dids: {dids}") print(f"my did verkey: {my_did_verkey}") req = requests.get('http://localhost:3000/auth/challenge') challenge = json.loads(req.text) print_ok(f"challenge: {challenge}") # 1. get server verkey from ledger server_verkey = await did.key_for_did(pool_handle, wallet_handle, str(challenge['sdid'])) print(f"server_verkey: {server_verkey}") print(f"challenge nonce: {challenge['nonce']}") # 2. create response response = {} response['sender_did'] = my_did nonce = challenge['nonce'] msg = await crypto.auth_crypt(wallet_handle, my_did_verkey, server_verkey, nonce.encode('utf-8')) msg_b64 = base64.b64encode(msg).decode('ascii') response['response_msg'] = msg_b64 print_ok(f"response {response}") # 3. send response req = requests.post(url='http://localhost:3000/auth/response', json=response) jwe_resp = json.loads(req.text) print_ok(f"jwt_resp {jwe_resp}") jwe_resp = json.loads(jwe_resp) # 4. retrive jwe jwe = jwe_resp['jwe'] print_warn(jwe) # 5. decript jwt unpacked_msg = await crypto.unpack_message(wallet_handle, str.encode(jwe)) print_ok(f"unpacked msg: {unpacked_msg}") unpacked_msg = json.loads(unpacked_msg) jwt_token = unpacked_msg['message'] print_ok(f"jwt token: {jwt_token}")
async def _save_cred_def_to_ledger(schema_id, cred_def_tag='TAG1', cred_def_type='CL'): """ # TODO logify # TODO indy ledger error handling # TODO ne print edilecek ne loglanacak cli ile kullanilmasi icin tasarlandi. diger moduller kullanmamali schema_id yi ledgerden ceker ve cred def olarak ekler, ayni sekilde birden fazla cred eklenebiliyor return: cred_def_id, None """ steward_did = indy_config["steward_did"] schema_req = await ledger.build_get_schema_request(None, schema_id) schema_response = await ledger.sign_and_submit_request( pool_handle, wallet_handle, steward_did, schema_req) schema_id, schema_json = await ledger.parse_get_schema_response( schema_response) print_warn(f'res schema id: {schema_id} schema json{schema_json}') # TODO if fetch schema then add cred def # if True: # print_ok(schema_id) cred_def_config = json.dumps({"support_revocation": False}) print_fail(schema_json) (cred_def_id, cred_def_json) = \ await anoncreds.issuer_create_and_store_credential_def(wallet_handle, steward_did, schema_json, cred_def_tag, cred_def_type, cred_def_config) print_ok(f"cred def id: {cred_def_id}") print_ok(f"cred def json: {cred_def_json}") cred_def_request = await ledger.build_cred_def_request( steward_did, cred_def_json) cred_def_resp = await ledger.sign_and_submit_request( pool_handle, wallet_handle, steward_did, cred_def_request) print_fail(cred_def_resp) cred_def_resp = json.loads(cred_def_resp) # TODO response burada yermi emin degilim if cred_def_resp['op'] == 'REJET': print_fail('cred def tx rejected !') return None print_ok(f'cred def {cred_def_id} added to ledger !') return cred_def_id
def get_version(module_name, properties_file): version = '' for line in properties_file: decoded_line = line.decode(constants.ENCODING) if re.match('version=', decoded_line): version = decoded_line.split('=')[-1][:-1] if version == '': utils.print_warn(f'Version not found for the module: {module_name}') return version
def _copy_data_dlls(self, arch): """ Updates libs and data files in the bin dir. """ print_ok("Packaging files (%s)..." % (ArchNames.names[arch])) # Changelog: make sure it is up to date (i.e. edited today) while True: chlog_moddate = datetime.fromtimestamp(os.path.getmtime(self._paths[CHLOGFILE])).date() if chlog_moddate >= datetime.today().date(): break else: print_warn("Changelog not edited today, but on " + str(chlog_moddate) + ". It is probably outdated.") print("Note that any changes you make after this point will probably not be present") print("in the installers.") cont = wait_for_key("(R)etry, (c)ontinue or (a)bort?", ["r", "c", "a"]) if cont == "r": continue elif cont == "c": break elif cont == "a": raise KeyboardInterrupt shutil.copy(self._paths[CHLOGFILE], self._paths[BINDIR][arch]) # copy licence files shutil.copy(self._paths[LICFILE], os.path.join(self._paths[BINDIR][arch], "License.txt")) shutil.copy(self._paths[LIC3FILE], os.path.join(self._paths[BINDIR][arch], "License 3rd party.txt")) # Call util scripts to updata data files and DLLs if not ptupdata.main([self._paths[PTBASEDIR], self._paths[BINDIR][arch]]): return False try: if not ptuplibs.main( [os.path.dirname(os.environ["tcpath"]), self._paths[BINDIR][arch], ArchNames.bits[arch]] ): return False except KeyError: print_err("Environment variable tcpath not set.") return False # strip unnecessary symbols from binaries for files in ["*.exe", "*.dll"]: if not run_cmd([CMD[STRIP], os.path.join(self._paths[BINDIR][arch], files)]): print_warn("WARNING: Failed to strip " + os.path.join(self._paths[BINDIR][arch], files)) return True
async def init_git(session, git_url, folder_path=None): if not folder_path: folder_path = '' proj_path = os.path.join(os.getcwd(), folder_path) if not os.path.exists(proj_path): os.mkdir(proj_path) os.chdir(proj_path) # init a new git project if doesn't exist if not os.path.exists(os.path.join(os.getcwd(), '.git')): proc = await asyncio.subprocess.create_subprocess_exec('git', 'init') await proc.communicate() # download packed data url = f'{git_url}objects/info/packs' status, content = await fetch(session, url) if status == 200: # create packs folder and download them packs_path = os.path.join(os.getcwd(), '.git', 'objects', 'pack') if not os.path.exists(packs_path): os.makedirs(packs_path) packs = re.findall(r'(pack-\w+)\.pack', content.decode()) loop = asyncio.get_running_loop() tasks = [ loop.create_task(unpack_hash(git_url, pack, session)) for pack in packs ] await asyncio.gather(*tasks) else: msg = 'ERROR: status_code=[%s] received downloading git packs' % status print_warn(msg) # download git index if doesn't exist index_path = os.path.join(os.getcwd(), '.git', 'index') if not os.path.exists(index_path): url = git_url + 'index' status, content = await fetch(session, url) if status != 200: msg = f'ERROR: status_code=[{status}] received downloading git index' raise IOError(200, msg) with open(index_path, 'wb') as f: f.write(content)
async def fetch_file(blob_path, git_url, session): blob, path = blob_path if 'vendor' in path or 'node_modules' in path or 'uploads/' in path: return content = await decode_hash(blob, git_url, session) if not content: # search blob in unpacked files folder, filename = blob[:2], blob[2:] blob_path = os.path.join(os.getcwd(), '.git', 'objects', folder, filename) if not os.path.exists(blob_path): print_warn('ERROR getting [%s] %s' % (blob, path)) return with open(blob_path, 'rb') as f: content = f.read() create_file(path, content) print_green('Created [%s] %s' % (blob, path))
async def unpack_hash(git_url, pack, session): """ download, save and unpack .pack file from git repository """ packs_path = os.path.join(os.getcwd(), '.git', 'objects', 'pack') for ext in ('.idx', '.pack'): filename = pack + ext filepath = os.path.join(packs_path, filename) # download packs only if doesn't exist already if not os.path.exists(filepath): print('Downloading pack=[%s]' % filename) url = f'{git_url}objects/pack/{filename}' status, content = await fetch(session, url) if status != 200: m = f'ERROR downloading pack=[{filename}]. status_code=[{status}]' print_warn(m) return with open(filepath, 'wb') as f: f.write(content) # store `filepath` content in StreamReader proc = await asyncio.subprocess.create_subprocess_exec( 'cat', filepath, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, _ = await proc.communicate() # unpack content using git subprocess, passing StreamReader as input proc = await asyncio.subprocess.create_subprocess_exec( 'git', 'unpack-objects', '-r', stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) await proc.communicate(input=stdout)
async def _init_creds(): ''' schemalari ledgere cred def olarak ekle. ''' schema_ids = get_added_schemas() schema_ids = json.loads(schema_ids) print_fail(f"schema ids: {schema_ids}") cred_def_list = [] for schema_id in schema_ids: cred_def_id = await _save_cred_def_to_ledger(schema_id) if cred_def_id != None: cred_def_list.append(cred_def_id) print_warn(cred_def_list) if len(cred_def_list) > 0: print_ok('writing cred def ids to json') with open('server_json/server_cred_defs.json', 'w') as f: f.write(json.dumps(cred_def_list))
async def init_client(): ''' init client indy TODO ledgere did'i buradaki seed'i kullanarak ekledim, init scripte tx ile did'i ledgere ekleme fonksiyonunu ekle ''' try: await pool.set_protocol_version(PROTOCOL_VERSION) wallet_config = json.dumps({"id": "client_wallet"}) wallet_credentials = json.dumps({"key": "very_secret_key"}) print_warn('creating wallet for client') try: await wallet.create_wallet(wallet_config, wallet_credentials) except IndyError as ex: if ex.error_code == ErrorCode.WalletAlreadyExistsError: print_fail("wallet already exists {}".format(wallet_config)) wallet_handle = await wallet.open_wallet(wallet_config, wallet_credentials) client_seed = '000000000000000000000000Client11' did_json = json.dumps({'seed': client_seed}) client_did, client_verkey = await did.create_and_store_my_did( wallet_handle, did_json) print_ok(f"client_did: {client_did}, client_verkey: {client_verkey}") link_secret_name = 'link_secret' link_secret_id = await anoncreds.prover_create_master_secret( wallet_handle, link_secret_name) except Exception as e: print_fail(e) raise e
def main(cli_params): print("\nPhotivo for Windows package builder", SCRIPT_VERSION) print(DIVIDER, end="\n\n") if not os.path.isfile(os.path.join(os.getcwd(), "photivo.pro")): print_err("ERROR: Photivo repository not found. Please run this script from the folder") print_err('where "photivo.pro" is located.') return False # setup, config and pre-build checks if not load_ini_file(): return False paths = build_paths(os.getcwd()) if not check_build_env(paths): return False if not prepare_dirs(paths): return False archlist = Arch.archs fullrelease = True if len(cli_params) > 0: if cli_params[0] == "32": print_warn("Only building 32bit package!") archlist = [Arch.win32] fullrelease = False elif cli_params[0] == "64": print_warn("Only building 64bit package!") archlist = [Arch.win64] fullrelease = False # build and package everything builder = PhotivoBuilder(paths) for arch in archlist: if not builder.build(arch): return False if not builder.package(arch): return False # final summary and option to clean up if not builder.show_summary(): print_err("Something went wrong along the way.") return False if fullrelease: print_ok("Everything looks fine.") print("You can test and upload the release now.") print("\nAfterwards I can clean up automatically, i.e.:") if ARCHIVE_DIR == "": print("* delete everything created during the build process.") else: print("* move installers to", ARCHIVE_DIR) print("* delete everything else created during the build process") if wait_for_yesno("\nShall I clean up now?"): if not builder.cleanup(): return False else: print("OK. The mess stays.") else: print_warn("Remember: Only the " + Archnames.names[archlist[0]] + " installer was built.") print_ok("All done.") return True
def check_build_env(paths): # Force English output from Mercurial os.environ['HGPLAIN'] = 'true' # Check presence of required commands cmds_ok = True for cmd in CMD: cmds_ok = check_bin([CMD[cmd]] + CMD_PARAMS_FOR_TEST[cmd]) and cmds_ok if not cmds_ok: return False hgbranch = get_cmd_output([CMD[HG], 'branch']) if hgbranch != 'default': print_warn('Working copy is set to branch "%s" instead of "default".' % (hgbranch)) if not wait_for_yesno('Continue anyway?'): return False # Working copy should be clean. The only exception is the Changelog.txt file. # Ignoring that makes it possible to start the release script and edit the # changelos while it is running. if not 'commit: (clean)' in get_cmd_output([CMD[HG], 'summary']): hgstatus = get_cmd_output([CMD[HG], 'status']).split('\n') for file_entry in hgstatus: if (len(file_entry) > 0) and (not 'Changelog.txt' in file_entry): print_warn('Working copy has uncommitted changes.') if wait_for_yesno('Continue anyway?'): break else: return False files_ok = True # files must be present if not os.path.isfile(paths[ISSFILE][Arch.win32]): print_err('ERROR: Installer script "%s" missing.' % paths[ISSFILE][Arch.win32]) files_ok = False if not os.path.isfile(paths[ISSFILE][Arch.win64]): print_err('ERROR: Installer script "%s" missing.' % paths[ISSFILE][Arch.win64]) files_ok = False if not os.path.isfile(paths[CHLOGFILE]): print_err('ERROR: File "%s" missing.' % paths[CHLOGFILE]) files_ok = False if not os.path.isfile(paths[LICFILE]): print_err('ERROR: File "%s" missing.' % paths[LICFILE]) files_ok = False if not os.path.isfile(paths[LIC3FILE]): print_err('ERROR: File "%s" missing.' % paths[LIC3FILE]) files_ok = False if not os.path.isfile(paths[DATESTYFILE]): print_err('ERROR: Style file "%s" missing.' % paths[DATESTYFILE]) files_ok = False if not os.path.isfile(paths[VERSTYFILE]): print_err('ERROR: Style file "%s" missing.' % paths[VERSTYFILE]) files_ok = False return files_ok
async def get_credential(): ''' # TODO Hicbirsekilde hata kontrolu yok ! ''' print_ok('get credential started') # 0. open wallet and create master link wallet_config = json.dumps({"id": "client_wallet"}) wallet_credentials = json.dumps({"key": "very_secret_key"}) wallet_handle = await wallet.open_wallet(wallet_config, wallet_credentials) pool_handle = await pool.open_pool_ledger(config_name='sandbox', config=None) link_secret_name = 'link_secret' # 1. get available creds req = requests.get('http://localhost:3000/availablecreds') cred_def_ids = req.text cred_def_ids = json.loads(cred_def_ids) print_ok(cred_def_ids) # TODO credentialin attribute lari ledgerden cekilebilir. # 2. get cred offer cred_offer_url = f'http://localhost:3000/credoffer/{cred_def_ids[0]}' # print(cred_offer_url) req = requests.get(cred_offer_url) cred_offer_ret = req.text cred_offer_ret = json.loads(cred_offer_ret) cred_offer_json = cred_offer_ret['cred_offer_json'] cred_offer_json = json.loads(cred_offer_json) cred_offer_json = json.dumps(cred_offer_json) print_ok(cred_offer_json) # 3. create and send cred req ''' { cred_offer_json: cred_offer_json cred_req_json: cred_req_json } ''' # 3.1 fetch cred def # TODO poolu acmak lazim cred_def_req = await ledger.build_get_cred_def_request( None, cred_def_ids[0]) cred_def_resp = await ledger.submit_request(pool_handle, cred_def_req) _, cred_def_json = await ledger.parse_get_cred_def_response(cred_def_resp) print_ok(cred_def_json) cred_req_body = {} client_dids = await did.list_my_dids_with_meta(wallet_handle) client_dids = json.loads(client_dids) client_did = client_dids[0]['did'] print_warn(f'client did: {client_did}') # print_fail(f'{cred_defs[0]}, {type(cred_defs[0])}') (cred_req_json, cred_req_metadata_json) = \ await anoncreds.prover_create_credential_req(wallet_handle, client_did, cred_offer_json, cred_def_json, link_secret_name) print_ok('credential request created!') cred_req_body['cred_offer_json'] = cred_offer_json cred_req_body['cred_req_json'] = cred_req_json cred_req_url = f'http://localhost:3000/credrequest' cred_req_resp = requests.post(url=cred_req_url, json=cred_req_body) cred_req_resp = cred_req_resp.text cred_req_resp = json.loads(cred_req_resp) print_ok(cred_req_resp) # 4. get and store cred cred_id = await anoncreds.prover_store_credential( wallet_handle, None, cred_req_metadata_json, cred_req_resp['cred_json'], cred_def_json, None) print_ok(cred_id) # 5. list cred pass
def check_build_env(paths): # Force English output from Mercurial os.environ["HGPLAIN"] = "true" # Check presence of required commands cmds_ok = True for cmd in CMD: cmds_ok = check_bin([CMD[cmd]] + CMD_PARAMS_FOR_TEST[cmd]) and cmds_ok if not cmds_ok: return False hgbranch = get_cmd_output([CMD[HG], "branch"]) if hgbranch != "default": print_warn('Working copy is set to branch "%s" instead of "default".' % (hgbranch)) if not wait_for_yesno("Continue anyway?"): return False # Working copy should be clean. The only exception is the Changelog.txt file. # Ignoring that makes it possible to start the release script and edit the # changelos while it is running. if not "commit: (clean)" in get_cmd_output([CMD[HG], "summary"]): hgstatus = get_cmd_output([CMD[HG], "status"]).split("\n") for file_entry in hgstatus: if (len(file_entry) > 0) and (not "Changelog.txt" in file_entry): print_warn("Working copy has uncommitted changes.") if wait_for_yesno("Continue anyway?"): break else: return False files_ok = True # files must be present if not os.path.isfile(paths[ISSFILE][Arch.win32]): print_err('ERROR: Installer script "%s" missing.' % paths[ISSFILE][Arch.win32]) files_ok = False if not os.path.isfile(paths[ISSFILE][Arch.win64]): print_err('ERROR: Installer script "%s" missing.' % paths[ISSFILE][Arch.win64]) files_ok = False if not os.path.isfile(paths[CHLOGFILE]): print_err('ERROR: File "%s" missing.' % paths[CHLOGFILE]) files_ok = False if not os.path.isfile(paths[LICFILE]): print_err('ERROR: File "%s" missing.' % paths[LICFILE]) files_ok = False if not os.path.isfile(paths[LIC3FILE]): print_err('ERROR: File "%s" missing.' % paths[LIC3FILE]) files_ok = False if not os.path.isfile(paths[DATESTYFILE]): print_err('ERROR: Style file "%s" missing.' % paths[DATESTYFILE]) files_ok = False if not os.path.isfile(paths[VERSTYFILE]): print_err('ERROR: Style file "%s" missing.' % paths[VERSTYFILE]) files_ok = False return files_ok
def game_over(): utils.print_warn("Fim de jogo!") sys.exit()
async def handle_auth_response(request): ''' responese { sender_did: "sender did" reponse_msg: "authencrypted_base64 encoded message" } POST /auth/response - ozhan agent hazirladigi response' i buraya gonderir - daha sonra kullanmak uzere jwt tokenini alir. ''' print_warn("handle auth response starting") wallet_handle = app['wallet_handle'] pool_handle = app['pool_handle'] # 1. parse request post_body = await request.read() response = json.loads(post_body) print_warn(post_body) client_did = response['sender_did'] # client_fetched_verkey = await did.key_for_did(pool_handle, wallet_handle, client_did) response_msg_b64 = response['response_msg'] response_msg = base64.b64decode(response_msg_b64) # 2. validate/decrypt auth encrypt message steward_did = indy_config['steward_did'] steward_verkey = await did.key_for_local_did(wallet_handle, steward_did) print_warn(f"steward verkey: {steward_verkey}") client_fetched_verkey, msg = await crypto.auth_decrypt(wallet_handle, steward_verkey, response_msg) print_ok(f"client_fetched_verkey: {client_fetched_verkey}") print_ok(f"msg: {msg}") nonce = msg.decode('utf-8') if nonce in app['nonces']: print_ok('nonce gecerli jwt donuluyor') # 4. generate jwt with hs256 payload = {'iss': 'did:sov:' + client_did} print_ok(f"payload: {payload}") encoded_jwt = jwt.encode(payload, 'secret', algorithm="HS256") print_ok(f"jwt: {encoded_jwt}") # 5. return jwt with jwe jwt_jwe = await crypto.pack_message(wallet_handle, encoded_jwt, [client_fetched_verkey], steward_verkey) print(jwt_jwe) # 6. create and return response jwt_resp = {} jwt_resp['jwe'] = jwt_jwe.decode('utf-8') print_ok(f"jwt \n{json.dumps(jwt_resp)}") return Response(text=jwt_jwe.decode('utf-8')) else: print_fail('nonce yok! unauth donuluyor') return web.Response(status=401)
def _copy_data_dlls(self, arch): """ Updates libs and data files in the bin dir. """ print_ok('Packaging files (%s)...' % (ArchNames.names[arch])) # Changelog: make sure it is up to date (i.e. edited today) while True: chlog_moddate = datetime.fromtimestamp( os.path.getmtime(self._paths[CHLOGFILE])).date() if chlog_moddate >= datetime.today().date(): break else: print_warn('Changelog not edited today, but on ' + str(chlog_moddate) + '. It is probably outdated.') print( 'Note that any changes you make after this point will probably not be present' ) print('in the installers.') cont = wait_for_key('(R)etry, (c)ontinue or (a)bort?', ['r', 'c', 'a']) if cont == 'r': continue elif cont == 'c': break elif cont == 'a': raise KeyboardInterrupt shutil.copy(self._paths[CHLOGFILE], self._paths[BINDIR][arch]) # copy licence files shutil.copy(self._paths[LICFILE], os.path.join(self._paths[BINDIR][arch], 'License.txt')) shutil.copy( self._paths[LIC3FILE], os.path.join(self._paths[BINDIR][arch], 'License 3rd party.txt')) # Call util scripts to updata data files and DLLs if not ptupdata.main( [self._paths[PTBASEDIR], self._paths[BINDIR][arch]]): return False try: if not ptuplibs.main([ os.path.dirname(os.environ['tcpath']), self._paths[BINDIR][arch], ArchNames.bits[arch] ]): return False except KeyError: print_err('Environment variable tcpath not set.') return False # strip unnecessary symbols from binaries for files in ['*.exe', '*.dll']: if not run_cmd( [CMD[STRIP], os.path.join(self._paths[BINDIR][arch], files)]): print_warn('WARNING: Failed to strip ' + os.path.join(self._paths[BINDIR][arch], files)) return True
def main(cli_params): print('\nPhotivo for Windows package builder', SCRIPT_VERSION) print(DIVIDER, end='\n\n') if not os.path.isfile(os.path.join(os.getcwd(), 'photivo.pro')): print_err( 'ERROR: Photivo repository not found. Please run this script from the folder' ) print_err('where "photivo.pro" is located.') return False # setup, config and pre-build checks if not load_ini_file(): return False paths = build_paths(os.getcwd()) if not check_build_env(paths): return False if not prepare_dirs(paths): return False archlist = Arch.archs fullrelease = True if len(cli_params) > 0: if cli_params[0] == '32': print_warn('Only building 32bit package!') archlist = [Arch.win32] fullrelease = False elif cli_params[0] == '64': print_warn('Only building 64bit package!') archlist = [Arch.win64] fullrelease = False # build and package everything builder = PhotivoBuilder(paths) for arch in archlist: if not builder.build(arch): return False if not builder.package(arch): return False # final summary and option to clean up if not builder.show_summary(): print_err('Something went wrong along the way.') return False if fullrelease: print_ok('Everything looks fine.') print('You can test and upload the release now.') print('\nAfterwards I can clean up automatically, i.e.:') if ARCHIVE_DIR == '': print('* delete everything created during the build process.') else: print('* move installers to', ARCHIVE_DIR) print('* delete everything else created during the build process') if wait_for_yesno('\nShall I clean up now?'): if not builder.cleanup(): return False else: print('OK. The mess stays.') else: print_warn('Remember: Only the ' + Archnames.names[archlist[0]] + ' installer was built.') print_ok('All done.') return True
def play(): players_names, players_tokens = players.register_players() utils.print_colored("§B§rPlacar Inicial§0\n") system.print_stats(players_names, players_tokens) print("") round = 1 while True: utils.print_colored(f"§B§rRODADA {round}§0\n") players_names, players_tokens, round_bets = bets.ask_bets( players_names, players_tokens) utils.print_colored("§B§rDANDO AS CARTAS...§0\n") round_cards = cards.draw_cards(players_names) cards_sum = cards.sum_players_cards(round_cards) cards.print_cards(players_names, round_cards) cards_round_winners = cards.get_winners(players_names, cards_sum) bet_round_winners = bets.get_winners(players_names, round_bets, cards_round_winners) bet_prizes = bets.get_prizes(players.get_real_players(players_names), round_bets, bet_round_winners, cards.deck_amount) for i in range(0, len(bet_prizes)): playername = players_names[i] prize_amount = bet_prizes[i] players_tokens[i] += prize_amount if (prize_amount > 0): utils.print_success( f"{playername} ganhou a aposta e recebeu {prize_amount} fichas!" ) if (prize_amount < 0): utils.print_danger( f"{playername} perdeu a aposta e pagou {abs(prize_amount)} fichas!" ) i = 0 while True: if not i < len(players.get_real_players(players_names)): break if players_tokens[i] == 0: player_name = players_names[i] del players_names[i] del players_tokens[i] utils.print_warn( f"{player_name} saiu do jogo com nenhuma ficha!") continue i += 1 if not players.has_players(players_names): system.game_over() utils.print_colored("§B§rNovo placar§0\n") system.print_stats(players_names, players_tokens) print("") round += 1