Пример #1
0
    def test_iterate_all_moves_with_both_players(self):
        p3 = Piece((0, 1), Owner.OPPONENT, Rank('4'))
        b = Board().place_piece(p2).place_piece(p3)

        expected_for_player = [((0, 0), m)
                               for m in b.iterate_moves_for_piece(p2)]
        expected_for_opponent = [((0, 1), m)
                                 for m in b.iterate_moves_for_piece(p3)]
        self.assertEqual(list(b.iterate_all_moves(Owner.PLAYER)),
                         expected_for_player)
        self.assertEqual(list(b.iterate_all_moves(Owner.OPPONENT)),
                         expected_for_opponent)
Пример #2
0
 def __init__(self, input_data):
     """
     Create the board.
     Make sure the initial_position is a valid move
     Add the initial_position to the path_history and set coins to 0
     """
     self.board = Board(*input_data.board_dimension, input_data.walls)
     if self.board.is_valid_move(*input_data.initial_position):
         self.the_pacman = ThePacman(*input_data.initial_position)
     else:
         raise PositionException(
             "The pacman can not be placed at the location: {}".format(
                 input_data.initial_position))
     self.movements = input_data.movements
     self.path_history = {input_data.initial_position}
     self.coins = 0
Пример #3
0
 def job_download_board_from_config(self, config, reconfigure=False):
     self.configure(base_config, reconfigure)
     board = Board()
     board.configure(config)
     board.dispatch()
     self.links = board.get_links()
     self.download()
Пример #4
0
    def __init__(self, data, dna, traits):
        self.game_id = data['game']['id']
        self.turn = data['turn']

        self.board = Board(data['board'])
        self.me = Snake(data['you'])

        # If no DNA is passed in, use the default values
        self.dna = [
            int(dna or DEFAULT_DNA[i]) for i, dna in enumerate(dna.split('-'))
        ] if dna else DEFAULT_DNA
        self.traits = traits.split('-')
Пример #5
0
class GameOrchestrator:
    def __init__(self, input_data):
        """
        Create the board.
        Make sure the initial_position is a valid move
        Add the initial_position to the path_history and set coins to 0
        """
        self.board = Board(*input_data.board_dimension, input_data.walls)
        if self.board.is_valid_move(*input_data.initial_position):
            self.the_pacman = ThePacman(*input_data.initial_position)
        else:
            raise PositionException(
                "The pacman can not be placed at the location: {}".format(
                    input_data.initial_position))
        self.movements = input_data.movements
        self.path_history = {input_data.initial_position}
        self.coins = 0

    def play(self) -> Tuple[int, int, int]:
        """
        play loop over the list of movements and execute them
        For each move, it check if it is a valid one
        For each valid move it will record the past history and compute the collected coins
        'return': "a tuple of [int, int, int] representing position x, y, and collected coins at the end of the game"
        """
        for move in self.movements:
            if self.board.is_valid_move(*self.the_pacman.move(move).coord()):
                self.the_pacman = self.the_pacman.move(move)
                coord = self.the_pacman.coord()
                if coord not in self.path_history:
                    LOG.debug("%s is not in path history: %s", coord,
                              self.path_history)
                    self.coins = self.coins + 1
                    LOG.debug("The number of coins is now: %s", self.coins)
                    self.path_history.add(coord)
        coord = self.the_pacman.coord()
        return (coord[0], coord[1], self.coins)
