Beispiel #1
0
def initialize_testdata():
    # Sample game for quicker tests
    testgame = Game(-1001113216265, 15771023)
    GamesController.games[-1001113216265] = testgame
    players = [Player("Александр", 320853702), Player("Gustav", 305333239), Player("Rene", 318940765), Player("Susi", 290308460), Player("Renate", 312027975)]
    for player in players:
        testgame.add_player(player.uid, player)
Beispiel #2
0
 def test_board_when_game_is_running(self):
     game = Game(-999, 12345)
     game.board = Board(5, game)
     GamesController.games[-999] = game
     self.updater.dispatcher.add_handler(
         CommandHandler("board", command_board))
     self.updater.start_polling()
     chat = self.cg.get_chat(cid=-999)
     update = self.mg.get_message(chat=chat, text="/board")
     self.bot.insertUpdate(update)
     self.assertEqual(len(self.bot.sent_messages), 1)
     sent = self.bot.sent_messages[0]
     self.assertEqual(sent['method'], "sendMessage")
     self.assertIn("--- Liberal acts ---", sent['text'])
     self.updater.stop()
def command_newgame(bot, update):
    cid = update.message.chat_id
    game = GamesController.games.get(cid, None)
    groupType = update.message.chat.type
    if groupType not in ['group', 'supergroup']:
        bot.send_message(
            cid,
            "You have to add me to a group first and type /newgame there!")
    elif game:
        bot.send_message(
            cid,
            "There is currently a game running. If you want to end it please type /cancelgame!"
        )
    else:
        GamesController.games[cid] = Game(cid, update.message.from_user.id)
        with open(STATS, 'r') as f:
            stats = json.load(f)
        if cid not in stats.get("groups"):
            stats.get("groups").append(cid)
            with open(STATS, 'w') as f:
                json.dump(stats, f)
        bot.send_message(
            cid,
            "New game created! Each player has to /join the game.\nThe initiator of this game (or the admin) can /join too and type /startgame or /startrebalanced when everyone has joined the game!"
        )
Beispiel #4
0
def command_newgame(update: Update, context: CallbackContext):
    bot = context.bot
    args = context.args
    cid = update.message.chat_id
    groupName = update.message.chat.title
    try:
        game = get_game(cid)
        groupType = update.message.chat.type
        if groupType not in ['group', 'supergroup']:
            bot.send_message(
                cid,
                "Tienes que agregarme a un grupo primero y escribir /newgame allá!"
            )
        elif game:
            bot.send_message(
                cid,
                "Hay un juego comenzado en este chat. Si quieres terminarlo escribe /cancelgame!"
            )
        else:
            GamesController.games[cid] = Game(cid, update.message.from_user.id,
                                              groupName)
            bot.send_message(
                cid,
                "Nuevo juego creado! Cada jugador debe unirse al juego con el comando /join.\nEl iniciador del juego (o el administrador) pueden unirse tambien y escribir /startgame cuando todos se hayan unido al juego!"
            )

    except Exception as e:
        bot.send_message(cid, str(e))
Beispiel #5
0
def CreateGame(cid, uid, tipo, groupName):
    # Al momento solo SayAnything y Arcana tienen game custom
    if tipo == 'SayAnything':
        GamesController.games[cid] = GameSayAnything(cid, uid, groupName, tipo)
    elif tipo == 'Arcana':
        GamesController.games[cid] = GameArcana(cid, uid, groupName, tipo)
    else:
        GamesController.games[cid] = Game(cid, uid, groupName, tipo)
    return GamesController.games[cid]
Beispiel #6
0
 def test_board_when_game_is_not_running(self):
     game = Game(-999, 12345)
     GamesController.games[-999] = game
     self.updater.dispatcher.add_handler(
         CommandHandler("board", command_board))
     self.updater.start_polling()
     chat = self.cg.get_chat(cid=-999)
     update = self.mg.get_message(chat=chat, text="/board")
     self.bot.insertUpdate(update)
     self.assertEqual(len(self.bot.sent_messages), 1)
     sent = self.bot.sent_messages[0]
     self.assertEqual(sent['method'], "sendMessage")
     self.assertIn(
         "There is no running game in this chat. Please start the game with /startgame",
         sent['text'])
     self.updater.stop()
Beispiel #7
0
def command_novojogo(bot, update):
    cid = update.message.chat_id
    game = GamesController.games.get(cid, None)
    groupType = update.message.chat.type
    if groupType not in ['group', 'supergroup']:
        bot.send_message(cid, "Primeiro você tem que me adicionar a um grupo e digitar /novojogo")
    elif game:
        bot.send_message(cid, "Já existe um jogo em andamento, se você quiser finalizar digite /cancelarjogo")
    else:
        GamesController.games[cid] = Game(cid, update.message.from_user.id)
        with open(STATS, 'r') as f:
            stats = json.load(f)
        if cid not in stats.get("groups"):
            stats.get("groups").append(cid)
            with open(STATS, 'w') as f:
                json.dump(stats, f)
        bot.send_message(cid, "Novo jogo criado! Cada jogador deve mandar o comando /participar do jogo.\nQuem iniciou o jogo (ou o admin do grupo) pode, /participar também e então digitar /comecarjogo quando todos já confirmaram participação")
