Beispiel #1
0
def random_data(tile_collection: TileCollection,
                random: random.Random) -> Tuple[int, int]:
    """
    Simulates a randomly swiping user and returns the score and the number of
    made valid moves.
    :param tile_collection:
    :param random:
    :return:
    """
    game_field = GameField(tile_collection)
    game_controller = GameController(game_field, tile_collection)
    game_controller.initialize()

    moves = 0
    actions = [
        game_controller.swipe_north_action, game_controller.swipe_east_action,
        game_controller.swipe_south_action, game_controller.swipe_west_action
    ]
    while True:
        try:
            # do anything
            action = random.choice(actions)
            action()
            moves += 1
        except InvalidActionError as _:
            # if the action was invalid, ignore and keep going
            pass
        except GameLostError as e:
            # if the game is lost, break out of the loop
            if isinstance(e, GameLostError):
                break
    # print score
    return game_controller.score, moves
Beispiel #2
0
def main():
    """
    Main function of the program
    From there the game is initialized
    :return: nothing
    """
    gameController = GameController("sentences.txt")
    gameController.runProgram()
    def __init__(self):
        BaseController.__init__(self, SERVICE_NAME)
        self.current_username = None
        self.current_user_id = None
        self.current_user_point = -1

        self.c.register(LOGIN_ID, self.login_callback)

        self.game_controller = GameController()
Beispiel #4
0
 def test_swipeWest(self):
     """
     Test that issueing a swipeNorthAction uses the west-ward iterator.
     """
     self.game_field = create_autospec(GameField)
     self.game_field.field_data = {}
     self.game_controller = GameController(self.game_field, self.tile_collection)
     self.game_controller._random.seed(1337)
     self.game_controller._swipe = MagicMock()
     self.game_controller.swipe_west_action()
     self.game_field.get_west_iterator.assert_any_call()
     self.game_controller._swipe.assert_called_with(self.game_field.get_west_iterator())
 def __init__(self):
     self.counter_debug = 0
     super().__init__()
     self.gc = GameController()
     self.initUI()
     self.activate_coor = []  # tuple x,y
     self.move_coor = []
     self.atk_coor = []
     self.INACTIVE_PAWN_CSS = "background-color: #9AAC41;"
     self.ACTIVE_PAWN_CSS = "background-color: #E1FE57"
     self.ACTIVATE_PAWN_CSS = "background-color: green; color: white; font-weight: 500;"
     self.TILE_MOVE_CSS = "background-color: #53F399;"
     self.TILE_ATK_CSS = "background-color: #FF3500;"
     self.PROMOTE_PAWN_CSS = "background-color: #2e00ff; color: white;"
Beispiel #6
0
class GameControllerTest(TestCase):

    def setUp(self):
        self.fileName = "test_sentences.txt"
        self.controller = GameController(self.fileName)

    def test_addSentence(self):
        with open(self.fileName, "w") as f:
            pass

        sent_words = ["jhon", "has", "apples"]
        self.controller.addSentence(sent_words)
        with self.assertRaises(Exception):
            self.controller.addSentence(sent_words)
Beispiel #7
0
    def test_initialization_enables_score(self):
        """
        Tests, that calling GameController.initialize() allows to acces GameCon-
        troller.score afterwards. Before, it raises a GameNotInitializedError.
        """
        self.game_field = GameField.basic_field(self.tile_collection)
        self.game_controller = GameController(
            self.game_field,
            self.tile_collection
        )

        with self.assertRaises(GameNotInitializedError):
            score = self.game_controller.score
        self.game_controller.initialize()
        self.assertEqual(0, self.game_controller.score)
Beispiel #8
0
 def __init__(
         self,
         input_stream: ConsoleInput,
         output_stream: ConsoleOutput
 ):
     self.input = input_stream
     self.output = output_stream
     self.tile_collection = TileCollection()
     self.game_field = GameField.basic_field(self.tile_collection)
     self.game_controller = GameController(
         self.game_field,
         self.tile_collection
     )
     self.game_controller.initialize()
     self.renderer = ConsoleRenderer(output_stream)  # type: Renderer
     self.prompt_counter = 0
Beispiel #9
0
    def initBuild(self, time):
        board = ChessBoardModel("black", "white")
        self._isPaused = False
        gameManager = GameManager(board, time)
        self.gameController = GameController(self, gameManager)
        self.selectMenu = None

        self.screenFrame = Frame()
        self.screenFrame.place(relx=0, rely=0, width=1000, height=800)

        self.statusBar = StatusBar(self.screenFrame, self.buttonClick,
                                   self.buttonBackClick)
        self.statusBar.place(relx=0, rely=0, width=200, height=800)
        self.chessBoard = ChessBoard(self.screenFrame, self.gameController,
                                     self._screenManager.imageHandler)
        self.chessBoard.place(x=200, y=12, width=800, height=800)

        threading.Timer(1, lambda: [self.update(onlyClock=True)]).start()

        self.update()
Beispiel #10
0
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        self.rid = LOBBY_ROOM_ID
        self.parent = parent
        self.setGeometry(0, 0, 800, 600)

        self.game_controller = GameController()
        # UI
        self.game_list_widget = GameListWidget(self)
        # self.game_windows = GameWindow(self, rid=1)
        #self.game_list_widget.doubleClicked.connect(self.game_list_widget.double_click_on_item)
        self.game_list_widget.setGeometry(40, 40, 550, 450)
        # self.game_list_widget.connect(BaseController(service_name='game_controller'),
        #                              SIGNAL('add_game_item(QString)'),
        #                              self.game_list_widget.add_game_item,
        #                              Qt.DirectConnection)

        self.rankTitle = QLabel(self)
        self.rankTitle.setText('Rank')
        self.rankTitle.setStyleSheet(
            QString(u"font: 75 14pt \"微软雅黑\";\n \
                                               color: rgb(100, 100, 200);"))
        self.rankTitle.setAlignment(Qt.AlignCenter)
        self.rankTitle.setGeometry(600, 20, 190, 20)
        self.rankList = RankList(self)
        self.rankList.setGeometry(600, 55, 190, 180)

        self.lobbyChat = ChatWidget(self)
        self.lobbyChat.input_box.setGeometry(600, 480, 190, 30)
        self.lobbyChat.chat_view.setGeometry(600, 250, 190, 220)

        self.lobbyChat.chat_view.connect(
            ChatController(),
            SIGNAL('showRoomTextWithRGB(QString,int,int,int)'),
            self.lobbyChat.chat_view.showText)
        self.lobbyChat.chat_view.connect(ChatController(), SIGNAL('clear'),
                                         self.lobbyChat.chat_view.clear)
        self.lobbyChat.chat_view.connect(
            GameController(),
            SIGNAL('showRoomTextWithRGB(QString,int,int,int)'),
            self.lobbyChat.chat_view.showText)
Beispiel #11
0
def random_data(
        tile_collection: TileCollection,
        random: random.Random
) -> Tuple[int, int]:
    """
    Simulates a randomly swiping user and returns the score and the number of
    made valid moves.
    :param tile_collection:
    :param random:
    :return:
    """
    game_field = GameField(tile_collection)
    game_controller = GameController(game_field, tile_collection)
    game_controller.initialize()

    moves = 0
    actions = [
        game_controller.swipe_north_action,
        game_controller.swipe_east_action,
        game_controller.swipe_south_action,
        game_controller.swipe_west_action
    ]
    while True:
        try:
            # do anything
            action = random.choice(actions)
            action()
            moves += 1
        except InvalidActionError as _:
            # if the action was invalid, ignore and keep going
            pass
        except GameLostError as e:
            # if the game is lost, break out of the loop
            if isinstance(e, GameLostError):
                break
    # print score
    return game_controller.score, moves
Beispiel #12
0
    def __init__(self, parent=None):
        QListView.__init__(self, parent)
        self.game_list = []
        self.model = QStandardItemModel()
        self.setModel(self.model)
        self.setWordWrap(True)
        self.setUniformItemSizes(True)
        self.setGridSize(QSize(self.rect().width(), 30))
        self.setFont(QFont("Microsoft YaHei", 10))
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # self.setFocusPolicy(Qt.NoFocus)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #self.setAcceptDrops(True)
        self.game_controller = GameController()
        self.game_controller.connector.connect(SIGNAL('game_list'),
                                               self.add_game_item)
        self.game_controller.connector.connect(SIGNAL('game_list_clear'),
                                               self.clear)

        self.clicked.connect(self.double_click_on_item)  ## ??????