Пример #6
0
 async def start(self):
     if not self.can_start():
         await self.print_group(
             f"Игра отменена. Требуется минимум {Game.MIN_PLAYERS} игроков")
         self.app["events"].unsubscribe_callback(self.group_chat_id)
         for p in self.channels:
             self.app["events"].unsubscribe_callback(p.user_id, self)
         return
     await self.print_group(game_info["description"] +
                            game_info["on_start_tip"])
     if self.app["cfg"].DEBUG:
         self.channels = [{
             "group_chat_id": self.group_chat_id,
             "user_id": 435627225,
             "user_fullname": "Дмитрий Калекин",
             "user_alert": "@herr_horror Дмитрий"
         }, {
             "group_chat_id": self.group_chat_id,
             "user_id": 435627225,
             "user_fullname": "Dmitriy Zaytsev",
             "user_alert": "@1"
         }, {
             "group_chat_id": self.group_chat_id,
             "user_id": 435627225,
             "user_fullname": "Zag",
             "user_alert": "@2"
         }, {
             "group_chat_id": self.group_chat_id,
             "user_id": 435627225,
             "user_fullname": "Александр Грицай",
             "user_alert": "@3"
         }]
     self.board = Board(self.channels)
     for p in self.board.players:
         assert type(p) == Player
         self.app["events"].subscribe_callback(p.user_id, self)
     await self.run()
Пример #7
0
    def test_iterate_all_moves_with_one_piece(self):
        b = Board().place_piece(p2)

        expected = [((0, 0), m) for m in b.iterate_moves_for_piece(p2)]
        self.assertEqual(list(b.iterate_all_moves(Owner.PLAYER)), expected)
Пример #8
0
 def test_iterate_moves_for_piece_forbids_attacking_in_camp(self):
     b = Board().place_piece(p1).place_piece(opponent)
     self.assertEqual(len(list(b.iterate_moves_for_piece(p1))), 3)
     self.assertFalse((1, 2) in list(b.iterate_moves_for_piece(p1)))
     self.assertTrue((0, 1) in list(b.iterate_moves_for_piece(opponent)))
Пример #9
0
 def test_iterate_moves_for_piece_forbids_moving_onto_blocked_spaces(self):
     b = Board().place_piece(p2).place_piece(p1)
     self.assertEqual(list(b.iterate_moves_for_piece(p2)), [(1, 0)])
Пример #10
0
 def test_iterate_moves_for_piece_simple(self):
     b = Board().place_piece(p2)
     self.assertEqual(list(b.iterate_moves_for_piece(p2)), [(0, 1), (1, 0)])
Пример #11
0
 def test_board_cell_at(self):
     board = Board(raws=10, cols=10)
     self.assertTrue(isinstance(board.cell_at(10, 10), Cell))
Пример #12
0
from app.board import Board

print("""Welcome to Plinko! 

This tool was made as an analyzer to determine which
slot on the Plinko board will yield the highest return.

Basic instructions are simple: Drop a chip into a slot
at the top of the Plinko board, and see where it lands.
At each row down through the board, the chip will either
go to the left of the peg or to the right.

Here is an example of a Plinko board """)
print()

b = Board()
b.print_board()