Beispiel #8
0
def command_newgame(update: Update, context: CallbackContext):
	bot = context.bot
	args = context.args
	cid = update.message.chat_id
	groupName = update.message.chat.title	
	try:
		game = get_game(cid)
		groupType = update.message.chat.type
		if groupType not in ['group', 'supergroup']:
			bot.send_message(cid, "Beni bir gruba eklemeli ve yeni bir oyun oluşturmak için /yenioyun yazmalısın!")
		elif game:
			bot.send_message(cid, "Şu anda başlamış bir oyun var. Sonlandırmak istiyorsanız, lütfen /oyuniptal yazın!")
		else:
			GamesController.games[cid] = Game(cid, update.message.from_user.id, groupName)
			bot.send_message(cid, "Yeni oyun oluşturuldu! Oyuna katılmak için /katil yaz.\nBu oyunu kuran kişi (veya yönetici) herkes oyuna katıldığında /oyunubaslat yazarak oyunu başlatabilir!")
			
	except Exception as e:
		bot.send_message(cid, str(e))
Beispiel #9
0
def command_newgame(bot, update):  
	cid = update.message.chat_id
		
	try:
		game = GamesController.games.get(cid, None)
		groupType = update.message.chat.type
		if groupType not in ['group', 'supergroup']:
			bot.send_message(cid, "Tienes que agregarme a un grupo primero y escribir /newgame allá!")
		elif game:
			bot.send_message(cid, "Hay un juego comenzado en este chat. Si quieres terminarlo escribe /cancelgame!")
		else:
			
			#Search game in DB
			game = load_game(cid)			
			if game:
				GamesController.games[cid] = game
				bot.send_message(cid, "Hay un juego comenzado en este chat. Si quieres terminarlo escribe /cancelgame!")				
				
				if not game.board:
					return
				
				# Ask the president to choose a chancellor
				if game.board.state.nominated_chancellor:
					if len(game.board.state.last_votes) == len(game.player_sequence):
						print_board(bot, game, cid)
						MainController.count_votes(bot, game)
					else:
						print_board(bot, game, cid)
						MainController.vote(bot, game)
						bot.send_message(cid, "Hay una votación en progreso utiliza /calltovote para decirles a los otros jugadores. ")
				else:				
					MainController.start_round(bot, game)
			else:
				GamesController.games[cid] = Game(cid, update.message.from_user.id)
				bot.send_message(cid, "Nuevo juego creado! Cada jugador debe unirse al juego con el comando /join.\nEl iniciador del juego (o el administrador) pueden unirse tambien y escribir /startgame cuando todos se hayan unido al juego!")
			
			
	except Exception as e:
		bot.send_message(cid, str(e))
Beispiel #10
0
def callback_finish_game_buttons(bot, update):
    callback = update.callback_query
    try:
        #log.info('callback_finish_game_buttons called: %s' % callback.data)
        regex = re.search("(-[0-9]*)\*chooseend\*(.*)\*([0-9]*)",
                          callback.data)
        cid, strcid, opcion, uid, struid = int(
            regex.group(1)), regex.group(1), regex.group(2), int(
                regex.group(3)), regex.group(3)
        mensaje_edit = "Has elegido el diccionario: {0}".format(opcion)
        try:
            bot.edit_message_text(mensaje_edit, cid,
                                  callback.message.message_id)
        except Exception as e:
            bot.edit_message_text(mensaje_edit, uid,
                                  callback.message.message_id)
        game = Commands.get_game(cid)

        # Obtengo el diccionario actual, primero casos no tendre el config y pondre el community
        try:
            dicc = game.configs.get('diccionario', 'community')
        except Exception as e:
            dicc = 'community'

        # Obtengo datos de juego anterior
        groupName = game.groupName
        tipojuego = game.tipo
        modo = game.modo
        descarte = game.board.discards
        # Dependiendo de la opcion veo que como lo inicio
        players = game.playerlist.copy()
        # Creo nuevo juego
        game = Game(cid, uid, groupName, tipojuego, modo)
        GamesController.games[cid] = game
        # Guarda los descartes en configs para asi puedo recuperarlos
        game.configs['discards'] = descarte
        if opcion == "Nuevo":
            bot.send_message(
                cid,
                "Cada jugador puede unirse al juego con el comando /join.\nEl iniciador del juego (o el administrador) pueden unirse tambien y escribir /startgame cuando todos se hayan unido al juego!"
            )
            return
        #log.info('Llego hasta la creacion')
        game.playerlist = players
        # StartGame
        player_number = len(game.playerlist)
        game.board = Board(player_number, game)
        game.player_sequence = []
        game.shuffle_player_sequence()

        if opcion == "Mismo Diccionario":
            #(Beta) Nuevo Partido, mismos jugadores, mismo diccionario
            #log.info('Llego hasta el new2')
            game.configs['diccionario'] = dicc
            finish_config(bot, game, dicc)
        if opcion == "Otro Diccionario":
            #(Beta) Nuevo Partido, mismos jugadores, diferente diccionario
            call_dicc_buttons(bot, game)
    except Exception as e:
        bot.send_message(ADMIN[0],
                         'No se ejecuto el comando debido a: ' + str(e))
        bot.send_message(ADMIN[0], callback.data)
Beispiel #11
0
 def __init__(self, cid, initiator, groupName, tipo=None, modo=None):
     BaseGame.__init__(self, cid, initiator, groupName, tipo, modo)
Beispiel #12
0
 def __init__(self, cid, initiator, groupName, tipo=None, modo=None):
     BaseGame.__init__(self, cid, initiator, groupName, tipo, modo)
     self.cartasAventura = random.sample([*cartas_aventura],
                                         len([*cartas_aventura]))
     self.cartasExplorationActual = []