Beispiel #13
0
 def __init__(self, loader):
     super().__init__(logger=getLogger('root.app.controller'))
     self.loader = loader
     self.view = AppView(controller=self)
     self.model = AppModel(controller=self, view=self.view)
     self.fade_in_animation = AppFadeInAnimation(self.view)
     self.fade_out_animation = AppFadeOutAnimation(self.view)
     self.main_menu = MainMenuController(self)
     self.onboarding = OnboardingController(self)
     self.license = LicenseController(self)
     self.game = GameController(self)
     self.settings = SettingsController(self)
     self.bonus_code_activation = BonusCodeActivationController(self)
     self.main_menu_to_game_transition_animation = TransitionAnimation(
         fade_out_animation=self.main_menu.fade_out_animation,
         fade_in_animation=self.game.fade_in_animation)
     self.main_menu_to_onboarding_transition_animation = TransitionAnimation(
         fade_out_animation=self.main_menu.fade_out_animation,
         fade_in_animation=self.onboarding.fade_in_animation)
     self.game_to_main_menu_transition_animation = TransitionAnimation(
         fade_out_animation=self.game.fade_out_animation,
         fade_in_animation=self.main_menu.fade_in_animation)
     self.main_menu_to_license_transition_animation = TransitionAnimation(
         fade_out_animation=self.main_menu.fade_out_animation,
         fade_in_animation=self.license.fade_in_animation)
     self.license_to_main_menu_transition_animation = TransitionAnimation(
         fade_out_animation=self.license.fade_out_animation,
         fade_in_animation=self.main_menu.fade_in_animation)
     self.game_to_settings_transition_animation = TransitionAnimation(
         fade_out_animation=self.game.fade_out_animation,
         fade_in_animation=self.settings.fade_in_animation)
     self.settings_to_game_transition_animation = TransitionAnimation(
         fade_out_animation=self.settings.fade_out_animation,
         fade_in_animation=self.game.fade_in_animation)
     self.onboarding_to_game_transition_animation = TransitionAnimation(
         fade_out_animation=self.onboarding.fade_out_animation,
         fade_in_animation=self.game.fade_in_animation)
     self.main_menu_to_settings_transition_animation = TransitionAnimation(
         fade_out_animation=self.main_menu.fade_out_animation,
         fade_in_animation=self.settings.fade_in_animation)
     self.settings_to_main_menu_transition_animation = TransitionAnimation(
         fade_out_animation=self.settings.fade_out_animation,
         fade_in_animation=self.main_menu.fade_in_animation)
     self.main_menu_to_bonus_code_activation_transition_animation = TransitionAnimation(
         fade_out_animation=self.main_menu.fade_out_animation,
         fade_in_animation=self.bonus_code_activation.fade_in_animation)
     self.bonus_code_activation_to_main_menu_transition_animation = TransitionAnimation(
         fade_out_animation=self.bonus_code_activation.fade_out_animation,
         fade_in_animation=self.main_menu.fade_in_animation)
     self.fade_in_animation.main_menu_fade_in_animation = self.main_menu.fade_in_animation
     self.fade_in_animation.license_fade_in_animation = self.license.fade_in_animation
     self.fade_in_animation.onboarding_fade_in_animation = self.onboarding.fade_in_animation
     self.fade_in_animation.game_fade_in_animation = self.game.fade_in_animation
     self.fade_in_animation.settings_fade_in_animation = self.settings.fade_in_animation
     self.fade_in_animation.bonus_code_activation_fade_in_animation = self.bonus_code_activation.fade_in_animation
     self.fade_out_animation.main_menu_fade_out_animation = self.main_menu.fade_out_animation
     self.fade_out_animation.license_fade_out_animation = self.license.fade_out_animation
     self.fade_out_animation.onboarding_fade_out_animation = self.onboarding.fade_out_animation
     self.fade_out_animation.game_fade_out_animation = self.game.fade_out_animation
     self.fade_out_animation.settings_fade_out_animation = self.settings.fade_out_animation
     self.fade_out_animation.bonus_code_activation_fade_out_animation = self.bonus_code_activation.fade_out_animation
     self.child_controllers = [
         self.main_menu, self.onboarding, self.license, self.game,
         self.settings, self.bonus_code_activation
     ]
from controller.game_controller import GameController
from exceptions import InvalidActionError, GameLostError
from gamefield.gamefield import GameField
from gamefield.tilecollection import TileCollection
import random
"""
This script simulates a player who randomly swipes the game until they lose.
Afterwards, the number of valid swipes and the reached score are displayed.
"""

tile_collection = TileCollection()
game_field = GameField(tile_collection)
game_controller = GameController(game_field, tile_collection)
game_controller.initialize()
random = random.Random()

moves = 0
actions = [
    game_controller.swipe_north_action, game_controller.swipe_east_action,
    game_controller.swipe_south_action, game_controller.swipe_west_action
]
while True:
    try:
        # do anything
        action = random.choice(actions)
        action()
        moves += 1
    except InvalidActionError as _:
        # if the action was invalid, ignore and keep going
        pass
    except GameLostError as e:
