def leave_game(bot, update): """Handler for the /leave command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if player is None: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) return game = player.game user = update.message.from_user try: gm.leave_game(user, chat) except NoGameInChatError: send_async(bot, chat.id, text=_("You are not playing in a game in " "this group."), reply_to_message_id=update.message.message_id) except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", game.translate)) else: send_async(bot, chat.id, text=__("Okay. Next Player: {name}", game.translate).format( name=display_name(game.current_player.user)), reply_to_message_id=update.message.message_id)
def data(self): url = 'https://finance.yahoo.com/quote/%s' % ( self.ticker) + '/financials' html = requests.get(url=url).text json_ = html.split('root.App.main =')[1].split('(this)')[0].split( ';\n}')[0].strip() df = json.loads( json_)['context']['dispatcher']['stores']['QuoteSummaryStore'] X = " " for idx, item in enumerate(json.dumps(df).split('{"raw": ')): if "fmt" in item: y = item.split(', "fmt":', maxsplit=1) X += y[0] + y[1].split('}', maxsplit=1)[1] else: X += item df = json.loads(X) cf = __(df['cashflowStatementHistory']['cashflowStatements']) bs = __(df['balanceSheetHistory']['balanceSheetStatements']) ics = __(df['incomeStatementHistory']['incomeStatementHistory']) cap = (df['summaryDetail']['marketCap']) return cf, bs, ics, cap
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.bluffing: send_async(bot, chat.id, text=__("Bluff called! Giving 4 cards to {name}", game.translate) .format(name=player.prev.user.first_name)) try: player.prev.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", game.translate)) else: game.draw_counter += 2 send_async(bot, chat.id, text=__("{name1} didn't bluff! Giving 6 cards to {name2}", game.translate) .format(name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", game.translate)) game.turn()
def skip_player(bot, update): """Handler for the /skip command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if not player: send_async(bot, chat.id, text=_("You are not playing in a game in this chat.")) return game = player.game skipped_player = game.current_player next_player = game.current_player.next started = skipped_player.turn_started now = datetime.now() delta = (now - started).seconds if delta < skipped_player.waiting_time: send_async(bot, chat.id, text=_("Please wait {time} seconds") .format(time=(skipped_player.waiting_time - delta)), reply_to_message_id=update.message.message_id) elif skipped_player.waiting_time > 0: skipped_player.anti_cheat += 1 skipped_player.waiting_time -= 30 try: skipped_player.draw() except DeckEmptyError: pass send_async(bot, chat.id, text=__("Waiting time to skip this player has " "been reduced to {time} seconds.\n" "Next player: {name}", game.translate) .format(time=skipped_player.waiting_time, name=display_name(next_player.user))) game.turn() else: try: gm.leave_game(skipped_player.user, chat) send_async(bot, chat.id, text=__("{name1} was skipped four times in a row " "and has been removed from the game.\n" "Next player: {name2}", game.translate) .format(name1=display_name(skipped_player.user), name2=display_name(next_player.user))) except NotEnoughPlayersError: send_async(bot, chat.id, text=__("{name} was skipped four times in a row " "and has been removed from the game.\n" "The game ended.", game.translate) .format(name=display_name(skipped_player.user))) gm.end_game(chat.id, skipped_player.user)
def process_result(bot, update): """ Handler for chosen inline results. Checks the players actions and acts accordingly. """ try: user = update.chosen_inline_result.from_user player = gm.userid_current[user.id] game = player.game result_id = update.chosen_inline_result.result_id chat = game.chat except KeyError: return logger.debug("Selected result: " + result_id) result_id, anti_cheat = result_id.split(':') last_anti_cheat = player.anti_cheat player.anti_cheat += 1 if result_id in ('hand', 'gameinfo', 'nogame'): return elif len(result_id) == 36: # UUID result return elif int(anti_cheat) != last_anti_cheat: send_async( bot, chat.id, text=__("Cheat attempt by {name}", game.translate).format(name=display_name(player.user))) return elif result_id == 'call_bluff': reset_waiting_time(bot, player) do_call_bluff(bot, player) elif result_id == 'draw': reset_waiting_time(bot, player) do_draw(bot, player) elif result_id == 'pass': game.turn() elif result_id in c.COLORS: game.choose_color(result_id) else: reset_waiting_time(bot, player) do_play_card(bot, player, result_id) if game in gm.chatid_games.get(chat.id, list()): send_async(bot, chat.id, text=__("Next player: {name}", game.translate).format( name=display_name(game.current_player.user)))
def add_draw(player, results): """Add option to draw""" n = player.game.draw_counter or 1 results.append( Sticker( "draw", sticker_file_id=c.STICKERS['option_draw'], input_message_content= InputTextMessageContent(__('Drawing 1 card', player.game.translate) if n == 1 else __('Drawing {number} cards', player.game.translate) .format(number=n)) ) )
def process_result(bot, update): """ Handler for chosen inline results. Checks the players actions and acts accordingly. """ try: user = update.chosen_inline_result.from_user player = gm.userid_current[user.id] game = player.game result_id = update.chosen_inline_result.result_id chat = game.chat except KeyError: return logger.debug("Selected result: " + result_id) result_id, anti_cheat = result_id.split(':') last_anti_cheat = player.anti_cheat player.anti_cheat += 1 if result_id in ('hand', 'gameinfo', 'nogame'): return elif len(result_id) == 36: # UUID result return elif int(anti_cheat) != last_anti_cheat: send_async(bot, chat.id, text=__("Cheat attempt by {name}", game.translate) .format(name=display_name(player.user))) return elif result_id == 'call_bluff': reset_waiting_time(bot, player) do_call_bluff(bot, player) elif result_id == 'draw': reset_waiting_time(bot, player) do_draw(bot, player) elif result_id == 'pass': game.turn() elif result_id in c.COLORS: game.choose_color(result_id) else: reset_waiting_time(bot, player) do_play_card(bot, player, result_id) if game in gm.chatid_games.get(chat.id, list()): send_async(bot, chat.id, text=__("Next player: {name}", game.translate) .format(name=display_name(game.current_player.user)))
def do_play_card(bot, player, result_id): """Plays the selected card and sends an update to the group if needed""" card = c.from_str(result_id) player.play(card) game = player.game chat = game.chat user = player.user us = UserSetting.get(id=user.id) if not us: us = UserSetting(id=user.id) us.cards_played += 1 if game.choosing_color: send_async(bot, chat.id, text=_("Please choose a color")) if len(player.cards) == 1: send_async(bot, chat.id, text="UNO!") if len(player.cards) == 0: send_async(bot, chat.id, text=__("{name} won!", game.translate).format(name=user.first_name)) if us.stats: us.games_played += 1 if game.players_won is 0: us.first_places += 1 try: gm.leave_game(user, chat) except NotEnoughPlayersError: send_async(bot, chat.id, text=__("Game ended!", game.translate)) us2 = UserSetting.get(id=game.current_player.user.id) if us2 and us2.stats: us2.games_played += 1 gm.end_game(chat, user) if botan: botan.track( Message(randint(1, 1000000000), user, datetime.now(), Chat(chat.id, 'group')), 'Played cards')
def do_play_card(bot, player, result_id): """Plays the selected card and sends an update to the group if needed""" card = c.from_str(result_id) player.play(card) game = player.game chat = game.chat user = player.user us = UserSetting.get(id=user.id) if not us: us = UserSetting(id=user.id) us.cards_played += 1 if game.choosing_color: send_async(bot, chat.id, text=_("Please choose a color")) if len(player.cards) == 1: send_async(bot, chat.id, text="UNO!") if len(player.cards) == 0: send_async(bot, chat.id, text=__("{name} won!", game.translate) .format(name=user.first_name)) if us.stats: us.games_played += 1 if game.players_won is 0: us.first_places += 1 try: gm.leave_game(user, chat) except NotEnoughPlayersError: send_async(bot, chat.id, text=__("Game ended!", game.translate)) us2 = UserSetting.get(id=game.current_player.user.id) if us2 and us2.stats: us2.games_played += 1 gm.end_game(chat, user) if botan: botan.track(Message(randint(1, 1000000000), user, datetime.now(), Chat(chat.id, 'group')), 'Played cards')
def add_pass(results, game): """Add option to pass""" results.append( Sticker( "pass", sticker_file_id=c.STICKERS['option_pass'], input_message_content=InputTextMessageContent(__('Pass', game.translate)) ) )
def reset_waiting_time(bot, player): """Resets waiting time for a player and sends a notice to the group""" chat = player.game.chat if player.waiting_time < 90: player.waiting_time = 90 send_async(bot, chat.id, text=__("Waiting time for {name} has been reset to 90 " "seconds", player.game.translate) .format(name=display_name(player.user)))
def add_call_bluff(results, game): """Add option to call a bluff""" results.append( Sticker( "call_bluff", sticker_file_id=c.STICKERS['option_bluff'], input_message_content= InputTextMessageContent(__("I'm calling your bluff!", game.translate)) ) )
def status_update(bot, update): """Remove player from game if user leaves the group""" chat = update.message.chat if update.message.left_chat_member: user = update.message.left_chat_member try: gm.leave_game(user, chat) game = gm.player_for_user_in_chat(user, chat).game except NoGameInChatError: pass except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", game.translate)) else: send_async(bot, chat.id, text=__("Removing {name} from the game", game.translate) .format(name=display_name(user)))
def status_update(bot, update): """Remove player from game if user leaves the group""" chat = update.message.chat if update.message.left_chat_member: user = update.message.left_chat_member try: gm.leave_game(user, chat) game = gm.player_for_user_in_chat(user, chat).game except NoGameInChatError: pass except NotEnoughPlayersError: gm.end_game(chat, user) send_async(bot, chat.id, text=__("Game ended!", game.translate)) else: send_async(bot, chat.id, text=__("Removing {name} from the game", game.translate).format(name=display_name(user)))
def reset_waiting_time(bot, player): """Resets waiting time for a player and sends a notice to the group""" chat = player.game.chat if player.waiting_time < 90: player.waiting_time = 90 send_async( bot, chat.id, text=__( "Waiting time for {name} has been reset to 90 " "seconds", player.game.translate).format(name=display_name(player.user)))
def do_call_bluff(bot, player): """Handles the bluff calling""" game = player.game chat = game.chat if player.prev.bluffing: send_async( bot, chat.id, text=__("Bluff called! Giving 4 cards to {name}", game.translate).format(name=player.prev.user.first_name)) try: player.prev.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", game.translate)) else: game.draw_counter += 2 send_async(bot, chat.id, text=__("{name1} didn't bluff! Giving 6 cards to {name2}", game.translate).format( name1=player.prev.user.first_name, name2=player.user.first_name)) try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", game.translate)) game.turn()
def do_draw(bot, player): """Does the drawing""" game = player.game draw_counter_before = game.draw_counter try: player.draw() except DeckEmptyError: send_async(bot, player.game.chat.id, text=__("There are no more cards in the deck.", game.translate)) if (game.last_card.value == c.DRAW_TWO or game.last_card.special == c.DRAW_FOUR) and \ draw_counter_before > 0: game.turn()
def gencase_completed_dialog(particle_count=0, detail_text="No details", data=dict(), temp_data=dict()): """ Creates a gencase save dialog with different options, like open the results with paraview, show details or dismiss. """ # TODO: This should be implemented as a custom class like GenCaseCompleteDialog(QtGui.QDialog) # Window Creation window = QtGui.QDialog() window.setWindowModality(QtCore.Qt.NonModal) window.setWindowTitle(utils.__("Save & GenCase")) # Main Layout creation main_layout = QtGui.QVBoxLayout() # Main Layout elements info_message = QtGui.QLabel( utils.__("Gencase exported {} particles.\nPress \"Details\" to check the output").format( str(particle_count))) button_layout = QtGui.QHBoxLayout() bt_open_with_paraview = QtGui.QPushButton(utils.__("Open with Paraview")) temp_data['widget_saver'] = QtGui.QMenu() temp_data['widget_saver'].addAction("{}_MkCells.vtk".format(data['project_name'])) temp_data['widget_saver'].addAction("{}_All.vtk".format(data['project_name'])) temp_data['widget_saver'].addAction("{}_Fluid.vtk".format(data['project_name'])) temp_data['widget_saver'].addAction("{}_Bound.vtk".format(data['project_name'])) bt_open_with_paraview.setMenu(temp_data['widget_saver']) bt_details = QtGui.QPushButton(utils.__("Details")) bt_ok = QtGui.QPushButton(utils.__("Ok")) button_layout.addWidget(bt_open_with_paraview) button_layout.addWidget(bt_details) button_layout.addWidget(bt_ok) # Details popup window detail_text_dialog = QtGui.QDialog() detail_text_dialog.setModal(False) detail_text_dialog_layout = QtGui.QVBoxLayout() detail_text_area = QtGui.QTextEdit() detail_text_area.setText(detail_text) detail_text_dialog_layout.addWidget(detail_text_area) detail_text_dialog.setLayout(detail_text_dialog_layout) # Main Layout scaffolding main_layout.addWidget(info_message) main_layout.addLayout(button_layout) # Window logic detail_text_dialog.hide() if len(data["paraview_path"]) > 1: bt_open_with_paraview.show() else: bt_open_with_paraview.hide() def on_ok(): detail_text_dialog.hide() window.accept() def on_view_details(): if detail_text_dialog.isVisible(): detail_text_dialog.hide() else: detail_text_dialog.show() detail_text_dialog.move( window.x() - detail_text_dialog.width() - 15, window.y() - abs(window.height() - detail_text_dialog.height()) / 2) def on_open_paraview_menu(action): try: subprocess.Popen( [ data['paraview_path'], "--data={}\\{}".format( data['project_path'] + '\\' + data['project_name'] + '_out', action.text() ) ], stdout=subprocess.PIPE) detail_text_dialog.hide() window.accept() except: error_dialog( "ERROR! \nCheck the ParaView executable path, it may have been saved from previously opened case!") return bt_ok.clicked.connect(on_ok) bt_details.clicked.connect(on_view_details) temp_data['widget_saver'].triggered.connect(on_open_paraview_menu) # Window scaffolding and execution window.setLayout(main_layout) window.show()
def start_game(bot, update, args): """Handler for the /start command""" if update.message.chat.type != 'private': chat = update.message.chat try: game = gm.chatid_games[chat.id][-1] except (KeyError, IndexError): send_async(bot, chat.id, text=_("There is no game running in this chat. Create " "a new one with /new")) return if game.started: send_async(bot, chat.id, text=_("The game has already started")) elif len(game.players) < 2: send_async(bot, chat.id, text=_("At least two players must /join the game " "before you can start it")) else: game.play_card(game.last_card) game.started = True first_message = (__( "First player: {name}\n" "Use /close to stop people from joining the game.\n" "Enable multi-translations with /enable_translations", game.translate).format( name=display_name(game.current_player.user))) @run_async def send_first(): """Send the first card and player""" bot.sendSticker(chat.id, sticker=c.STICKERS[str(game.last_card)], timeout=TIMEOUT) bot.sendMessage(chat.id, text=first_message, timeout=TIMEOUT) send_first() elif len(args) and args[0] == 'select': players = gm.userid_players[update.message.from_user.id] groups = list() for player in players: title = player.game.chat.title if player is gm.userid_current[update.message.from_user.id]: title = '- %s -' % player.game.chat.title groups.append([ InlineKeyboardButton(text=title, callback_data=str(player.game.chat.id)) ]) send_async(bot, update.message.chat_id, text=_('Please select the group you want to play in.'), reply_markup=InlineKeyboardMarkup(groups)) else: help(bot, update)
def skip_player(bot, update): """Handler for the /skip command""" chat = update.message.chat user = update.message.from_user player = gm.player_for_user_in_chat(user, chat) if not player: send_async(bot, chat.id, text=_("You are not playing in a game in this chat.")) return game = player.game skipped_player = game.current_player next_player = game.current_player.next started = skipped_player.turn_started now = datetime.now() delta = (now - started).seconds if delta < skipped_player.waiting_time: send_async(bot, chat.id, text=_("Please wait {time} seconds").format( time=(skipped_player.waiting_time - delta)), reply_to_message_id=update.message.message_id) elif skipped_player.waiting_time > 0: skipped_player.anti_cheat += 1 skipped_player.waiting_time -= 30 try: skipped_player.draw() except DeckEmptyError: pass send_async(bot, chat.id, text=__( "Waiting time to skip this player has " "been reduced to {time} seconds.\n" "Next player: {name}", game.translate).format( time=skipped_player.waiting_time, name=display_name(next_player.user))) game.turn() else: try: gm.leave_game(skipped_player.user, chat) send_async(bot, chat.id, text=__( "{name1} was skipped four times in a row " "and has been removed from the game.\n" "Next player: {name2}", game.translate).format( name1=display_name(skipped_player.user), name2=display_name(next_player.user))) except NotEnoughPlayersError: send_async(bot, chat.id, text=__( "{name} was skipped four times in a row " "and has been removed from the game.\n" "The game ended.", game.translate).format( name=display_name(skipped_player.user))) gm.end_game(chat.id, skipped_player.user)
def start_game(bot, update, args): """Handler for the /start command""" if update.message.chat.type != 'private': chat = update.message.chat try: game = gm.chatid_games[chat.id][-1] except (KeyError, IndexError): send_async(bot, chat.id, text=_("There is no game running in this chat. Create " "a new one with /new")) return if game.started: send_async(bot, chat.id, text=_("The game has already started")) elif len(game.players) < 2: send_async(bot, chat.id, text=_("At least two players must /join the game " "before you can start it")) else: game.play_card(game.last_card) game.started = True first_message = ( __("First player: {name}\n" "Use /close to stop people from joining the game.\n" "Enable multi-translations with /enable_translations", game.translate) .format(name=display_name(game.current_player.user))) @run_async def send_first(): """Send the first card and player""" bot.sendSticker(chat.id, sticker=c.STICKERS[str(game.last_card)], timeout=TIMEOUT) bot.sendMessage(chat.id, text=first_message, timeout=TIMEOUT) send_first() elif len(args) and args[0] == 'select': players = gm.userid_players[update.message.from_user.id] groups = list() for player in players: title = player.game.chat.title if player is gm.userid_current[update.message.from_user.id]: title = '- %s -' % player.game.chat.title groups.append( [InlineKeyboardButton(text=title, callback_data=str(player.game.chat.id))] ) send_async(bot, update.message.chat_id, text=_('Please select the group you want to play in.'), reply_markup=InlineKeyboardMarkup(groups)) else: help(bot, update)
def get_scaled_pos(self): return __(self.pos[0]), __(self.pos[1]), __(self.pos[2])
def case_summary(orig_data): """ Displays a dialog with a summary of the current opened case. """ # TODO: This should be implemented as a custom class like CaseSummary(QtGui.QDialog) if not utils.valid_document_environment(): return # Data copy to avoid referencing issues data = dict(orig_data) # Preprocess data to show in data copy data['gravity'] = "({}, {}, {})".format(*data['gravity']) if data['project_name'] == "": data['project_name'] = "<i>{}</i>".format(utils.__("Not yet saved")) if data['project_path'] == "": data['project_path'] = "<i>{}</i>".format(utils.__("Not yet saved")) for k in ['gencase_path', 'dsphysics_path', 'partvtk4_path']: if data[k] == "": data[k] = "<i>{}</i>".format( utils.__("Executable not correctly set")) data['stepalgorithm'] = { '1': 'Verlet', '2': 'Symplectic' }[str(data['stepalgorithm'])] data['project_mode'] = '3D' if data['3dmode'] else '2D' data['incz'] = float(data['incz']) * 100 data['partsoutmax'] = float(data['partsoutmax']) * 100 # Setting certain values to automatic for x in [ 'hswl', 'speedsystem', 'speedsound', 'h', 'b', 'massfluid', 'massbound' ]: data[x] = '<u>Automatic</u>' if data[x + '_auto'] else data[x] # region Formatting objects info data['objects_info'] = "" if len(data['simobjects']) > 1: data['objects_info'] += "<ul>" # data['simobjects'] is a dict with format # {'key': ['mk', 'type', 'fill']} where key is an internal name. for key, value in data['simobjects'].iteritems(): if key.lower() == 'case_limits': continue fc_object = utils.get_fc_object(key) is_floating = utils.__('Yes') if str( value[0]) in data['floating_mks'].keys() else utils.__('No') is_floating = utils.__('No') if value[ 1].lower() == "fluid" else is_floating has_initials = utils.__('Yes') if str( value[0]) in data['initials_mks'].keys() else utils.__('No') has_initials = utils.__('No') if value[ 1].lower() == "bound" else has_initials real_mk = value[0] + 11 if value[ 1].lower() == "bound" else value[0] + 1 data['objects_info'] += "<li><b>{label}</b> (<i>{iname}</i>): <br/>" \ "Type: {type} (MK{type}: <b>{mk}</b> ; MK: <b>{real_mk}</b>)<br/>" \ "Fill mode: {fillmode}<br/>" \ "Floating: {floats}<br/>" \ "Initials: {initials}</li><br/>".format(label=fc_object.Label, iname=key, type=value[1].title(), mk=value[0], real_mk=str( real_mk), fillmode=value[2].title( ), floats=is_floating, initials=has_initials) data['objects_info'] += "</ul>" else: data['objects_info'] += utils.__( "No objects were added to the simulation yet.") # endregion Formatting objects info # region Formatting movement info data['movement_info'] = "" if len(data['simobjects']) > 1: data['movement_info'] += "<ul>" for mov in data['global_movements']: try: movtype = mov.type except AttributeError: movtype = mov.__class__.__name__ mklist = list() for key, value in data['motion_mks'].iteritems(): if mov in value: mklist.append(str(key)) data['movement_info'] += "<li>{movtype} <u>{movname}</u><br/>" \ "Applied to MKBound: {mklist}</li><br/>".format( movtype=movtype, movname=mov.name, mklist=', '.join(mklist)) data['movement_info'] += "</ul>" else: data['movement_info'] += "No movements were defined in this case." # Create a string with MK used (of each type) data['mkboundused'] = list() data['mkfluidused'] = list() for element in data['simobjects'].values(): if element[1].lower() == 'bound': data['mkboundused'].append(str(element[0])) elif element[1].lower() == 'fluid': data['mkfluidused'].append(str(element[0])) data['mkboundused'] = ", ".join( data['mkboundused']) if len(data['mkboundused']) > 0 else "None" data['mkfluidused'] = ", ".join( data['mkfluidused']) if len(data['mkfluidused']) > 0 else "None" data['last_number_particles'] = data['last_number_particles'] if data['last_number_particles'] >= 0 else "GenCase wasn't executed" # endregion Formatting movement info # Dialog creation and template filling main_window = QtGui.QDialog() main_layout = QtGui.QVBoxLayout() info = QtGui.QTextEdit() lib_folder = os.path.dirname(os.path.realpath(__file__)) try: with open("{}/templates/case_summary_template.html".format(lib_folder), "r") as input_template: info_text = input_template.read().format(**data) except: error_dialog( "An error occurred trying to load the template file and format it.") return info.setText(info_text) info.setReadOnly(True) main_layout.addWidget(info) main_window.setLayout(main_layout) main_window.setModal(True) main_window.setMinimumSize(500, 650) main_window.exec_()