print()
print("""As you can see at the bottom of the board, there are five
different options for what payout you can receive. They are:

Small:          $100
Medium:         $500
Large:          $1000
Grand Prize:    $10000
Blank Space:    $0

Get started! Find out which slot will be your best bet.""")
Пример #13
0
class TestBoard(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_board_initailizes_with_empty_board(self):
        empty_board = {
            1: ' ',
            2: ' ',
            3: ' ',
            4: ' ',
            5: ' ',
            6: ' ',
            7: ' ',
            8: ' ',
            9: ' '
        }
        self.assertEqual(self.board.game_board(), empty_board)

    def test_set_arkBoard_puts_X_on_board(self):
        self.board.set_mark_board("X", 3)
        self.assertEqual(self.board.game_board()[3], "X")

    def test_board_isCellOccupied_method_returns_true_if_cell_occupied(self):
        self.board.set_mark_board("X", 3)
        self.assertEqual(self.board.is_cell_occupied(3), True)

    def test_board_isCellOccupied_method_returns_false_if_cell_not_occupied(
            self):
        self.assertEqual(self.board.is_cell_occupied(3), False)

    def test_board_isBoardFull_method_returns_false_if_board_not_full(self):
        self.board.set_mark_board("X", 1)
        self.assertEqual(self.board.is_board_full(), False)

    def test_board_isBoardFull_method_returns_true_if_board_full(self):
        self.board.set_mark_board("X", 1)
        self.board.set_mark_board("X", 2)
        self.board.set_mark_board("X", 3)
        self.board.set_mark_board("X", 4)
        self.board.set_mark_board("X", 5)
        self.board.set_mark_board("X", 6)
        self.board.set_mark_board("X", 7)
        self.board.set_mark_board("X", 8)
        self.board.set_mark_board("X", 9)
        self.assertEqual(self.board.is_board_full(), True)
Пример #14
0
 def setUp(self):
     self.board = Board()
Пример #15
0
 def test_piece_at_with_piece(self):
     b = Board().place_piece(p1)
     self.assertEqual(b.piece_at((0, 1)), p1)
Пример #16
0
 def test_piece_at_with_no_piece(self):
     b = Board()
     self.assertEqual(b.piece_at((0, 0)), None)
Пример #17
0
 def test_serialize_board_with_piece(self):
     b = Board().place_piece(p1)
     self.assertEqual(b.serialize(), "( ( A2 1 ) )")
Пример #18
0
 def test_iterate_all_moves_with_landmine_and_flag(self):
     b = Board().place_piece(landmine).place_piece(flag)
     self.assertEqual(list(b.iterate_all_moves(Owner.PLAYER)), [])
Пример #19
0
    def test_place_figures_on_board(self):
        board = Board(raws=3, cols=3)

        self.assertEqual(board.add_figure(KingFigure), (0, 0))
        print [(cell.x, cell.y, cell.value) for _, cell in board.cells.iteritems()]
Пример #20
0
    def test_iterate_all_moves_with_multiple_pieces(self):
        b = Board().place_piece(p2).place_piece(p1)

        expected = ([((0, 0), m) for m in b.iterate_moves_for_piece(p2)] +
                    [((0, 1), m) for m in b.iterate_moves_for_piece(p1)])
        self.assertEqual(list(b.iterate_all_moves(Owner.PLAYER)), expected)
Пример #21
0
def test_data(rows=3, columns=3, row=2, column=6, start="4.5"):
    tour = Tour(rows, columns, start, verbosity=0)
    board = Board(rows, columns, tour.verbosity.verbose_int)
    position = Position(row, column, board, tour.verbosity.verbose_int)
    knight = Knight(position, tour.verbosity.verbose_int)
    return tour, board, position, knight
Пример #22
0
 def __init__(self):
     self.player1 = Player()
     self.player2 = Player()
     self.board_control = Board()
     self.game_board = self.board_control.game_board()
Пример #23
0
 def test_move_piece(self):
     b = Board().place_piece(p2).move_piece((0, 0), (0, 1))
     self.assertTrue(isinstance(b.piece_at((0, 1)), Piece))
     self.assertEqual(b.piece_at((0, 0)), None)
Пример #24
0
from flask import Flask, _app_ctx_stack
from app.config import Config
from flask_wtf.csrf import CSRFProtect
from flask_bootstrap import Bootstrap
from celery import Celery
from app.board import Board
from sqlalchemy.orm import scoped_session
from .database import SessionLocal, engine

app = Flask(__name__)
app.config.from_object(Config)

app.session = scoped_session(SessionLocal,
                             scopefunc=_app_ctx_stack.__ident_func__)

csrf = CSRFProtect(app)
bootstrap = Bootstrap(app)

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

board = Board()

from app import routes
Пример #25
0
class Game:
    MIN_PLAYERS = 4
    STATUS_PENDING = "pending"
    STATUS_LAUNCHED = "launched"
    STATUS_CANCELED = "canceled"

    def __init__(self, group_chat_id, app):
        self.group_chat_id = group_chat_id
        self.channels = []
        self.status = Game.STATUS_PENDING
        self.board = None
        self.app = app
        self.app["events"].subscribe_callback(self.group_chat_id, self)
        self.callback_input = dict()
        self.table = "```Здесь отобразится стол```"
        self.log = ["```Здесь лог событий```"]

    async def update_callback(self, callback: Callback):
        assert type(callback.sender) == User
        if callback.chat_id not in self.callback_input:
            self.callback_input[callback.chat_id] = []
        self.callback_input[callback.chat_id].append(callback)
        await asyncio.sleep(0)
        return

    def add_player(self, player_id):
        if player_id not in self.channels:
            self.channels.append(player_id)

    def can_start(self) -> bool:
        return True  # TODO: delete
        return len(self.channels) >= Game.MIN_PLAYERS

    async def start(self):
        if not self.can_start():
            await self.print_group(
                f"Игра отменена. Требуется минимум {Game.MIN_PLAYERS} игроков")
            self.app["events"].unsubscribe_callback(self.group_chat_id)
            for p in self.channels:
                self.app["events"].unsubscribe_callback(p.user_id, self)
            return
        await self.print_group(game_info["description"] +
                               game_info["on_start_tip"])
        if self.app["cfg"].DEBUG:
            self.channels = [{
                "group_chat_id": self.group_chat_id,
                "user_id": 435627225,
                "user_fullname": "Дмитрий Калекин",
                "user_alert": "@herr_horror Дмитрий"
            }, {
                "group_chat_id": self.group_chat_id,
                "user_id": 435627225,
                "user_fullname": "Dmitriy Zaytsev",
                "user_alert": "@1"
            }, {
                "group_chat_id": self.group_chat_id,
                "user_id": 435627225,
                "user_fullname": "Zag",
                "user_alert": "@2"
            }, {
                "group_chat_id": self.group_chat_id,
                "user_id": 435627225,
                "user_fullname": "Александр Грицай",
                "user_alert": "@3"
            }]
        self.board = Board(self.channels)
        for p in self.board.players:
            assert type(p) == Player
            self.app["events"].subscribe_callback(p.user_id, self)
        await self.run()

    # TODO: ------------------------------- refactor -------------------

    async def show_cards_to_all(self):
        if self.app["cfg"].DEBUG:
            for p in self.board.players:
                await self.show_cards(p)
        else:
            await asyncio.gather(
                *[self.show_cards(p) for p in self.board.players])

    async def show_cards(self, p: Player):
        # if not p.title_message_id:
        #     r1 = await self.app["telebot"].sendMessage(p.user_id, f"Ваше имя: *{p.user_fullname}* -------------------------------- ")
        #     p.title_message_id = r1["result"]["message_id"]

        if not p.table_message_id:
            r2 = await self.app["telebot"].sendMessage(p.user_id, self.table)
            p.table_message_id = r2["result"]["message_id"]

        if not p.hand_slots or len(p.hand_slots) == 0:
            await self.create_image_slots(p)
        else:
            await self.update_image_slots(p)

        if not p.panel_message_id:
            r3 = await self.app["telebot"].sendMessage(
                p.user_id,
                f"`[Это сообщение обновится, и вы выберете ваше действие с картами]`"
            )
            p.panel_message_id = r3["result"]["message_id"]
        else:
            await self.app["telebot"].editMessageText(p.user_id,
                                                      p.panel_message_id,
                                                      "\r\n".join(p.local_log))

        if not p.log_message_id:
            r4 = await self.app["telebot"].sendMessage(p.user_id,
                                                       "\n".join(self.log))
            p.log_message_id = r4["result"]["message_id"]
        return

    async def show_play_drop_options(self, p):
        await self.app["telebot"].editMessageText(
            p.user_id,
            p.panel_message_id,
            "\r\n".join(p.local_log),
            reply_markup={
                "inline_keyboard": [
                    *[[{
                        "text": f"▶️ {play_card.name}",
                        "callback_data": f"phase2:play_card {play_card.uuid}"
                    }] for play_card in p.get_possible_play()],
                    *[[{
                        "text": f"🗑 {drop_card.name}",
                        "callback_data": f"phase2:drop_card {drop_card.uuid}"
                    }] for drop_card in p.get_possible_drop()]
                ]
                # 🖐  🕹 Joystick 🗑 Wastebasket ☣ Biohazard 🎮 🎯 Direct Hit
            },
            parse_mode="markdown")

    async def show_give_options(self, p, receiver, can_def=False):
        def_buttons = []
        if can_def:
            def_buttons = [[{
                "text":
                f"🛡 {block_card.name}",
                "callback_data":
                f"phase3:block_exchange_card {block_card.uuid}"
            }] for block_card in p.get_possible_block_exchange()]

        await self.app["telebot"].editMessageText(
            p.user_id,
            p.panel_message_id,
            "\r\n".join(p.local_log),
            reply_markup={
                "inline_keyboard": [
                    *[[{
                        "text": f"🎁 {give_card.name}",
                        "callback_data": f"phase3:give_card {give_card.uuid}"
                    }] for give_card in p.get_possible_give(receiver)],
                    *def_buttons
                ]
                #   🕹 Joystick 🗑 Wastebasket ☣ Biohazard 🎮 🎯 Direct Hit
            },
            parse_mode="markdown")

    async def print_group(self, msg: str, **kwargs):
        return await self.app["telebot"].sendMessage(self.group_chat_id, msg,
                                                     **kwargs)

    async def listen_input(self, p: Player):
        while True:
            await asyncio.sleep(1)
            if p.user_id not in self.callback_input:
                continue
            events = self.callback_input[p.user_id]
            index = None
            for i, clb in enumerate(events):
                if clb.message_id == p.panel_message_id:
                    index = i
            if index is not None:
                c = self.callback_input[p.user_id].pop(index)
                return c.data, p

    async def clear_input(self, p: Player):
        assert p.panel_message_id is not None
        return await self.app["telebot"].editMessageText(
            p.user_id, p.panel_message_id, "\r\n".join(p.local_log))

    async def show_table_to_all(self, table):
        assert type(self.board.players) == list
        await asyncio.gather(
            *[self.show_table(p, table) for p in self.board.players])
        return

    async def show_table(self, p: Player, table: str):
        try:
            await self.app["telebot"].editMessageText(p.user_id,
                                                      p.table_message_id,
                                                      table)
        except Warning:
            print("Стол остался прежним")

    async def show_log_to_all(self, msg: str):
        self.log.append(msg)
        while len(self.log) > 6:
            _ = self.log.pop(0)
        assert type(self.board.players) == list
        for p in self.board.players:
            await self.show_log(p)
            # self.app.loop.create_task(self.show_log(p))
        return

    async def show_log(self, p: Player):
        await self.app["telebot"].editMessageText(p.user_id, p.log_message_id,
                                                  "\n".join(self.log))

    async def create_image_slots(self, p):
        """
        Создаём слоты для изображений 
        """

        top_card_image = "https://eva-bot.ru/res/normal/min/top-card-950x1343-min.png"
        media = list([
            f"https://eva-bot.ru/res/normal/min/{choice(h.images)}-950x1343-min.png"
            for h in p.hand
        ])
        if len(media) < 5:
            media.append(top_card_image)

        r2 = await self.app["telebot"].sendMediaGroup(
            p.user_id,
            list([{
                "type": "photo",
                "media": image
            } for image in media]))
        for i, msg in enumerate(r2["result"]):
            p.hand_slots.append(msg["message_id"])

    async def update_image_slots(self, p):
        """
        Обновляем слоты для изображений -  только изменившиеся
        """
        counter = 0
        for card in p.hand:
            assert type(card) == Card
            image = f"https://eva-bot.ru/res/normal/min/{choice(card.images)}-950x1343-min.png"
            try:
                self.app.loop.create_task(self.app["telebot"].editMessageMedia(
                    p.user_id, p.hand_slots[counter], {
                        "type": "photo",
                        "media": image
                    }))
            except Warning:
                print(f"Изображение карты осталось старым: {card.name}")
            counter += 1

        for i in range(counter, len(p.hand_slots)):
            image = "https://eva-bot.ru/res/normal/min/top-card-950x1343-min.png"
            try:
                self.app.loop.create_task(self.app["telebot"].editMessageMedia(
                    p.user_id, p.hand_slots[counter], {
                        "type": "photo",
                        "media": image
                    }))
            except Warning:
                print(f"Изображение осталось старым: top-card")

    def print_hands(self):
        output = f"Ход {self.board.move}, ходит *{self.board.current_player().user_fullname}* \r\n"
        for i, p in enumerate(self.board.players):
            turn = "✅" if i == self.board.turn else "⏳"  # ☣️ # 🤢
            # output += "```"
            name = f"*{p.name}*" if p == self.board.current_player(
            ) else p.name
            output += f"{turn} {p.avatar} {name}\r\n"
            # output += "```"
            # for o in p.get_cards_names():
            #     if o == "Заражение":
            #         output += "`[`🤢`" + o + "]`; "
            #     if o == "Нечто":
            #         output += "`[`🍄`" + o + "]`; "
            #     else:
            #         output += "`[" + o + "]`; "
            if len(p.global_log) > 0:
                output += '\r\n'.join(
                    [f"             `{s}`" for s in p.global_log]) + "\r\n"
            else:
                output += "`       ...`\r\n"
        return output

    async def phase1(self, p: Player) -> bool:
        """
        Фаза взятия карты и игры паники
        Возвращает необходимость продолжать код
        """
        # p.global_log = "тянет карту с колоды..."
        # await self.show_table_to_all()
        # await self.show_log_to_all(f"Фаза 1. {p.user_fullname} тянет карту с колоды")
        card = p.pull_deck()
        assert type(card) == Card
        if not card.is_panic():
            p.take_on_hand(card)
            p.local_log.append(f"🎲 событие `{card.name}` c колоды")
            p.global_log.append(f"🎲 Вытянул событие из колоды")
            await self.show_cards(p)
            return True
        else:
            p.local_log.append(
                f"🔥 паника `{card.name}` с колоды, ход завершён.")
            p.global_log.append(
                f"🔥 Вытянул панику `{card.name}` с колоды. Ход завершён.")
            p.play_panic(card)
            self.board.deck.append(card)  # карта паники ушла в колоду
            return False
        return True

    async def phase2(self, p: Player):
        """
        Фаза сброса или игры карты с руки
        """
        # Обновили карты на руке игрока и ждём от него хода
        # await self.show_cards(p)
        p.local_log.append(f"❗️ Сыграйте ▶️ или сбросьте 🗑 карту...")
        p.global_log.append(f"🃏 Играет или сбрасывает...")
        await asyncio.gather(*[
            self.show_play_drop_options(p),
            self.show_table_to_all(self.print_hands())
        ])

        cmd = None
        # while cmd not in ["phase2:play_card", "phase2:drop_card"]:
        # await asyncio.sleep(0)
        full_input, triggered_player = await self.listen_input(p)
        cmd, card_uuid = full_input.split(" ")
        assert cmd == "phase2:play_card" or cmd == "phase2:drop_card"
        assert triggered_player == p
        card = p.pop_card_by_uuid(int(card_uuid))  # выбранная карта
        assert type(card) == Card
        if cmd == "phase2:play_card":
            p.play_card(card, target=None)
            p.local_log[-1] = f"▶️ сыграна `{card.name}`"
            p.global_log[-1] = f"▶️ Сыграл карту `{card.name}`"
        else:
            p.local_log[-1] = f"🗑 сброшена `{card.name}`"
            p.global_log[-1] = f"🗑 Сбросил карту"

        await self.clear_input(p)

        p.drop_card(card)  # в любом случае в колоду
        await asyncio.gather(
            *[self.show_cards(p),
              self.show_table_to_all(self.print_hands())])
        return

    async def proccess_exchange(self, p: Player, next_player: Player):
        full_input, player = await self.listen_input(p)
        assert player == p
        cmd, card_uuid = full_input.split(" ")
        # BUG: assertion error here
        assert cmd in ["phase3:give_card", "phase3:block_exchange_card"]
        my_card = player.pop_card_by_uuid(int(card_uuid))
        assert type(my_card) == Card

        if cmd == "phase3:give_card":
            player.local_log[
                -1] = f"🎁 отдана `{my_card.name}` для *{next_player.user_fullname}*"
            player.global_log[
                -1] = f"♣️ Отдал карту для {next_player.user_fullname}"

            await asyncio.gather(*[
                self.clear_input(player),
                self.show_cards(player),
                self.show_table_to_all(self.print_hands())
            ])
        else:
            assert cmd == "phase3:block_exchange_card"
            player.local_log[
                -1] = f"🛡 сыграна защита `{my_card.name}` от *{next_player.user_fullname}*"
            player.global_log[
                -1] = f"🛡 Защитился `{my_card.name}` от обмена с {next_player.user_fullname}"

            await asyncio.gather(*[
                self.clear_input(player),
                self.show_cards(player),
                self.show_table_to_all(self.print_hands())
            ])
        return player, my_card

    async def phase3(self, p: Player):
        next_player = self.board.player_next()
        p.local_log.append(f"❗️ Передайте карту *{next_player.user_fullname}*")
        p.global_log.append(f"💤 Передаёт карту {next_player.user_fullname}")

        next_player.local_log.append(
            f"❗️ Передайте карту *{p.user_fullname}*, либо защититесь 🛡 от обмена."
        )
        next_player.global_log.append(f"💤 Передаёт карту {p.user_fullname}")

        exchangers = await asyncio.gather(*[
            self.show_give_options(p, next_player),
            self.show_give_options(next_player, p, can_def=True),
            self.show_table_to_all(self.print_hands()),
            self.proccess_exchange(p, next_player),
            self.proccess_exchange(next_player, p)
        ])
        p1, card1 = exchangers[3]
        p2, card2 = exchangers[4]
        assert type(p1) == Player
        assert type(p2) == Player
        assert type(card1) == Card
        assert type(card2) == Card
        p1.take_on_hand(card2, sender=p2)
        p2.take_on_hand(card1, sender=p1)

        p1.local_log.append(
            f"🤲 получена `{card2.name}` от *{p2.user_fullname}*")
        p2.local_log.append(
            f"🤲 получена `{card1.name}` от *{p1.user_fullname}*")
        p1.global_log[-1] = f"👌🏻 Передал карту {p2.user_fullname}"
        p2.global_log[-1] = f"👌🏻 Передал карту {p1.user_fullname}"

        await asyncio.gather(*[
            self.app.loop.create_task(self.show_cards(p1)),
            self.app.loop.create_task(self.show_cards(p2)),
            self.app.loop.create_task(
                self.show_table_to_all(self.print_hands()))
        ])
        return

    async def run(self):
        # До старта игры показываем карты игрокам, пишем историю ситуации и ждём, чтобы они прочитали
        p = None
        await self.show_cards_to_all()
        while not self.board.is_end:
            await asyncio.sleep(0)

            if p:
                p.global_log = []
                p.local_log.append("`----------`")
                if len(p.local_log) > 10:
                    for _ in range(0, 5):
                        p.local_log.pop(0)

            self.board.next_turn()
            p = self.board.current_player()

            # Рисуем стол и очередность в общем чате
            await self.show_table_to_all(self.print_hands())
            # await self.print_group(self.table)
            # Тянем карту: либо паника и переход хода, либо фаза сыграть карту с руки
            p.global_log = []
            if len(p.local_log) > 0:
                p.local_log.append("`----------`")

            if not await self.phase1(p):
                print("=============================")
                # self.app.loop.create_task(self.delay_flush(p))
                continue
            await self.phase2(p)
            await self.phase3(p)
            # await self.app.loop.create_task(self.delay_flush(p))
            print("=============================")
        await self.print_group("game ended")
        return
Пример #26
0
 def test_remove_piece(self):
     p = Piece((0, 0), Owner.PLAYER, Rank('1'))
     mt = Board()
     b = Board().place_piece(p).remove_piece((0, 0))
     self.assertEqual(mt.serialize(), b.serialize())
Пример #27
0
class Game():
    def __init__(self):
        self.player1 = Player()
        self.player2 = Player()
        self.board_control = Board()
        self.game_board = self.board_control.game_board()

    def start_game(self):
        print("Welcome to TicTacToe")
        print("What is Player1s Name?")
        player1_name = input(" : ")
        self.player1.set_name(player1_name)
        print("What is Player2s Name?")
        player2_name = input(" : ")
        self.player2.set_name(player2_name)
        print(
            "Here is the board. Each cell of the grid is represented by the numbers 1 - 9 going from left to right, top to bottom."
        )
        self.player1_turn = True

    def take_turn(self, mark, input_given):
        self.check_if_cell_is_occupied(input_given)
        self.board_control.set_mark_board(mark, input_given)
        self.board_control.print_board()
        if self.is_game_won():
            self.win_message()

    def check_if_cell_is_occupied(self, input_given):
        if self.board_control.is_cell_occupied(input_given):
            print("That place is taken")
            self.game_active_loop()

    def win_message(self):
        self.game_active = False
        if self.player1_turn == True:
            print(self.player1.name + " Wins! Congratulations!")
        else:
            print(self.player2.name + " Wins! Congratulations!")
        return "You Win!"

    def is_game_won(self):
        win_conds = ((1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8),
                     (3, 6, 9), (1, 5, 9), (3, 5, 7))
        for win_cond in win_conds:
            if self.game_board[win_cond[0]] == self.game_board[win_cond[
                    1]] and self.game_board[win_cond[1]] == self.game_board[
                        win_cond[2]] and self.game_board[win_cond[0]] != ' ':
                return True

    def main(self):
        self.game_active = True
        self.start_game()
        self.game_active_loop()

    def check_input_between_1_and_9(self, input_given):
        try:
            if input_given > 9 or input_given < 1:
                raise Exception
        except:
            print('Pick a number between 1-9')
            return self.game_active_loop()

    def game_active_loop(self):
        while self.game_active:
            if self.player1_turn == True:
                position = int(raw_input("Choose a place to put your mark"))
                self.check_input_between_1_and_9(position)
                mark = "X"
                self.take_turn(mark, position)
                self.player1_turn = False
            else:
                position = int(raw_input("Choose a place to put your mark"))
                self.check_input_between_1_and_9(position)
                mark = "O"
                self.take_turn(mark, position)
                self.player1_turn = True

            self.check_if_draw()

    def check_if_draw(self):
        if self.board_control.is_board_full():
            print("Its a draw!! You both lose!")
            self.game_active = False
Пример #28
0
 def test_is_space_blocked_for(self):
     b = Board().place_piece(p2)
     self.assertTrue(b.is_space_blocked_for((0, 0), Owner.PLAYER))
     self.assertFalse(b.is_space_blocked_for((0, 0), Owner.OPPONENT))
     self.assertFalse(b.is_space_blocked_for((0, 1), Owner.PLAYER))
     self.assertFalse(b.is_space_blocked_for((0, 1), Owner.OPPONENT))
Пример #29
0
def run_water(zone, alias, minutes):
    with SessionLocal() as db:
        start_time = datetime.now()
        b = Board(
        )  # init a new board since tasks dont seem to have GPIO setup...
        b.register_flow()

        temperature = b.get_temp()
        db.add(Temperature(temperature))
        db.commit()

        #     moisture0 = board.read_analog_sensor(analog0)
        #     moisture1 = board.read_analog_sensor(analog1)
        #     moisture2 = board.read_analog_sensor(analog2)
        #     moisture3 = board.read_analog_sensor(analog3)
        #     sql_helper.insert_moistures(moisture0, moisture1, moisture2, moisture3)

        b.set_high(pins[zone])
        time.sleep(minutes *
                   60)  # sleep for our duration with the solenoid open
        b.set_low(pins[zone])

        water_used = b.read_water_flow()
        db.add(Water(zone, alias, start_time, water_used))
        db.commit()

        b.deregister_flow()
Пример #30
0
 def test_iterate_pieces_with_opponent_pieces(self):
     b = Board().place_piece(p1).place_piece(p2).place_piece(opponent)
     self.assertEqual(len(list(b.iterate_pieces(Owner.PLAYER))), 2)
     self.assertEqual(len(list(b.iterate_pieces(Owner.OPPONENT))), 1)