Beispiel #15
0
class AppController(AppBaseController):
    def __init__(self, loader):
        super().__init__(logger=getLogger('root.app.controller'))
        self.loader = loader
        self.view = AppView(controller=self)
        self.model = AppModel(controller=self, view=self.view)
        self.fade_in_animation = AppFadeInAnimation(self.view)
        self.fade_out_animation = AppFadeOutAnimation(self.view)
        self.main_menu = MainMenuController(self)
        self.onboarding = OnboardingController(self)
        self.license = LicenseController(self)
        self.game = GameController(self)
        self.settings = SettingsController(self)
        self.bonus_code_activation = BonusCodeActivationController(self)
        self.main_menu_to_game_transition_animation = TransitionAnimation(
            fade_out_animation=self.main_menu.fade_out_animation,
            fade_in_animation=self.game.fade_in_animation)
        self.main_menu_to_onboarding_transition_animation = TransitionAnimation(
            fade_out_animation=self.main_menu.fade_out_animation,
            fade_in_animation=self.onboarding.fade_in_animation)
        self.game_to_main_menu_transition_animation = TransitionAnimation(
            fade_out_animation=self.game.fade_out_animation,
            fade_in_animation=self.main_menu.fade_in_animation)
        self.main_menu_to_license_transition_animation = TransitionAnimation(
            fade_out_animation=self.main_menu.fade_out_animation,
            fade_in_animation=self.license.fade_in_animation)
        self.license_to_main_menu_transition_animation = TransitionAnimation(
            fade_out_animation=self.license.fade_out_animation,
            fade_in_animation=self.main_menu.fade_in_animation)
        self.game_to_settings_transition_animation = TransitionAnimation(
            fade_out_animation=self.game.fade_out_animation,
            fade_in_animation=self.settings.fade_in_animation)
        self.settings_to_game_transition_animation = TransitionAnimation(
            fade_out_animation=self.settings.fade_out_animation,
            fade_in_animation=self.game.fade_in_animation)
        self.onboarding_to_game_transition_animation = TransitionAnimation(
            fade_out_animation=self.onboarding.fade_out_animation,
            fade_in_animation=self.game.fade_in_animation)
        self.main_menu_to_settings_transition_animation = TransitionAnimation(
            fade_out_animation=self.main_menu.fade_out_animation,
            fade_in_animation=self.settings.fade_in_animation)
        self.settings_to_main_menu_transition_animation = TransitionAnimation(
            fade_out_animation=self.settings.fade_out_animation,
            fade_in_animation=self.main_menu.fade_in_animation)
        self.main_menu_to_bonus_code_activation_transition_animation = TransitionAnimation(
            fade_out_animation=self.main_menu.fade_out_animation,
            fade_in_animation=self.bonus_code_activation.fade_in_animation)
        self.bonus_code_activation_to_main_menu_transition_animation = TransitionAnimation(
            fade_out_animation=self.bonus_code_activation.fade_out_animation,
            fade_in_animation=self.main_menu.fade_in_animation)
        self.fade_in_animation.main_menu_fade_in_animation = self.main_menu.fade_in_animation
        self.fade_in_animation.license_fade_in_animation = self.license.fade_in_animation
        self.fade_in_animation.onboarding_fade_in_animation = self.onboarding.fade_in_animation
        self.fade_in_animation.game_fade_in_animation = self.game.fade_in_animation
        self.fade_in_animation.settings_fade_in_animation = self.settings.fade_in_animation
        self.fade_in_animation.bonus_code_activation_fade_in_animation = self.bonus_code_activation.fade_in_animation
        self.fade_out_animation.main_menu_fade_out_animation = self.main_menu.fade_out_animation
        self.fade_out_animation.license_fade_out_animation = self.license.fade_out_animation
        self.fade_out_animation.onboarding_fade_out_animation = self.onboarding.fade_out_animation
        self.fade_out_animation.game_fade_out_animation = self.game.fade_out_animation
        self.fade_out_animation.settings_fade_out_animation = self.settings.fade_out_animation
        self.fade_out_animation.bonus_code_activation_fade_out_animation = self.bonus_code_activation.fade_out_animation
        self.child_controllers = [
            self.main_menu, self.onboarding, self.license, self.game,
            self.settings, self.bonus_code_activation
        ]

    def on_update_current_locale(self, new_locale):
        super().on_update_current_locale(new_locale)
        self.model.on_save_and_commit_locale(new_locale)

    def on_save_state(self):
        super().on_save_state()
        on_commit()

    def on_update_clock_state(self, clock_24h_enabled):
        super().on_update_clock_state(clock_24h_enabled)
        self.model.on_save_and_commit_clock_state(clock_24h_enabled)

    def on_fullscreen_button_click(self):
        WINDOW.set_size(*self.model.fullscreen_resolution)
        if self.model.fullscreen_mode_available:
            self.on_fullscreen_mode_turned_on()

    def on_restore_button_click(self):
        self.on_fullscreen_mode_turned_off()
        WINDOW.set_size(*self.settings.model.windowed_resolution)

    def on_fullscreen_mode_turned_on(self):
        self.model.on_fullscreen_mode_turned_on()

    def on_fullscreen_mode_turned_off(self):
        self.model.on_fullscreen_mode_turned_off()

    def on_activate_main_menu_view(self):
        self.main_menu.on_activate_view()

    def on_activate_game_view(self):
        self.game.on_activate_view()

    def on_open_license(self):
        self.game_to_main_menu_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_deactivate()
        self.settings_to_main_menu_transition_animation.on_deactivate()
        self.bonus_code_activation_to_main_menu_transition_animation.on_deactivate(
        )
        self.main_menu_to_license_transition_animation.on_activate()

    def on_close_license(self):
        self.main_menu_to_license_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_activate()

    def on_open_onboarding(self):
        self.game_to_main_menu_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_deactivate()
        self.settings_to_main_menu_transition_animation.on_deactivate()
        self.bonus_code_activation_to_main_menu_transition_animation.on_deactivate(
        )
        self.main_menu_to_onboarding_transition_animation.on_activate()

    def on_close_onboarding(self):
        self.game.on_unlock_map(PASSENGER_MAP)
        self.main_menu_to_onboarding_transition_animation.on_deactivate()
        self.onboarding_to_game_transition_animation.on_activate()
        self.onboarding.on_save_and_commit_onboarding_state()
        self.game.on_resume_game()

    def on_back_to_the_station(self):
        self.game_to_main_menu_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_deactivate()
        self.settings_to_main_menu_transition_animation.on_deactivate()
        self.bonus_code_activation_to_main_menu_transition_animation.on_deactivate(
        )
        self.main_menu_to_game_transition_animation.on_activate()
        self.game.on_resume_game()

    def on_open_bonus_code(self):
        self.game_to_main_menu_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_deactivate()
        self.settings_to_main_menu_transition_animation.on_deactivate()
        self.bonus_code_activation_to_main_menu_transition_animation.on_deactivate(
        )
        self.main_menu_to_bonus_code_activation_transition_animation.on_activate(
        )

    def on_close_bonus_code(self):
        self.main_menu_to_bonus_code_activation_transition_animation.on_deactivate(
        )
        self.bonus_code_activation_to_main_menu_transition_animation.on_activate(
        )

    def on_open_settings_from_main_menu(self):
        self.game_to_main_menu_transition_animation.on_deactivate()
        self.license_to_main_menu_transition_animation.on_deactivate()
        self.settings_to_main_menu_transition_animation.on_deactivate()
        self.bonus_code_activation_to_main_menu_transition_animation.on_deactivate(
        )
        self.main_menu_to_settings_transition_animation.on_activate()
        self.settings.navigated_from_main_menu = True

    def on_open_settings_from_game(self):
        self.main_menu_to_game_transition_animation.on_deactivate()
        self.settings_to_game_transition_animation.on_deactivate()
        self.onboarding_to_game_transition_animation.on_deactivate()
        self.game_to_settings_transition_animation.on_activate()
        self.settings.navigated_from_game = True

    def on_close_settings(self):
        if self.settings.navigated_from_main_menu:
            self.settings.navigated_from_main_menu = False
            self.main_menu_to_settings_transition_animation.on_deactivate()
            self.settings_to_main_menu_transition_animation.on_activate()
        elif self.settings.navigated_from_game:
            self.settings.navigated_from_game = False
            self.game_to_settings_transition_animation.on_deactivate()
            self.settings_to_game_transition_animation.on_activate()

    def on_activate_new_bonus_code(self, sha512_hash):
        self.game.on_activate_new_bonus_code(sha512_hash)

    def on_accept_changes(self, windowed_resolution, display_fps,
                          fade_animations_enabled, clock_24h_enabled,
                          level_up_notification_enabled,
                          feature_unlocked_notification_enabled,
                          construction_completed_notification_enabled,
                          enough_money_notification_enabled,
                          bonus_expired_notification_enabled,
                          shop_storage_notification_enabled,
                          voice_not_found_notification_enabled, master_volume,
                          announcements_enabled):
        self.settings.on_accept_changes(
            windowed_resolution, display_fps, fade_animations_enabled,
            clock_24h_enabled, level_up_notification_enabled,
            feature_unlocked_notification_enabled,
            construction_completed_notification_enabled,
            enough_money_notification_enabled,
            bonus_expired_notification_enabled,
            shop_storage_notification_enabled,
            voice_not_found_notification_enabled, master_volume,
            announcements_enabled)
        self.on_update_fade_animation_state(fade_animations_enabled)
        self.on_update_clock_state(clock_24h_enabled)
        self.on_change_level_up_notification_state(
            level_up_notification_enabled)
        self.on_change_feature_unlocked_notification_state(
            feature_unlocked_notification_enabled)
        self.on_change_construction_completed_notification_state(
            construction_completed_notification_enabled)
        self.on_change_enough_money_notification_state(
            enough_money_notification_enabled)
        self.on_change_bonus_expired_notification_state(
            bonus_expired_notification_enabled)
        self.on_change_shop_storage_notification_state(
            shop_storage_notification_enabled)
        self.on_change_voice_not_found_notification_state(
            voice_not_found_notification_enabled)
        self.on_master_volume_update(master_volume)
        self.on_update_announcements_state(announcements_enabled)
        if not WINDOW.fullscreen:
            WINDOW.set_size(*windowed_resolution)

        if display_fps:
            self.view.fps_display.on_activate()
        else:
            self.view.fps_display.on_deactivate()

    def on_save_and_commit_bonus_code_abuse(self):
        self.model.on_save_and_commit_bonus_code_abuse()

    def on_master_volume_update(self, new_master_volume):
        self.game.on_master_volume_update(new_master_volume)

    def on_update_announcements_state(self, new_state):
        self.game.on_update_announcements_state(new_state)
Beispiel #16
0
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from view.gamelist_widget import GameListWidget
from controller.game_controller import GameController

app = QApplication(sys.argv)
game_controller = GameController()
widget = GameListWidget()
widget.show()
widget.game_controller.get_game_list_callback(
    data={
        'code': 200,
        'list': [{
            'host_name': 'a',
            'guest_name': 'b'
        }]
    })
sys.exit(app.exec_())
class ViewGUI(QWidget):
    # TODO Add AI handle
    def __init__(self):
        self.counter_debug = 0
        super().__init__()
        self.gc = GameController()
        self.initUI()
        self.activate_coor = []  # tuple x,y
        self.move_coor = []
        self.atk_coor = []
        self.INACTIVE_PAWN_CSS = "background-color: #9AAC41;"
        self.ACTIVE_PAWN_CSS = "background-color: #E1FE57"
        self.ACTIVATE_PAWN_CSS = "background-color: green; color: white; font-weight: 500;"
        self.TILE_MOVE_CSS = "background-color: #53F399;"
        self.TILE_ATK_CSS = "background-color: #FF3500;"
        self.PROMOTE_PAWN_CSS = "background-color: #2e00ff; color: white;"

    def button_two_players_clicked(self):
        sender = self.sender()
        returned_params = self.gc.play_with_two_players_start()
        returned_task_controller = returned_params['task']
        if returned_task_controller == "END_GAME":
            self.task = "END GAME"
        else:
            self.clear_all_button_board()
            self.reset_board_two_players(returned_params)
            self.parse_possible_action()

    def button_ai_white_vs_players_clicked(self):
        sender = self.sender()
        returned_params = self.gc.play_with_ai_white()
        returned_task_controller = returned_params['task']
        if returned_task_controller == "END_GAME":
            self.task = "END GAME"
        else:
            self.clear_all_button_board()
            self.reset_board_two_players(returned_params)
            self.parse_possible_action()

    def decide_status_board_css(self, y, x):
        return self.ACTIVE_PAWN_CSS if self.list_btn_board[y][
            x].active_status_pawn else self.INACTIVE_PAWN_CSS

    def parse_possible_action(self):

        self.counter_debug += 1
        self.activate_coor = []
        self.promote_coor = []
        self.move_coor = []
        self.atk_coor = []
        # pprint(self.possible_action)
        for key, value in self.possible_action.items():
            if value['action'] == 'activate':
                self.btn_activate.setEnabled(True)
                self.list_btn_board[value['pawn_y']][
                    value['pawn_x']].set_activate_key(key)
                self.btn_activate.clicked.connect(
                    lambda: self.enable_activate_possible_action_button())
                self.activate_coor.append((value['pawn_x'], value['pawn_y']))
            if value['action'] == 'move':
                self.move_coor.append({"pawn_x" : value['pawn_x'],\
                                        "pawn_y" : value['pawn_y'],\
                                        "end_x" : value['x_end'],\
                                        "end_y" : value['y_end'],
                                        "move_key" : key})
                pawn_x = value['pawn_x']
                pawn_y = value['pawn_y']
                end_x = value['x_end']
                end_y = value['y_end']
                move_key = key
                self.list_btn_board[pawn_y][pawn_x].setEnabled(True)
                self.list_btn_board[pawn_y][pawn_x].add_move_list(
                    end_y, end_x, key)
                self.list_btn_board[pawn_y][pawn_x].clicked.connect(
                    lambda: self.enable_move())
            if value['action'] == 'attack':
                pawn_x = value['pawn_x']
                pawn_y = value['pawn_y']
                end_x = value['x_end']
                end_y = value['y_end']
                move_key = key
                self.list_btn_board[pawn_y][pawn_x].setEnabled(True)
                self.atk_coor.append({"pawn_x" : pawn_x,\
                                        "pawn_y" : pawn_y,\
                                        "end_x" : end_x,\
                                        "end_y" : end_y,\
                                        "move_key" : key})
                self.list_btn_board[pawn_y][pawn_x].add_attack_list(
                    end_y, end_x, key)
                # print(self.list_btn_board[pawn_y][pawn_x].attack_list)
                self.list_btn_board[pawn_y][pawn_x].clicked.connect(
                    lambda: self.enable_attack())

            if value['action'] == 'promote':
                pawn_x = value['pawn_x']
                pawn_y = value['pawn_y']
                move_key = key
                choice = value['promoted_choice']
                self.list_btn_board[pawn_y][pawn_x].add_promote_list(
                    move_key, choice)
                self.promote_coor.append((pawn_x, pawn_y))
                self.btn_evolve.clicked.connect(
                    lambda: self.enable_promote_possible_action_button())
                self.btn_evolve.setEnabled(True)

            if value['action'] == 'skip':
                self.gc.receive_input_action_play("skip",
                                                  self.possible_action["skip"])
                returned_params = self.gc.get_whattodo_view()
                self.returned_params = returned_params
                returned_task_controller = returned_params['task']
                self.clear_all_button_board()
                self.reset_board_two_players(returned_params)
                self.btn_activate.setEnabled(False)
                self.btn_evolve.setEnabled(False)

                self.parse_possible_action()

    def enable_promote_possible_action_button(self):
        if len(self.promote_coor) > 0:
            self.btn_activate.setEnabled(False)
            self.disable_all_pawn_button()
            for coor in self.promote_coor:
                try:
                    self.list_btn_board[coor[1]][coor[0]].clicked.disconnect()
                except Exception:
                    pass
                self.list_btn_board[coor[1]][coor[0]].setEnabled(True)
                self.list_btn_board[coor[1]][coor[0]].setStyleSheet(
                    self.PROMOTE_PAWN_CSS)
                self.list_btn_board[coor[1]][coor[0]].clicked.connect(
                    self.button_promote_pawn)
            self.btn_evolve.setText("Cancel Evolve")
            try:
                self.btn_evolve.clicked.disconnect()
            except Exception:
                pass
            self.btn_evolve.clicked.connect(
                lambda: self.disable_promote_possible_action_button())

    def disable_promote_possible_action_button(self):
        for coor in self.promote_coor:
            self.list_btn_board[coor[1]][coor[0]].setEnabled(False)
            self.list_btn_board[coor[1]][coor[0]].setStyleSheet(
                self.decide_status_board_css(coor[1], coor[0]))
            try:
                self.list_btn_board[coor[1]][coor[0]].clicked.disconnect()
            except Exception:
                pass
        self.btn_evolve.setText("Evolve")
        self.parse_possible_action()

    def button_promote_pawn(self):
        # print(self.sender().promote_dict.keys())
        items = self.sender().promote_dict.keys()
        item, okPressed = QInputDialog.getItem(self, "Select Promote",
                                               "Promote To:", items, 0, False)
        if item and okPressed:
            choice = self.sender().promote_dict[item]
            self.gc.receive_input_action_play(choice,
                                              self.possible_action[choice])
            returned_params = self.gc.get_whattodo_view()
            self.returned_params = returned_params
            returned_task_controller = returned_params['task']
            self.clear_all_button_board()
            self.reset_board_two_players(returned_params)
            self.btn_activate.setEnabled(False)
            self.btn_evolve.setEnabled(False)

            self.parse_possible_action()

    def enable_attack(self):
        sender = self.sender()

        self.disable_all_pawn_button()
        sender.setEnabled(True)
        self.btn_activate.setEnabled(False)
        self.btn_evolve.setEnabled(False)

        for tuple_range in sender.attack_list:
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setEnabled(
                True)
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setStyleSheet(
                self.TILE_ATK_CSS)
            self.list_btn_board[tuple_range[1]][tuple_range[0]].set_attack_key(
                tuple_range[2])
            self.list_btn_board[tuple_range[1]][tuple_range[
                0]].clicked.connect(lambda: self.button_attack_pawn())
        sender.clicked.connect(lambda: self.disable_attack())

    def disable_attack(self):
        sender = self.sender()
        for tuple_range in sender.attack_list:
            try:
                self.list_btn_board[tuple_range[1]][
                    tuple_range[0]].disconnect()
            except Exception:
                pass
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setEnabled(
                False)
        try:
            sender.clicked.disconnect()
        except Exception:
            pass
        for tuple_range in sender.attack_list:
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setStyleSheet(
                "")
        sender.clear_attack_list()
        for tuple_range in sender.move_list:
            try:
                self.list_btn_board[tuple_range[1]][
                    tuple_range[0]].disconnect()
            except Exception:
                pass
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setEnabled(
                False)
        try:
            sender.clicked.disconnect()
        except Exception:
            pass
        for tuple_range in sender.move_list:
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setStyleSheet(
                "")
        sender.clear_move_list()
        self.parse_possible_action()

    def button_attack_pawn(self):
        sender = self.sender()
        self.gc.receive_input_action_play(
            sender.attack_key, self.possible_action[sender.attack_key])
        returned_params = self.gc.get_whattodo_view()
        self.returned_params = returned_params
        returned_task_controller = returned_params['task']
        self.clear_all_button_board()
        self.reset_board_two_players(returned_params)
        self.btn_activate.setEnabled(False)
        self.btn_evolve.setEnabled(False)
        self.parse_possible_action()

    def disable_all_pawn_button(self):
        for move in self.move_coor:
            self.list_btn_board[move['pawn_y']][move['pawn_x']].setEnabled(
                False)
        for move in self.atk_coor:
            self.list_btn_board[move['pawn_y']][move['pawn_x']].setEnabled(
                False)

    def enable_move(self):
        sender = self.sender()
        # try: sender.clicked.disconnect()
        # except Exception: pass
        self.disable_all_pawn_button()
        sender.setEnabled(True)
        self.btn_activate.setEnabled(False)
        self.btn_evolve.setEnabled(False)

        for tuple_range in sender.move_list:
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setEnabled(
                True)
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setStyleSheet(
                self.TILE_MOVE_CSS)
            self.list_btn_board[tuple_range[1]][tuple_range[0]].set_move_key(
                tuple_range[2])
            self.list_btn_board[tuple_range[1]][tuple_range[
                0]].clicked.connect(lambda: self.button_move_pawn())
        sender.clicked.connect(lambda: self.disable_attack())

    def button_move_pawn(self):
        sender = self.sender()
        self.gc.receive_input_action_play(
            sender.move_key, self.possible_action[sender.move_key])
        returned_params = self.gc.get_whattodo_view()
        print(type(returned_params))

        self.returned_params = returned_params
        returned_task_controller = returned_params['task']
        self.clear_all_button_board()
        self.reset_board_two_players(returned_params)
        self.btn_activate.setEnabled(False)
        self.btn_evolve.setEnabled(False)
        self.parse_possible_action()

    def disable_move(self):
        sender = self.sender()
        for tuple_range in sender.move_list:
            try:
                self.list_btn_board[tuple_range[1]][
                    tuple_range[0]].disconnect()
            except Exception:
                pass
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setEnabled(
                False)
        try:
            sender.clicked.disconnect()
        except Exception:
            pass
        for tuple_range in sender.move_list:
            self.list_btn_board[tuple_range[1]][tuple_range[0]].setStyleSheet(
                "")
        sender.clear_move_list()
        self.parse_possible_action()

    def enable_activate_possible_action_button(self):
        self.btn_evolve.setEnabled(False)

        if len(self.activate_coor) > 0:
            for coor in self.activate_coor:
                self.list_btn_board[coor[1]][coor[0]].setEnabled(True)
                self.list_btn_board[coor[1]][coor[0]].setStyleSheet(
                    self.ACTIVATE_PAWN_CSS)
                self.list_btn_board[coor[1]][coor[0]].clicked.connect(
                    self.button_activate_pawn)
            self.btn_activate.setText("Cancel Activate")
            self.disable_all_pawn_button()
            try:
                self.btn_activate.clicked.disconnect()
            except Exception:
                pass
            self.btn_activate.clicked.connect(
                lambda: self.disable_activate_possible_action_button())

    def disable_activate_possible_action_button(self):
        for coor in self.activate_coor:
            self.list_btn_board[coor[1]][coor[0]].setEnabled(False)
            self.list_btn_board[coor[1]][coor[0]].setStyleSheet(
                self.decide_status_board_css(coor[1], coor[0]))
            try:
                self.list_btn_board[coor[1]][coor[0]].clicked.disconnect()
            except Exception:
                pass
        self.btn_activate.setText("Activate")
        self.parse_possible_action()

    def button_activate_pawn(self):
        for coor in self.activate_coor:
            try:
                self.list_btn_board[coor[1]][coor[0]].clicked.disconnect()
            except Exception:
                pass
        key_action = self.sender().activate_key
        self.gc.receive_input_action_play(key_action,
                                          self.possible_action[key_action])
        returned_params = self.gc.get_whattodo_view()
        self.returned_params = returned_params
        returned_task_controller = returned_params['task']
        self.reset_board_two_players(returned_params)
        self.btn_activate.setEnabled(False)
        self.btn_evolve.setEnabled(False)
        self.parse_possible_action()

    def clear_all_button_board(self):
        self.btn_activate.setText("Activate")
        self.btn_evolve.setText("Evolve")
        for board_rows in self.list_btn_board:
            for board in board_rows:
                try:
                    board.clicked.disconnect()
                except Exception:
                    pass
                board.clear_move_list()
                board.clear_attack_list()
                board.clear_promote_list()
                board.setEnabled(False)
                board.move_key = None
                board.setText("")
                board.setStyleSheet("")

    def color_check_mana(self, mana, label):
        if mana == 10:
            label.setStyleSheet("background-color: #fe0081;")
        elif mana > 4:
            label.setStyleSheet("background-color: #07fe00;")
        elif mana > 2:
            label.setStyleSheet("background-color: #e0e728;")
        else:
            label.setStyleSheet("")

    def check_task(self, returned_params):
        pass

    def reset_board_two_players(self, returned_params):
        self.clear_all_button_board()
        # pprint(returned_params)

        # TODO put to check task function
        if returned_params['task'] == 'END_GAME':
            QMessageBox.about(self, "Title", "Game has ended")
            sys.exit()

        self.mana_0 = returned_params['state']['player_list'][0]['mana']
        self.mana_1 = returned_params['state']['player_list'][1]['mana']
        self.mn0.setText(str(self.mana_0))
        self.mn1.setText(str(self.mana_1))
        self.color_check_mana(self.mana_0, self.mn0)
        self.color_check_mana(self.mana_1, self.mn1)

        self.black_king = returned_params['state']['black_king']
        if not self.black_king['dead']:
            self._pawn_write_to_board(self.black_king)
        self.white_king = returned_params['state']['white_king']
        if not self.white_king['dead']:
            self._pawn_write_to_board(self.white_king)

        self.black_pawn_list = returned_params['state']['black_pawn_list']
        for black_pawn in self.black_pawn_list:
            if not black_pawn['dead']:
                self._pawn_write_to_board(black_pawn)

        self.white_pawn_list = returned_params['state']['white_pawn_list']
        for white_pawn in self.white_pawn_list:
            if not white_pawn['dead']:
                self._pawn_write_to_board(white_pawn)

        self.player_list = returned_params['state']['player_list']
        self.rune_list = returned_params['state']['rune_list']
        for rune in self.rune_list:
            self._rune_write_to_board(rune)
        self.possible_action = returned_params['possible_action']
        self.possible_action_keys = returned_params['possible_action'].keys()

    def _rune_write_to_board(self, rune):
        self.list_btn_board[rune['y']][rune['x']].set_text_with_params(
            rune, "rune")

    def _pawn_write_to_board(self, pawn):
        self.list_btn_board[pawn['y']][pawn['x']].set_text_with_params(
            pawn, "pawn")
        self.list_btn_board[pawn['y']][pawn['x']].set_active_status_pawn(
            pawn['status'])
        self.list_btn_board[pawn['y']][pawn['x']].setStyleSheet(
            self.decide_status_board_css(pawn['y'], pawn['x']))

    def initUI(self):
        main_layout = QHBoxLayout()
        board_layout = self.ui_board()
        mana_info = self.ui_info_mana()
        special_ui_button = self.ui_button_special()
        info_game = self.ui_info_static()
        info_layout = QVBoxLayout()
        info_layout.addLayout(mana_info)
        info_layout.addLayout(special_ui_button)
        info_layout.addLayout(info_game)

        self.button_two_players = QPushButton("Play Two Players")
        self.button_two_players.clicked.connect(
            self.button_two_players_clicked)
        self.button_ai_white_player = QPushButton("AI White vs Human")
        self.button_ai_white_player.clicked.connect(
            self.button_ai_white_vs_players_clicked)

        main_layout.addWidget(self.button_two_players)
        main_layout.addWidget(self.button_ai_white_player)

        main_layout.addLayout(board_layout)
        main_layout.addLayout(info_layout)

        self.setLayout(main_layout)
        self.move(50, 50)
        self.show()

    def ui_info_mana(self):
        lbl1 = QLabel('Player White', self)
        lbl2 = QLabel('Player Black', self)
        self.mn0 = QLabel('5', self)
        self.mn1 = QLabel('5', self)
        self.label_task = QLabel("STATUS", self)
        self.task = QLabel('WAIT', self)
        grid = QGridLayout()
        grid.addWidget(lbl1, 0, 0)
        grid.addWidget(lbl2, 0, 1)
        grid.addWidget(self.mn0, 1, 0)
        grid.addWidget(self.mn1, 1, 1)
        grid.addWidget(self.label_task, 2, 0)
        grid.addWidget(self.task, 2, 1)
        return grid

    def ui_button_special(self):
        hbox = QVBoxLayout()
        self.btn_evolve = QPushButton("Evolve")
        self.btn_evolve.setEnabled(False)
        self.btn_activate = QPushButton("Activate")
        self.btn_activate.setEnabled(False)

        hbox.addWidget(self.btn_evolve)
        hbox.addWidget(self.btn_activate)
        return hbox

    def ui_info_static(self):
        grid = QVBoxLayout()
        lbl1 = QLabel('3 = Activate', self)
        lbl2 = QLabel('5 = Promote 2nd tier', self)
        lbl3 = QLabel('10 = Promote to Queen', self)
        grid.addWidget(QLabel("Information"))
        grid.addWidget(lbl1)
        grid.addWidget(lbl2)
        grid.addWidget(lbl3)
        return grid

    def ui_board(self, size=9):
        grid = QGridLayout()
        grid.setHorizontalSpacing(0)
        grid.setVerticalSpacing(0)

        i, j = 0, 0
        self.list_btn_board = [[None for i in range(9)] for j in range(9)]
        for k in range(size):
            for l in range(size):
                btn_board = BoardButton()
                btn_board.setEnabled(False)
                btn_board.setFixedSize(100, 90)
                self.list_btn_board[k][l] = btn_board
                grid.addWidget(btn_board, k, l)
        return grid
Beispiel #18
0
from controller.game_controller import GameController

if __name__ == '__main__':
    game = GameController()
    game.run_game()
Beispiel #19
0
 def setUp(self):
     self.fileName = "test_sentences.txt"
     self.controller = GameController(self.fileName)
Beispiel #20
0
class ChessScreen(Screen, IView):
    ROUTENAME = "/chess"
    FIGURE_TO_TEXT = ["knight", "bishop", "rock", "queen"]

    def buttonBackClick(self):
        # Erstellt Fenster, um sicherzugehen ob Spieler wirklich Runde beenden will
        self._pause()
        response = messagebox.askquestion(
            "Runde verlassen ",
            "Möchtest du die Runde wirklich verlassen?",
            icon='warning')
        if response == "yes":
            self.goBack()
        else:
            self._resume()

    def _pause(self):
        # Stoppt die Zeit, Spielfluß
        self.statusBar.setTime(self.gameController.getTime())
        self._isPaused = True
        self.statusBar.setPauseButton(False)
        self.gameController.pause()

    def _resume(self):
        # Restartet die Zeit und Spielfluß
        self._isPaused = False
        self.statusBar.setPauseButton(True)
        self.gameController.resume()

    def buttonClick(self):
        if self._isPaused == False:
            self._pause()
        else:
            self._resume()

    def goBack(self):
        self._screenManager.navigate("/")

    def initBuild(self, time):
        board = ChessBoardModel("black", "white")
        self._isPaused = False
        gameManager = GameManager(board, time)
        self.gameController = GameController(self, gameManager)
        self.selectMenu = None

        self.screenFrame = Frame()
        self.screenFrame.place(relx=0, rely=0, width=1000, height=800)

        self.statusBar = StatusBar(self.screenFrame, self.buttonClick,
                                   self.buttonBackClick)
        self.statusBar.place(relx=0, rely=0, width=200, height=800)
        self.chessBoard = ChessBoard(self.screenFrame, self.gameController,
                                     self._screenManager.imageHandler)
        self.chessBoard.place(x=200, y=12, width=800, height=800)

        threading.Timer(1, lambda: [self.update(onlyClock=True)]).start()

        self.update()

    def clear(self):
        self.chessBoard.destroy()
        self.statusBar.destroy()
        self.screenFrame.destroy()
        del self.gameController
        self.gameController = None

    def timerFunc(self):
        if self.gameController != None:
            self.update(onlyClock=True)

    def update(self, onlyClock=False):
        # If timer is still running after game is finished
        if self.gameController == None:
            return

        if self.gameController.getIsPromoting():
            if self.selectMenu == None:
                #Erstellt Auswahlfenster für Promoting
                self.selectMenu = SelectFigureFrame(
                    self.screenFrame, self,
                    self.gameController.getCurrentPlayer())
                self.selectMenu.place(x=0, y=0, width=1000, height=800)
                return
            else:
                # Führt Promotion aus, löscht Promoting Fenster
                if self.selectMenu.selectedFigure != -1:
                    self.gameController.promote(
                        self.FIGURE_TO_TEXT[self.selectMenu.selectedFigure])
                    threading.Timer(1, self.timerFunc).start()
                    self.selectMenu.destroy()
                    del self.selectMenu
                    self.selectMenu = None
                else:
                    return

        self.statusBar.setTime(
            self.gameController.getTime())  #Zeitzähler wird aktuellisiert
        gameOver = self.gameController.getGameOver()

        if gameOver != False:
            self._screenManager.navigate("/end", gameOver)
            return

        if onlyClock:
            #Startet process, der die Zeitzähler alle 1s aktuellisiert, neu
            threading.Timer(1, lambda: [self.update(onlyClock=True)]).start()
            return

        self.chessBoard.updateBoard(self.gameController.getBoardState(),
                                    self.gameController.getCurrentPlayer())
        self.statusBar.setGameRound(self.gameController.getRoundNumber())
        currentPlayer = self.gameController.getCurrentPlayer()
        if (currentPlayer == "black"):
            self.statusBar.setCurrentPlayer("S", "#000", "#FFF")
        elif (currentPlayer == "white"):
            self.statusBar.setCurrentPlayer("W", "#FFF", "#000")
Beispiel #21
0
 def setUp(self):
     self.tile_collection = TileCollection()
     self.game_field = GameField(self.tile_collection)
     self.game_controller = GameController(self.game_field, self.tile_collection)
     self.game_controller._random.seed(1337)
class GameViewCLI():
    """
    A class used to show the view in CLI
    """
    def __init__(self):
        self.gc = GameController()
        self.board_size = 9
        self.board = [[None for i in range(self.board_size)]
                      for j in range(self.board_size)]

    def start_game_2_players(self):
        """
        Start the game in 2 players mode (no AI)
        To play use these command:
        "exit" : exit the game
        action_key : input the action key stated in the command line.
        """
        state = self.gc.state
        while (not AIElements.is_over(state)):
            pprint(AIElements.get_state_dict(state))
            collected_action = AIElements.get_possible_action(state)
            print("List of Action : ")
            pprint(collected_action)
            self.gc.debug_print_board(state)
            print("Mana (White, Black) = " +
                  str(AIElements.get_players_mana(state)))
            print("Rune List:")
            print(AIElements.get_rune_information(state))
            inp = input("command : ")
            if inp in collected_action.keys():
                state = AIElements.result_function(state,
                                                   collected_action[inp])
            if inp == 'exit':
                break

    def start_game_2_experimental_(self):
        """
        Start the game in 2 players mode (no AI)
        To play use these command:
        "exit" : exit the game
        action_key : input the action key stated in the command line.
        """
        returned_params = self.gc.play_with_two_players_start()
        returned_task_controller = returned_params['task']

        while (not returned_task_controller == "END_GAME"):
            print(returned_task_controller)
            self.parse_returned_params_change_player(returned_params)
            pprint(pd.DataFrame(self.board))
            pprint(self.possible_action)
            pprint(self.rune_list)
            pprint(self.player_list)
            inp = input("command : ")
            if inp in self.possible_action_keys:
                self.gc.receive_input_action_play(inp,
                                                  self.possible_action[inp])
                returned_params = self.gc.get_whattodo_view()
                returned_task_controller = returned_params['task']
            elif inp == 'exit':
                break
            else:
                print("Wrong Input")

    def start_game_ai_experimental_(self):
        """
        Start the game in 2 players mode (no AI)
        To play use these command:
        "exit" : exit the game
        action_key : input the action key stated in the command line.
        """
        # returned_params = self.gc.play_with_two_players_start()
        returned_params = self.gc.play_with_ai_white()

        returned_task_controller = returned_params['task']

        while (not returned_task_controller == "END_GAME"):
            print(returned_task_controller)
            if returned_task_controller == 'CHANGE_PLAYER':
                self.parse_returned_params_change_player(returned_params)
                pd.options.display.max_columns = 10
                display(pd.DataFrame(self.board))
                pprint(self.possible_action)
                pprint(self.rune_list)
                pprint(self.player_list)
            elif returned_task_controller == 'AI_MOVE':
                self.parse_returned_params_ai_move(returned_params)
                if 'end' in returned_params:
                    break

                print("AI MOVE")
                pprint(returned_params['ai_action'])
                pprint(pd.DataFrame(self.board))
                print("----")
                self.parse_returned_params_change_player(returned_params)
                pprint(pd.DataFrame(self.board))
                pprint(self.possible_action)
                pprint(self.rune_list)
                pprint(self.player_list)
            inp = input("command : ")
            if inp in self.possible_action_keys:
                self.gc.receive_input_action_play(inp,
                                                  self.possible_action[inp])
                returned_params = self.gc.get_whattodo_view()
                returned_task_controller = returned_params['task']

            elif inp == 'exit':
                break
            else:
                print("Wrong Input")

    def parse_returned_params_ai_move(self, returned_params):
        self.board = [[None for i in range(self.board_size)]
                      for j in range(self.board_size)]

        # Prev state
        self.black_king = returned_params['prev_state']['black_king']
        self._pawn_write_to_board(self.black_king)
        self.white_king = returned_params['prev_state']['white_king']
        self._pawn_write_to_board(self.white_king)

        self.black_pawn_list = returned_params['prev_state']['black_pawn_list']
        for black_pawn in self.black_pawn_list:
            self._pawn_write_to_board(black_pawn)

        self.white_pawn_list = returned_params['prev_state']['white_pawn_list']
        for white_pawn in self.white_pawn_list:
            self._pawn_write_to_board(white_pawn)

        self.player_list = returned_params['prev_state']['player_list']
        self.rune_list = returned_params['prev_state']['rune_list']
        for rune in self.rune_list:
            self._rune_write_to_board(rune)

    def parse_returned_params_change_player(self, returned_params):
        self.board = [[None for i in range(self.board_size)]
                      for j in range(self.board_size)]
        self.black_king = returned_params['state']['black_king']
        self._pawn_write_to_board(self.black_king)
        self.white_king = returned_params['state']['white_king']
        self._pawn_write_to_board(self.white_king)

        self.black_pawn_list = returned_params['state']['black_pawn_list']
        for black_pawn in self.black_pawn_list:
            self._pawn_write_to_board(black_pawn)

        self.white_pawn_list = returned_params['state']['white_pawn_list']
        for white_pawn in self.white_pawn_list:
            self._pawn_write_to_board(white_pawn)

        self.player_list = returned_params['state']['player_list']
        self.rune_list = returned_params['state']['rune_list']
        for rune in self.rune_list:
            self._rune_write_to_board(rune)
        self.possible_action = returned_params['possible_action']
        self.possible_action_keys = returned_params['possible_action'].keys()

    def _rune_write_to_board(self, rune):
        self.board[rune['y']][rune['x']] = 'Runeeeeee'

    def _pawn_write_to_board(self, pawn):
        self.board[pawn['y']][pawn['x']] = pawn['pawn_type'][0:2] + 'i' \
                                                        + str(pawn['pawn_index']) \
                                                        + 'a' \
                                                        + str(pawn['atk']) \
                                                        + 'h' \
                                                        + str(pawn['hp']) \
                                                        + 'p' \
                                                        + str(pawn['step']) \
                                                        + 't' \
                                                        + str(pawn['status'])[0:2]

    def one_action(self, list_action):
        """
        Concatenate all list of actions to become one list

        ...

        Attributes
        ----------
        list_action : list
            a list of actions of Kings, Players, and Pawns

        Returns
        -------
        list
            a concatenated all list of actions.
        """
        action_list_completed = {}
        for act in list_action:
            if 'action' in act and len(act['action']) > 0:
                for key, value in act['action'].items():
                    action_list_completed[key] = value
        return action_list_completed
 def __init__(self):
     self.gc = GameController()
     self.board_size = 9
     self.board = [[None for i in range(self.board_size)]
                   for j in range(self.board_size)]
Beispiel #24
0
class App(object):
    """
    The App administrates the game. It instantiates a GameField and a GameCon-
    troller and makes them interact with the user.
    """
    def __init__(
            self,
            input_stream: ConsoleInput,
            output_stream: ConsoleOutput
    ):
        self.input = input_stream
        self.output = output_stream
        self.tile_collection = TileCollection()
        self.game_field = GameField.basic_field(self.tile_collection)
        self.game_controller = GameController(
            self.game_field,
            self.tile_collection
        )
        self.game_controller.initialize()
        self.renderer = ConsoleRenderer(output_stream)  # type: Renderer
        self.prompt_counter = 0

    @staticmethod
    def input_invalid(user_input: str) -> bool:
        """
        Checks if a given user input is valid. Allowed inputs are one charachter
        directions or 'q' to end the application.
        :param user_input:
        """
        return user_input not in ['n', 'e', 's', 'w', 'q']

    def run(self, max_prompts: int = -1):
        """
        Runs the mainloop for a maximum of max_prompts times.
        :param max_prompts:
        """
        run_indefinitely = max_prompts == -1
        run_limit_not_reached_yet = max_prompts > self.prompt_counter

        # render once before everything starts, so the initial field can be seen
        self.renderer.render(self.game_field, self.game_controller.score)

        while run_indefinitely or run_limit_not_reached_yet:
            user_input = self.input.getline(
                'Wohin swipen? n/e/s/w | q for exit\n'
            )
            if self.input_invalid(user_input):
                self.output.write('Ungültiger Input, bitte wiederholen.')
                continue
            else:
                try:
                    if user_input == 'n':
                        self.output.write("swiping north")
                        self.game_controller.swipe_north_action()
                    elif user_input == 'e':
                        self.output.write("swiping east")
                        self.game_controller.swipe_east_action()
                    elif user_input == 's':
                        self.output.write("swiping south")
                        self.game_controller.swipe_south_action()
                    elif user_input == 'w':
                        self.output.write("swiping west")
                        self.game_controller.swipe_west_action()
                    else:
                        exit()
                except (GameLostError, InvalidActionError) as e:
                    if isinstance(e, GameLostError):
                        print("sorry, you lost the game!")
                        exit()
                    else:
                        print("that move was invalid. try again!")
            # render again after input and calculation
            self.renderer.render(self.game_field, self.game_controller.score)

            self.prompt_counter += 1
            run_limit_not_reached_yet = max_prompts > self.prompt_counter
Beispiel #25
0
class GameControllerTestCase(unittest.TestCase):
    def setUp(self):
        self.tile_collection = TileCollection()
        self.game_field = GameField(self.tile_collection)
        self.game_controller = GameController(self.game_field, self.tile_collection)
        self.game_controller._random.seed(1337)

    def test_initialize(self):
        """
        Tests that initialization places two random Tiles on the GameField.
        """
        self.game_controller.initialize()
        # The spaces which the random tiles occupy are based on the random gene-
        # rator seed and thus are always equal in tests.
        self.assertEqual(
            self.game_field.field_data[2][1].tile,
            self.tile_collection.get_tile('value', value=2)
        )
        self.assertEqual(
            self.game_field.field_data[2][3].tile,
            self.tile_collection.get_tile('value', value=4)
        )

    def test_swipeNorth(self):
        """
        Test that issueing a swipeNorthAction uses the north-ward iterator.
        """
        self.game_field = create_autospec(GameField)
        self.game_field.field_data = {}
        self.game_controller = GameController(self.game_field, self.tile_collection)
        self.game_controller._random.seed(1337)
        self.game_controller._swipe = MagicMock()
        self.game_controller.swipe_north_action()
        self.game_field.get_north_iterator.assert_any_call()
        self.game_controller._swipe.assert_called_with(self.game_field.get_north_iterator())

    def test_swipeEast(self):
        """
        Test that issueing a swipeNorthAction uses the east-ward iterator.
        """
        self.game_field = create_autospec(GameField)
        self.game_field.field_data = {}
        self.game_controller = GameController(self.game_field, self.tile_collection)
        self.game_controller._random.seed(1337)
        self.game_controller._swipe = MagicMock()
        self.game_controller.swipe_east_action()
        self.game_field.get_east_iterator.assert_any_call()
        self.game_controller._swipe.assert_called_with(self.game_field.get_east_iterator())

    def test_swipeSouth(self):
        """
        Test that issueing a swipeNorthAction uses the south-ward iterator.
        """
        self.game_field = create_autospec(GameField)
        self.game_field.field_data = {}
        self.game_controller = GameController(self.game_field, self.tile_collection)
        self.game_controller._random.seed(1337)
        self.game_controller._swipe = MagicMock()
        self.game_controller.swipe_south_action()
        self.game_field.get_south_iterator.assert_any_call()
        self.game_controller._swipe.assert_called_with(self.game_field.get_south_iterator())

    def test_swipeWest(self):
        """
        Test that issueing a swipeNorthAction uses the west-ward iterator.
        """
        self.game_field = create_autospec(GameField)
        self.game_field.field_data = {}
        self.game_controller = GameController(self.game_field, self.tile_collection)
        self.game_controller._random.seed(1337)
        self.game_controller._swipe = MagicMock()
        self.game_controller.swipe_west_action()
        self.game_field.get_west_iterator.assert_any_call()
        self.game_controller._swipe.assert_called_with(self.game_field.get_west_iterator())

    def test_swipe(self):
        """
        Functional test that a swipe action correctly traverses the created
        iterator.
        The field is layed out like this:
         2  x  x  4
         2  4  8  4
         4  4  2  4
        32 16  2  4
        The result should be this: (northward swipe)
         4  8  8  8
         4 16  4  8
        32  x  x  x
         x  x  x  x
        """
        # set up field:
        self.game_field.field_data[0][0].tile = self.tile_collection.get_tile('value', value=2)
        self.game_field.field_data[3][0].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[0][1].tile = self.tile_collection.get_tile('value', value=2)
        self.game_field.field_data[1][1].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[2][1].tile = self.tile_collection.get_tile('value', value=8)
        self.game_field.field_data[3][1].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[0][2].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[1][2].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[2][2].tile = self.tile_collection.get_tile('value', value=2)
        self.game_field.field_data[3][2].tile = self.tile_collection.get_tile('value', value=4)
        self.game_field.field_data[0][3].tile = self.tile_collection.get_tile('value', value=32)
        self.game_field.field_data[1][3].tile = self.tile_collection.get_tile('value', value=16)
        self.game_field.field_data[2][3].tile = self.tile_collection.get_tile('value', value=2)
        self.game_field.field_data[3][3].tile = self.tile_collection.get_tile('value', value=4)

        self.game_controller.swipe_north_action()

        self.assertEqual(
            self.tile_collection.get_tile('value', value=4),
            self.game_field.field_data[0][0]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=8),
            self.game_field.field_data[1][0]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=8),
            self.game_field.field_data[2][0]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=8),
            self.game_field.field_data[3][0]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=4),
            self.game_field.field_data[0][1]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=16),
            self.game_field.field_data[1][1]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=4),
            self.game_field.field_data[2][1]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=8),
            self.game_field.field_data[3][1]._tile
        )
        self.assertEqual(
            self.tile_collection.get_tile('value', value=32),
            self.game_field.field_data[0][2]._tile
        )
        # One Tile is randomly inserted after swiping
        self.assertEqual(
            self.tile_collection.get_tile('value', value=4),
            self.game_field.field_data[2][3].tile
        )

    def test_scorekeeping(self) -> None:
        """
        Tests, that swipes return the resulting score and score is accessible.
        The Score numbers are based on the random seed and thus are equal every
        time the Test is run.
        """
        with self.assertRaises(GameNotInitializedError):
            score = self.game_controller.score
        self.game_controller.initialize()

        self.assertEqual(
            0,
            self.game_controller.swipe_east_action()
        )
        self.assertEqual(
            4,
            self.game_controller.swipe_south_action()
        )
        self.assertEqual(
            12,
            self.game_controller.swipe_south_action()
        )
        self.assertEqual(
            16,
            self.game_controller.swipe_south_action()
        )
        self.assertEqual(
            16,
            self.game_controller.swipe_south_action()
        )
        self.assertEqual(
            20,
            self.game_controller.swipe_south_action()
        )
        self.assertEqual(20, self.game_controller.score)

    def test_initialization_enables_score(self):
        """
        Tests, that calling GameController.initialize() allows to acces GameCon-
        troller.score afterwards. Before, it raises a GameNotInitializedError.
        """
        self.game_field = GameField.basic_field(self.tile_collection)
        self.game_controller = GameController(
            self.game_field,
            self.tile_collection
        )

        with self.assertRaises(GameNotInitializedError):
            score = self.game_controller.score
        self.game_controller.initialize()
        self.assertEqual(0, self.game_controller.score)

    def test_invalid_action_error(self):
        """
        Tests that an InvalidActionError is raised when an action is issued that
        can't be executed.

        This test is very rough but should work.
        """
        self.game_controller.initialize()

        with self.assertRaises(InvalidActionError):
            for i in range(100):
                self.game_controller.swipe_east_action()

    def test_game_lost_error(self):
        """
        Tests that a GameLostError is raised when an action is issued but no
        action can be executed anymore.

        This test is very rough but should work.
        """
        self.game_controller.initialize()

        # fill the GameField in a checkers mannern with value twos/fours, so
        # that they can't be fused with each other.
        for x in range(4):
            for y in range(4):
                if x % 2 == y % 2:
                    self.game_field.field_data[x][y].tile = \
                        self.tile_collection.get_tile('value', value=2)
                else:
                    self.game_field.field_data[x][y].tile = \
                        self.tile_collection.get_tile('value', value=4)

        with self.assertRaises(GameLostError):
            self.game_controller.swipe_north_action()
Beispiel #26
0
class UserController(BaseController):
    def __init__(self):
        BaseController.__init__(self, SERVICE_NAME)
        self.current_username = None
        self.current_user_id = None
        self.current_user_point = -1

        self.c.register(LOGIN_ID, self.login_callback)

        self.game_controller = GameController()

    def is_logging(self):
        return self.is_connecting

    def is_login(self):
        return self.is_connected

    def login(self, username):
        # print(username)
        client = self.get_client()
        req = {'username': username}
        client.send(SERVICE_NAME, LOGIN_ID, req)

    def login_callback(self, data):
        '''
        {
        uid: "",
        code: "",
        }
        :param data:
        :return:
        '''

        logging.debug('Login Callback %s', data)
        try:
            self.current_username = data.get('username')
            self.current_user_id = data.get('uid')
            self.current_user_point = data.get('point')
            self.emit(SIGNAL("login_callback(int,QString)"), data['code'],
                      QString(self.current_username))
            self.is_connected = True

            self.add_polling_rank_task()
            self.game_controller.add_polling_game_list_task()
        except KeyError:
            logging.debug('Login Callback data is None %s', data)

    def add_polling_rank_task(self):
        c = self.get_client()
        c.set_periodic_task(self.get_user_rank, (),
                            self.get_user_rank_callback, GET_RANK_ID)

    def get_user_rank(self):
        client = self.get_client()
        req = {'uid': self.current_user_id}
        client.send(SERVICE_NAME, GET_RANK_ID, req)

    def get_user_rank_callback(self, data):
        if data and data.get('code') == 200:
            try:
                user_list = data['list']
            except KeyError:
                logging.debug("get_rank: %s ", data)
            else:
                self.connector.emit(SIGNAL('clear'))
                for user in user_list:
                    username = user.get('username')
                    point = user.get('point')
                    self.connector.emit(SIGNAL('add_rank_item(QString, int)'),
                                        username, point)
        else:
            logging.debug("get_user_rank_callback: %s", data)
Beispiel #27
0
from controller.game_controller import GameController
from gamefield.gamefield import GameField
from gamefield.tilecollection import TileCollection
from exceptions import GameLostError, InvalidActionError, \
    GameNotInitializedError

tile_collection = TileCollection()
game_field = GameField.basic_field(tile_collection)
game_controller = GameController(game_field, tile_collection)

# If the game was not initialized yet, the score is not accessible
try:
    game_controller.score
except GameNotInitializedError as e:
    print(e)

game_controller.initialize()

# score is returned after each action and each action can raise an
# InvalidActionError if the called action can't be executed:
try:
    score = game_controller.swipe_north_action()
    score = game_controller.swipe_east_action()
    score = game_controller.swipe_south_action()
    score = game_controller.swipe_west_action()
except InvalidActionError as e:
    print(e)
# score can be accessed at any time:
score = game_controller.score

# when there is no move left, a GameLostError is raised:
from controller.game_controller import GameController
from exceptions import InvalidActionError, GameLostError
from gamefield.gamefield import GameField
from gamefield.tilecollection import TileCollection
import random

"""
This script simulates a player who randomly swipes the game until they lose.
Afterwards, the number of valid swipes and the reached score are displayed.
"""

tile_collection = TileCollection()
game_field = GameField(tile_collection)
game_controller = GameController(game_field, tile_collection)
game_controller.initialize()
random = random.Random()

moves = 0
actions = [
    game_controller.swipe_north_action,
    game_controller.swipe_east_action,
    game_controller.swipe_south_action,
    game_controller.swipe_west_action
]
while True:
    try:
        # do anything
        action = random.choice(actions)
        action()
        moves += 1
    except InvalidActionError as _: