예제 #1
0
class BoardViewTests(TestCase):
    EMPTY_BOARD = [[EMPTY_INNER_BOARD, EMPTY_INNER_BOARD, EMPTY_INNER_BOARD],
                   [EMPTY_INNER_BOARD, EMPTY_INNER_BOARD, EMPTY_INNER_BOARD],
                   [EMPTY_INNER_BOARD, EMPTY_INNER_BOARD, EMPTY_INNER_BOARD]]

    def setUp(self):
        self.boardView = BoardView()
        self.testBoard = self.EMPTY_BOARD

    def test_init_should_add_empty_board_to_board_view(self):
        self.assertEqual(BoardView.EMPTY_BOARD, self.boardView.boardViewString)

    def test_UpdateBoard_should_add_a_character_to_boardViewString(self):
        self.testBoard[1][1] = self.testBoard[1][1].replace('1', 'X')

        self.boardView.UpdateBoard(1, 1, 0, 0, 'X')

        self.assertEqual(self.testBoard, self.boardView.boardViewString)

    def test_PrintBoard_should_print_an_empty_board(self):
        self.assertEqual(EMPTY_BOARD_TO_PRINT,
                         self.boardView.GetFormattedBoard())

    def test_PrintBoard_should_print_the_board_with_one_character(self):
        self.boardView.UpdateBoard(1, 1, 0, 0, 'X')

        self.assertEqual(BOARD_WITH_ONE_CHAR,
                         self.boardView.GetFormattedBoard())
예제 #2
0
    def __init__(self, sizex, sizey):

        self.sizex = sizex
        self.sizey = sizey
        self.view = BoardView(sizex,sizey,600,480)
        self.model = BoardModel(sizex,sizey)

        self.keyPressed = False
예제 #3
0
    def __init__(self, gamemodel, actionMenuItems):
        gtk.EventBox.__init__(self)
        self.promotionDialog = PromotionDialog()
        self.view = BoardView(gamemodel)
        self.add(self.view)

        self.actionMenuItems = actionMenuItems
        self.connections = {}
        for key, menuitem in self.actionMenuItems.iteritems():
            if menuitem == None: print key
            self.connections[menuitem] = menuitem.connect(
                "activate", self.actionActivate, key)

        self.view.connect("shown_changed", self.shown_changed)
        gamemodel.connect("moves_undoing", self.moves_undone)
        self.connect("button_press_event", self.button_press)
        self.connect("button_release_event", self.button_release)
        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK
                        | gtk.gdk.POINTER_MOTION_MASK)
        self.connect("motion_notify_event", self.motion_notify)
        self.connect("leave_notify_event", self.leave_notify)

        self.selected_last = None
        self.stateLock = threading.Lock()
        self.normalState = NormalState(self)
        self.selectedState = SelectedState(self)
        self.activeState = ActiveState(self)
        self.lockedState = LockedState(self)
        self.lockedSelectedState = LockedSelectedState(self)
        self.lockedActiveState = LockedActiveState(self)
        self.currentState = self.lockedState

        self.lockedPly = self.view.shown
        self.possibleBoards = {
            self.lockedPly: self._genPossibleBoards(self.lockedPly)
        }

        self.allowPremove = False

        def onGameStart(gamemodel):
            for player in gamemodel.players:
                if player.__type__ == LOCAL:
                    self.allowPremove = True

        gamemodel.connect("game_started", onGameStart)
예제 #4
0
 def __init__(self):
     #GameBoard, display and notification objects
     self.board = Board()
     self.boardView = BoardView()
     self.notifications = Notifications()
     #Player objects
     self.human = Human()
     self.computer = Computer()
     #Toss Variables
     self.humanDieToss = 0
     self.computerDieToss = 0
     #Control variables
     self.humanTurn = False
     self.computerTurn = False
     #Variables to store user input of coordinates
     self.startRow = 0
     self.startCol = 0
     self.endRow = 0
     self.endCol = 0
     #1 for vertical first, 2 for lateral first
     self.path = 0
예제 #5
0
 def __init__(self):
     GObject.GObject.__init__(self)
     self.view = BoardView()
     self.add(self.view)
     self.view.showEnpassant = True
     
     self.connect("button_press_event", self.button_press)
     self.connect("button_release_event", self.button_release)
     self.add_events(Gdk.EventMask.LEAVE_NOTIFY_MASK|Gdk.EventMask.POINTER_MOTION_MASK)
     self.connect("motion_notify_event", self.motion_notify)
     self.connect("leave_notify_event", self.leave_notify)
     
     self.brush = None
예제 #6
0
    def __init__(self, app):
        self.restart_pressed = False
        self.already_won = False
        self.total_cur_words_n = 0
        self.app = app
        self.game_model = GameModel()

        self.player_views = []
        for i, cards in enumerate(self.game_model.cards):
            name = "player {}".format(i + 1)
            self.player_views.append(PackView(name, cards))

        self.open_view = PackView("open", self.game_model.cards_open)
        self.open_view.switch_to_open_view()
        self.hidden_view = PackView("hidden", self.game_model.cards_hidden)
        self.hidden_view.switch_to_hidden_view()

        self.question_view = QuestionView(
            self.game_model.questions_in_hand_number,
            self.game_model.players_number)
        self.question_view.set_questions(self.game_model.players_questions[0])

        self.board_view = BoardView(self.player_views, self.open_view,
                                    self.hidden_view, self.question_view)

        self.question_view.question_clicked.connect(
            self.question_button_clicked)
        self.board_view.next_turn_button.clicked.connect(
            self.nex_player_button_clicked)
        self.board_view.restart_button.clicked.connect(self.restart_clicked)

        self.update_tables_for_cur_player()
        self.update_tips()
        self.update_views()

        self.board_view.next_turn_button.setDisabled(True)
예제 #7
0
    def __init__(self, gamemodel, actionMenuItems):
        gtk.EventBox.__init__(self)
        self.promotionDialog = PromotionDialog()
        self.view = BoardView(gamemodel)
        self.add(self.view)
        self.variant = gamemodel.variant

        self.RANKS = gamemodel.boards[0].RANKS
        self.FILES = gamemodel.boards[0].FILES
        
        self.actionMenuItems = actionMenuItems
        self.connections = {}
        for key, menuitem in self.actionMenuItems.iteritems():
            if menuitem == None: print key
            self.connections[menuitem] = menuitem.connect("activate", self.actionActivate, key)
        
        self.view.connect("shown_changed", self.shown_changed)
        gamemodel.connect("moves_undoing", self.moves_undone)
        self.connect("button_press_event", self.button_press)
        self.connect("button_release_event", self.button_release)
        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.connect("motion_notify_event", self.motion_notify)
        self.connect("leave_notify_event", self.leave_notify)
        
        self.selected_last = None
        self.stateLock = threading.Lock()
        self.normalState = NormalState(self)
        self.selectedState = SelectedState(self)
        self.activeState = ActiveState(self)
        self.lockedNormalState = LockedNormalState(self)
        self.lockedSelectedState = LockedSelectedState(self)
        self.lockedActiveState = LockedActiveState(self)
        self.currentState = self.normalState
        
        self.lockedPly = self.view.shown
        self.possibleBoards = {
            self.lockedPly : self._genPossibleBoards(self.lockedPly) }
        
        self.allowPremove = False
        def onGameStart (gamemodel):
            for player in gamemodel.players:
                if player.__type__ == LOCAL:
                    self.allowPremove = True
        gamemodel.connect("game_started", onGameStart)
        self.keybuffer = ""
예제 #8
0
class BoardControl(object):

    def __init__(self, sizex, sizey):

        self.sizex = sizex
        self.sizey = sizey
        self.view = BoardView(sizex,sizey,600,480)
        self.model = BoardModel(sizex,sizey)

        self.keyPressed = False
        #self.action()

    def action(self):

        self.waitInput = True
        self.bx = self.by = None

        while self.waitInput:
            for event in pygame.event.get():
                self.handleEvent(event)

    def handleEvent(self, event):

        if event.type == QUIT:
            self.triggerEnd()

        if event.type == MOUSEBUTTONDOWN:
            self.handleMouseButtonEvents(event)

        if event.type == KEYUP:
            self.keyPressed = False

        if event.type == KEYDOWN and not self.keyPressed:
            self.keyPressed = True
            self.handleKeyEvents(event)

    def handleKeyEvents(self, event):

        if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
            self.triggerEnd()

    def triggerEnd(self):
        exit()

    def handleMouseButtonEvents(self, event):

        (x,y) = event.pos
        (bx,by) = self.view.point2Box(x,y)

        #print "(x: %d, y: %d) -> (bx: %d, by: %d)" %(x,y,bx,by)

        if bx in range(self.sizex) and by in range(self.sizey):

            if event.button == 1:
                self.waitInput = False;
                self.bx = bx
                self.by = by

    def renderModel(self):

        for x in range(self.sizex):
            for y in range(self.sizey):
                cell = self.model.getPoint(x,y)
                if cell == 'W':
                    self.view.setBoxWhite(x,y)
                elif cell == 'B':
                    self.view.setBoxBlack(x,y)
                elif cell == 'w':
                    self.view.setCanMoveWhite(x,y)
                elif cell == 'b':
                    self.view.setCanMoveBlack(x,y)
                else:
                    self.view.unsetBox(x,y)

        self.view.update()

    def importModel(self,model):
        for y in range(self.sizey):
            for x in range(self.sizex):
                value = model[y*self.sizey+x] 
                if value == 'W' or value == 'B':
                    self.model.setPoint(x,y,value)
                else:
                    self.model.unsetPoint(x,y)
                    self.model.setPoint(x,y,value)

    def setCanMove(self, bx, by, turn):
        self.model.setPoint(bx-1,by-1, turn.lower())

    def cursorHand(self):
        self.view.cursorHand()

    def cursorWait(self):
        self.view.cursorWait()
예제 #9
0
class BoardControl(gtk.EventBox):

    __gsignals__ = {
        'piece_moved': (SIGNAL_RUN_FIRST, TYPE_NONE, (object, int)),
        'action': (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object))
    }

    def __init__(self, gamemodel, actionMenuItems):
        gtk.EventBox.__init__(self)
        self.promotionDialog = PromotionDialog()
        self.view = BoardView(gamemodel)
        self.add(self.view)

        self.actionMenuItems = actionMenuItems
        self.connections = {}
        for key, menuitem in self.actionMenuItems.iteritems():
            if menuitem == None: print key
            self.connections[menuitem] = menuitem.connect(
                "activate", self.actionActivate, key)

        self.view.connect("shown_changed", self.shown_changed)
        gamemodel.connect("moves_undoing", self.moves_undone)
        self.connect("button_press_event", self.button_press)
        self.connect("button_release_event", self.button_release)
        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK
                        | gtk.gdk.POINTER_MOTION_MASK)
        self.connect("motion_notify_event", self.motion_notify)
        self.connect("leave_notify_event", self.leave_notify)

        self.selected_last = None
        self.stateLock = threading.Lock()
        self.normalState = NormalState(self)
        self.selectedState = SelectedState(self)
        self.activeState = ActiveState(self)
        self.lockedState = LockedState(self)
        self.lockedSelectedState = LockedSelectedState(self)
        self.lockedActiveState = LockedActiveState(self)
        self.currentState = self.lockedState

        self.lockedPly = self.view.shown
        self.possibleBoards = {
            self.lockedPly: self._genPossibleBoards(self.lockedPly)
        }

        self.allowPremove = False

        def onGameStart(gamemodel):
            for player in gamemodel.players:
                if player.__type__ == LOCAL:
                    self.allowPremove = True

        gamemodel.connect("game_started", onGameStart)

    def __del__(self):
        for menu, conid in self.connections.iteritems():
            menu.disconnect(conid)
        self.connections = {}

    def emit_move_signal(self, cord0, cord1):
        color = self.view.model.boards[-1].color
        board = self.view.model.getBoardAtPly(self.view.shown)

        # Ask player for which piece to promote into. If this move does not
        # include a promotion, QUEEN will be sent as a dummy value, but not used
        promotion = QUEEN
        if board[cord0].sign == PAWN and cord1.y in (0, 7):
            res = self.promotionDialog.runAndHide(color)
            if res != gtk.RESPONSE_DELETE_EVENT:
                promotion = res
            else:
                # Put back pawn moved be d'n'd
                self.view.runAnimation(redrawMisc=False)
                return

        move = Move(cord0, cord1, self.view.model.boards[-1], promotion)
        self.emit("piece_moved", move, color)

    def actionActivate(self, widget, key):
        """ Put actions from a menu or similar """
        if key == "call_flag":
            self.emit("action", FLAG_CALL, None)
        elif key == "abort":
            self.emit("action", ABORT_OFFER, None)
        elif key == "adjourn":
            self.emit("action", ADJOURN_OFFER, None)
        elif key == "draw":
            self.emit("action", DRAW_OFFER, None)
        elif key == "resign":
            self.emit("action", RESIGNATION, None)
        elif key == "ask_to_move":
            self.emit("action", HURRY_ACTION, None)
        elif key == "undo1":
            if self.view.model.curplayer.__type__ == LOCAL \
               and self.view.model.ply > 1:
                self.emit("action", TAKEBACK_OFFER, self.view.model.ply - 2)
            else:
                self.emit("action", TAKEBACK_OFFER, self.view.model.ply - 1)
        elif key == "pause1":
            self.emit("action", PAUSE_OFFER, None)
        elif key == "resume1":
            self.emit("action", RESUME_OFFER, None)

    def shown_changed(self, view, shown):
        self.lockedPly = self.view.shown
        self.possibleBoards[self.lockedPly] = self._genPossibleBoards(
            self.lockedPly)
        if self.view.shown - 2 in self.possibleBoards:
            del self.possibleBoards[self.view.shown - 2]

    def moves_undone(self, gamemodel, moves):
        self.stateLock.acquire()
        try:
            self.view.selected = None
            self.view.active = None
            self.view.hover = None
            self.view.draggedPiece = None
            self.view.startAnimation()
            self.currentState = self.lockedState
        finally:
            self.stateLock.release()

    def setLocked(self, locked):
        self.stateLock.acquire()
        try:
            if locked:
                if self.view.model.status != RUNNING:
                    self.view.selected = None
                    self.view.active = None
                    self.view.hover = None
                    self.view.draggedPiece = None
                    self.view.startAnimation()
                self.currentState = self.lockedState
            else:
                if self.currentState == self.lockedSelectedState:
                    self.currentState = self.selectedState
                elif self.currentState == self.lockedActiveState:
                    self.currentState = self.activeState
                else:
                    self.currentState = self.normalState
        finally:
            self.stateLock.release()

    def setStateSelected(self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState,
                                     self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedSelectedState
            else:
                self.currentState = self.selectedState
        finally:
            self.stateLock.release()

    def setStateActive(self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState,
                                     self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedActiveState
            else:
                self.currentState = self.activeState
        finally:
            self.stateLock.release()

    def setStateNormal(self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState,
                                     self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedState
            else:
                self.currentState = self.normalState
        finally:
            self.stateLock.release()

    def button_press(self, widget, event):
        return self.currentState.press(event.x, event.y)

    def button_release(self, widget, event):
        return self.currentState.release(event.x, event.y)

    def motion_notify(self, widget, event):
        return self.currentState.motion(event.x, event.y)

    def leave_notify(self, widget, event):
        return self.currentState.leave(event.x, event.y)

    def _genPossibleBoards(self, ply):
        possibleBoards = []
        curboard = self.view.model.getBoardAtPly(ply)
        for lmove in lmovegen.genAllMoves(curboard.board):
            move = Move(lmove)
            board = curboard.move(move)
            possibleBoards.append(board)
        return possibleBoards
예제 #10
0
class GameController():
    def __init__(self, app):
        self.restart_pressed = False
        self.already_won = False
        self.total_cur_words_n = 0
        self.app = app
        self.game_model = GameModel()

        self.player_views = []
        for i, cards in enumerate(self.game_model.cards):
            name = "player {}".format(i + 1)
            self.player_views.append(PackView(name, cards))

        self.open_view = PackView("open", self.game_model.cards_open)
        self.open_view.switch_to_open_view()
        self.hidden_view = PackView("hidden", self.game_model.cards_hidden)
        self.hidden_view.switch_to_hidden_view()

        self.question_view = QuestionView(
            self.game_model.questions_in_hand_number,
            self.game_model.players_number)
        self.question_view.set_questions(self.game_model.players_questions[0])

        self.board_view = BoardView(self.player_views, self.open_view,
                                    self.hidden_view, self.question_view)

        self.question_view.question_clicked.connect(
            self.question_button_clicked)
        self.board_view.next_turn_button.clicked.connect(
            self.nex_player_button_clicked)
        self.board_view.restart_button.clicked.connect(self.restart_clicked)

        self.update_tables_for_cur_player()
        self.update_tips()
        self.update_views()

        self.board_view.next_turn_button.setDisabled(True)

    def start(self):
        self.board_view.showMaximized()
        self.app.exec_()
        return self.restart_pressed

    def question_button_clicked(self, str):
        if str.lower().startswith("player"):
            self.game_model.player_to_ask_choosen(str)
            self.update_tables_for_cur_player()
            self.question_view.disable_all()
            self.update_views()
            self.update_tips()
            self.board_view.next_turn_button.setEnabled(True)
        else:
            question = str.split(" ")
            self.game_model.question_chosen(question)
            self.question_view.change_player_question_mode(False)
            #self.update_views()
            #self.update_tips()

    def update_views(self):
        if not self.already_won:
            self.question_view.set_questions(
                self.game_model.get_cuurent_player_questions())
            info_text = ""
            answer_text = " "
            if self.game_model.game_state == GameState.PLAYER_TO_ASK_CHOOSING:
                question = ''.join(s + " "
                                   for s in self.game_model.question_gonna_ask)
                info_text = "Question is {}. Choose the player to ask".format(
                    question)
            elif self.game_model.game_state == GameState.QUESTION_CHOOSING:
                self.question_view.hide_player_button_but_show_others(
                    self.game_model.current_turn_player)
                info_text = "Choose the question to ask"
            elif self.game_model.game_state == GameState.CURRENT_PLAYER_FINISHED:
                info_text = "click 'Next player' when you finished"
                answer_text = "Answer: " + self.game_model.last_answer

            self.board_view.info_label.setText("Player {} turn. ".format(
                self.game_model.current_turn_player + 1) + info_text)
            self.board_view.answer_label.setText(answer_text)

            self.update_hide_show_views()
            self.update_tables_for_cur_player()

    def update_hide_show_views(self):
        for i, view in enumerate(self.player_views):
            if (i == self.game_model.current_turn_player):
                view.switch_to_open_view()
            else:
                view.switch_to_hidden_view()

    def update_tables_for_cur_player(self):
        possible_variant, varian_numbers, total_number = self.game_model.get_possible_states_for_cur_player(
        )
        self.total_cur_words_n = total_number
        self.hidden_view.update_tables(possible_variant[0], varian_numbers[0],
                                       total_number)
        for i, view in enumerate(self.player_views):
            if i != self.game_model.current_turn_player:
                view.update_tables(possible_variant[i + 1],
                                   varian_numbers[i + 1], total_number)

        if (len(possible_variant[0]) == 1) and not self.already_won:
            self.already_won = True
            self.hidden_view.show_both()
            self.board_view.restart_button.show()
            self.board_view.next_turn_button.hide()
            self.board_view.answer_label.hide()
            self.board_view.info_label.setText(
                "Player {} won, congratulation!!!. To play again press 'Restart' button"
                .format(self.game_model.current_turn_player + 1))

    def update_tips(self):
        tips = self.game_model.get_tips_for_cur_player()

        players = [1, 2, 3]
        players.remove(self.game_model.current_turn_player + 1)

        self.question_view.setTips(tips, players, self.total_cur_words_n)

    def nex_player_button_clicked(self):
        self.game_model.next_turn()
        self.game_model.start_turn()
        self.update_views()
        self.update_tips()
        self.question_view.change_player_question_mode(True)
        self.board_view.next_turn_button.setDisabled(True)

    def restart_clicked(self):
        self.restart_pressed = True
        self.app.quit()
예제 #11
0
파일: Game.py 프로젝트: Gerome/XXOs
    def start(self):

        innerBoards = [[InnerBoard(), InnerBoard(),
                        InnerBoard()],
                       [InnerBoard(), InnerBoard(),
                        InnerBoard()],
                       [InnerBoard(), InnerBoard(),
                        InnerBoard()]]

        overallBoard = InnerBoard()

        mainBoard = Board(innerBoards)
        boardView = BoardView()

        playerOneNoughtCross = NoughtCross(
            input("Player 1, please input your symbol.\r\n"))
        playerTwoNoughtCross = NoughtCross(
            input("Player 2, please input your symbol.\r\n"))

        playerCharacters = [playerOneNoughtCross, playerTwoNoughtCross]

        currentPlayer = 2
        playerSwitchValue = -1

        xBoard, yBoard = 1, 1

        print("Enter \"tl\" for the top left position.")

        while not self.gameIsFinished:

            print(boardView.GetFormattedBoard())

            currentPlayer += playerSwitchValue
            playerSwitchValue *= -1

            validMove = False

            while not validMove:
                print("Player {}'s go.".format(currentPlayer))

                userInput = input("Where do you want to go?\r\n").lower()

                if userInput.startswith('t'):
                    yInput = 0
                if userInput.startswith('m'):
                    yInput = 1
                if userInput.startswith('b'):
                    yInput = 2

                if userInput.endswith('l'):
                    xInput = 0
                if userInput.endswith('m'):
                    xInput = 1
                if userInput.endswith('r'):
                    xInput = 2

                moveReturnValue = mainBoard.TakeTurn(
                    xBoard, yBoard, int(xInput), int(yInput),
                    playerCharacters[currentPlayer - 1])
                validMove = (moveReturnValue == InnerBoard.ERROR_NO_ERROR)

                if not validMove:
                    print("INVALID MOVE!\r\n")

            boardView.UpdateBoard(xBoard, yBoard, xInput, yInput,
                                  playerCharacters[currentPlayer - 1].type)

            self.CheckForWin(currentPlayer, mainBoard, overallBoard,
                             playerCharacters, xBoard, yBoard)

            if (self.gameIsFinished):
                print(boardView.GetFormattedBoard())
                print("Player {} wins!.".format(currentPlayer))

            xBoard = xInput
            yBoard = yInput
예제 #12
0
 def setUp(self):
     self.boardView = BoardView()
     self.testBoard = self.EMPTY_BOARD
예제 #13
0
class Game:

    #Default Constructor
    def __init__(self):
        #GameBoard, display and notification objects
        self.board = Board()
        self.boardView = BoardView()
        self.notifications = Notifications()
        #Player objects
        self.human = Human()
        self.computer = Computer()
        #Toss Variables
        self.humanDieToss = 0
        self.computerDieToss = 0
        #Control variables
        self.humanTurn = False
        self.computerTurn = False
        #Variables to store user input of coordinates
        self.startRow = 0
        self.startCol = 0
        self.endRow = 0
        self.endCol = 0
        #1 for vertical first, 2 for lateral first
        self.path = 0

    """ *********************************************************************
    Function Name: implement_game

    Purpose: Runs a full game until someone wins or user requests serialization

    Parameters:
    restoringGame, boolean value stating whether a restore of previous game was requested by user
    nextPlayer, a string that contains who's turn is next (if restoring) (Computer or Human)

    Return Value: 'c' if bot wins, 'h' if human wins, 'S' if serialization requested during bot turn, 's' if serialization requested during human turn

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    #Implements a Round.
    #Return value is 'h' for human winner, 'c' for computer winner, 'S' for serializing during computer's turn, 's' for serializing during human's turn
    def implement_game(self, restoringGame, nextPlayer=""):
        #Set the turns if restoring a game from saved state
        if restoringGame:
            if (nextPlayer == "Computer"):
                self.computerTurn = True
            if (nextPlayer == "Human"):
                self.humanTurn = True

        #Draw Initial Board
        self.boardView.draw_board(self.board)

        #Conduct a toss if the controls haven't been assigned while restoring
        if (not self.humanTurn and not self.computerTurn):
            self.toss_to_begin()

        #Continue the loop until one of the king is captured, one of the key squares gets occupied or user chooses to serialize and quit
        while True:
            refresh = False
            #If it is computer's turn
            if self.computerTurn:
                self.notifications.msg_turns("COMPUTER'S TURN")
                if (self.computer.play(self.board, False)):
                    #Transfer Controls
                    self.computerTurn = False
                    self.humanTurn = True
                    self.notifications.msg_turns("BOARD AFTER COMPUTER'S MOVE")
                    refresh = True  #Using this boolean to prevent human's loop from running immediately
                else:
                    continue

            #If it is human's Turn
            if not refresh:
                if self.humanTurn:
                    self.notifications.msg_turns("YOUR TURN")
                    if self.turn_help_mode_on():
                        self.notifications.msg_helpmode_on()
                        #Calling computer Play in Help Mode
                        self.computer.play(self.board, True)

                    self.get_user_input()
                    if (self.human.play(self.startRow, self.startCol,
                                        self.endRow, self.endCol, self.board,
                                        self.path)):
                        self.humanTurn = False
                        self.computerTurn = True  #Transferring controls
                        self.notifications.msg_turns(
                            "BOARD AFTER HUMAN'S MOVE")
                    else:
                        self.notifications.msg_invalid_move()
                        continue

            #After the move is made
            #Re-draw the board after each move
            self.boardView.draw_board(self.board)

            #If game over condition met
            if (self.game_over_condition_met()):
                #Whoever just received the control is the one who lost
                if self.humanTurn:
                    self.notifications.msg_game_over("COMPUTER")
                    return 'c'  #Bot Winner
                else:
                    self.notifications.msg_game_over("HUMAN")
                    return 'h'  #Human Winner
            """Stop the game and return if user wants to serialize
            return 'S' if serializing during computer's turn, 's' if serializing during human's turn"""
            if self.user_wants_to_serialize():
                if self.computerTurn:
                    return 'S'
                if self.humanTurn:
                    return 's'

    """ *********************************************************************
    Function Name: turn_help_mode_on

    Purpose: Ask human player if they want to turn help mode on

    Parameters: none

    Return Value: true if user requests help mode, false otherwise

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    # Receives user input on whether they want to turn on help mode
    def turn_help_mode_on(self):
        #Continue asking user for input until they press 'y' or 'n'
        while True:
            self.notifications.msg_help_mode_prompt()
            input = getche()
            if (input == 'y' or input == 'Y'):
                return True
            if (input == 'n' or input == 'N'):
                return False
            self.notifications.msg_improper_input()

    """ *********************************************************************
    Function Name: user_wants_to_serialize

    Purpose: Ask human player if they want to serialize

    Parameters: none

    Return Value: true if user requests serialization, false otherwise

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    # Asks if user wants to serialize & returns true if user wants to serialize
    def user_wants_to_serialize(self):
        #Continue asking user for input until they press 'y' or 'n'
        while True:
            self.notifications.msg_serialize_prompt()
            input = getche()
            if (input == 'y' or input == 'Y'):
                return True
            if (input == 'n' or input == 'N'):
                return False
            self.notifications.msg_improper_input()

    """ *********************************************************************
    Function Name: game_over_condition_met

    Purpose: To check if the condition for game over has been met

    Parameters: none

    Return Value: true if condition met for game to be over, false otherwise

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    # Checks if the condition to end the game has been met
    def game_over_condition_met(self):
        #If one of the kings captured
        if (self.board.get_human_king().captured
                or self.board.get_bot_king().captured):
            return True

        #If the human key square is occupied by the bots king die
        if (self.board.get_square_resident(0, 4) != None):
            if (self.board.get_square_resident(0, 4).botOperated):
                if (self.board.get_square_resident(0, 4).king):
                    return True

        #If the computer key square is occupied by the Human king die
        if (self.board.get_square_resident(7, 4) != None):
            if (not self.board.get_square_resident(7, 4).botOperated):
                if (self.board.get_square_resident(7, 4).king):
                    return True

        #If none of the game over conditions are met
        return False

    """ *********************************************************************
    Function Name: get_user_input

    Purpose: To get user input for coordinates

    Parameters: none

    Return Value: none

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    # Gets user input for coordinates if it is a human's turn
    def get_user_input(self):
        self.startRow = 0
        self.startCol = 0
        self.endRow = 0
        self.endCol = 0
        self.path = 0

        #Continue asking user for input until they press all the digits
        #Ask for origin row
        while True:
            self.notifications.msg_enter_origin_row()
            input = getche()
            try:
                self.startRow = int(input)
                break
            except ValueError:
                self.notifications.msg_improper_input()

        #Ask for origin column
        while True:
            self.notifications.msg_enter_origin_column()
            input = getche()
            try:
                self.startCol = int(input)
                break
            except ValueError:
                self.notifications.msg_improper_input()

        #Ask for destination row
        while True:
            self.notifications.msg_enter_destination_row()
            input = getche()
            try:
                self.endRow = int(input)
                break
            except ValueError:
                self.notifications.msg_improper_input()

        #Ask for destination column
        while True:
            self.notifications.msg_enter_destination_column()
            input = getche()
            try:
                self.endCol = int(input)
                break
            except ValueError:
                self.notifications.msg_improper_input()

        #In case of a 90 degree turn, ask the path preference as well
        if ((self.startRow != self.endRow) and (self.startCol != self.endCol)):
            while True:
                self.notifications.msg_90degree_path_selection()
                input = getche()
                try:
                    if (int(input) == 1 or int(input) == 2):
                        self.path = int(input)
                        break
                except ValueError:
                    self.notifications.msg_improper_input()

    """ *********************************************************************
    Function Name: toss_to_begin

    Purpose: To conduct a toss and set the turn of appropriate player to true

    Parameters: none

    Return Value: none

    Local Variables: none

    Assistance Received: none
    ********************************************************************* """

    # Does a toss to determine which team will start the game
    def toss_to_begin(self):

        #Continue until both have different toss results
        while True:
            self.humanDieToss = randint(1, 6)
            self.computerDieToss = randint(1, 6)

            if (self.humanDieToss != self.computerDieToss):
                break

        #Whoever has the highest number on top - wins the toss
        if (self.humanDieToss > self.computerDieToss):
            self.humanTurn = True
            self.notifications.msg_toss_results("You", self.humanDieToss,
                                                self.computerDieToss)
        else:
            self.computerTurn = True
            self.notifications.msg_toss_results("Computer", self.humanDieToss,
                                                self.computerDieToss)
class BoardControl (gtk.EventBox):
    
    __gsignals__ = {
        'piece_moved' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object, int)),
        'action' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object))
    }
    
    def __init__(self, gamemodel, actionMenuItems):
        gtk.EventBox.__init__(self)
        self.promotionDialog = PromotionDialog()
        self.view = BoardView(gamemodel)
        self.add(self.view)
        
        self.actionMenuItems = actionMenuItems
        self.connections = {}
        for key, menuitem in self.actionMenuItems.iteritems():
            if menuitem == None: print key
            self.connections[menuitem] = menuitem.connect("activate", self.actionActivate, key)
        
        self.view.connect("shown_changed", self.shown_changed)
        gamemodel.connect("moves_undoing", self.moves_undone)
        self.connect("button_press_event", self.button_press)
        self.connect("button_release_event", self.button_release)
        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.connect("motion_notify_event", self.motion_notify)
        self.connect("leave_notify_event", self.leave_notify)
        
        self.selected_last = None
        self.stateLock = threading.Lock()
        self.normalState = NormalState(self)
        self.selectedState = SelectedState(self)
        self.activeState = ActiveState(self)
        self.lockedState = LockedState(self)
        self.lockedSelectedState = LockedSelectedState(self)
        self.lockedActiveState = LockedActiveState(self)
        self.currentState = self.lockedState
        
        self.lockedPly = self.view.shown
        self.possibleBoards = {
            self.lockedPly : self._genPossibleBoards(self.lockedPly) }
        
        self.allowPremove = False
        def onGameStart (gamemodel):
            for player in gamemodel.players:
                if player.__type__ == LOCAL:
                    self.allowPremove = True
        gamemodel.connect("game_started", onGameStart)
        
    def __del__ (self):
        for menu, conid in self.connections.iteritems():
            menu.disconnect(conid)
        self.connections = {}
        
    def emit_move_signal (self, cord0, cord1):
        color = self.view.model.boards[-1].color
        board = self.view.model.getBoardAtPly(self.view.shown)
        
        # Ask player for which piece to promote into. If this move does not
        # include a promotion, QUEEN will be sent as a dummy value, but not used
        promotion = QUEEN
        if board[cord0].sign == PAWN and cord1.y in (0,7):
            res = self.promotionDialog.runAndHide(color)
            if res != gtk.RESPONSE_DELETE_EVENT:
                promotion = res
            else:
                # Put back pawn moved be d'n'd
                self.view.runAnimation(redrawMisc = False)
                return
        
        move = Move(cord0, cord1, self.view.model.boards[-1], promotion)
        self.emit("piece_moved", move, color)
    
    def actionActivate (self, widget, key):
        """ Put actions from a menu or similar """
        if key == "call_flag":
            self.emit("action", FLAG_CALL, None)
        elif key == "abort":
            self.emit("action", ABORT_OFFER, None)
        elif key == "adjourn":
            self.emit("action", ADJOURN_OFFER, None)
        elif key == "draw":
            self.emit("action", DRAW_OFFER, None)
        elif key == "resign":
            self.emit("action", RESIGNATION, None)
        elif key == "ask_to_move":
            self.emit("action", HURRY_ACTION, None)
        elif key == "undo1":
            if self.view.model.curplayer.__type__ == LOCAL \
               and self.view.model.ply > 1:
                self.emit("action", TAKEBACK_OFFER, self.view.model.ply-2)
            else: self.emit("action", TAKEBACK_OFFER, self.view.model.ply-1)
        elif key == "pause1":
            self.emit("action", PAUSE_OFFER, None)
        elif key == "resume1":
            self.emit("action", RESUME_OFFER, None)
    
    def shown_changed (self, view, shown):
        self.lockedPly = self.view.shown
        self.possibleBoards[self.lockedPly] = self._genPossibleBoards(self.lockedPly)
        if self.view.shown-2 in self.possibleBoards:
            del self.possibleBoards[self.view.shown-2]
    
    def moves_undone (self, gamemodel, moves):
        self.stateLock.acquire()
        try:
            self.view.selected = None
            self.view.active = None
            self.view.hover = None
            self.view.draggedPiece = None
            self.view.startAnimation()
            self.currentState = self.lockedState
        finally:
            self.stateLock.release()
    
    def setLocked (self, locked):
        self.stateLock.acquire()
        try:
            if locked:
                if self.view.model.status != RUNNING:
                    self.view.selected = None
                    self.view.active = None
                    self.view.hover = None
                    self.view.draggedPiece = None
                    self.view.startAnimation()
                self.currentState = self.lockedState
            else:
                if self.currentState == self.lockedSelectedState:
                    self.currentState = self.selectedState
                elif self.currentState == self.lockedActiveState:
                    self.currentState = self.activeState
                else:
                    self.currentState = self.normalState
        finally:
            self.stateLock.release()
    
    def setStateSelected (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedSelectedState
            else:
                self.currentState = self.selectedState
        finally:
            self.stateLock.release()
    
    def setStateActive (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedActiveState
            else:
                self.currentState = self.activeState
        finally:
            self.stateLock.release()
    
    def setStateNormal (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedState
            else:
                self.currentState = self.normalState
        finally:
            self.stateLock.release()
    
    def button_press (self, widget, event):
        return self.currentState.press(event.x, event.y)
    
    def button_release (self, widget, event):
        return self.currentState.release(event.x, event.y)
    
    def motion_notify (self, widget, event):
        return self.currentState.motion(event.x, event.y)
    
    def leave_notify (self, widget, event):
        return self.currentState.leave(event.x, event.y)
    
    def _genPossibleBoards(self, ply):
        possibleBoards = []
        curboard = self.view.model.getBoardAtPly(ply)
        for lmove in lmovegen.genAllMoves(curboard.board):
            move = Move(lmove)
            board = curboard.move(move)
            possibleBoards.append(board)        
        return possibleBoards
예제 #15
0
class BoardControl (gtk.EventBox):
    
    __gsignals__ = {
        'piece_moved' : (SIGNAL_RUN_FIRST, TYPE_NONE, (object, int)),
        'action' : (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object))
    }
    
    def __init__(self, gamemodel, actionMenuItems):
        gtk.EventBox.__init__(self)
        self.promotionDialog = PromotionDialog()
        self.view = BoardView(gamemodel)
        self.add(self.view)
        self.variant = gamemodel.variant

        self.RANKS = gamemodel.boards[0].RANKS
        self.FILES = gamemodel.boards[0].FILES
        
        self.actionMenuItems = actionMenuItems
        self.connections = {}
        for key, menuitem in self.actionMenuItems.iteritems():
            if menuitem == None: print key
            self.connections[menuitem] = menuitem.connect("activate", self.actionActivate, key)
        
        self.view.connect("shown_changed", self.shown_changed)
        gamemodel.connect("moves_undoing", self.moves_undone)
        self.connect("button_press_event", self.button_press)
        self.connect("button_release_event", self.button_release)
        self.add_events(gtk.gdk.LEAVE_NOTIFY_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.connect("motion_notify_event", self.motion_notify)
        self.connect("leave_notify_event", self.leave_notify)
        
        self.selected_last = None
        self.stateLock = threading.Lock()
        self.normalState = NormalState(self)
        self.selectedState = SelectedState(self)
        self.activeState = ActiveState(self)
        self.lockedNormalState = LockedNormalState(self)
        self.lockedSelectedState = LockedSelectedState(self)
        self.lockedActiveState = LockedActiveState(self)
        self.currentState = self.normalState
        
        self.lockedPly = self.view.shown
        self.possibleBoards = {
            self.lockedPly : self._genPossibleBoards(self.lockedPly) }
        
        self.allowPremove = False
        def onGameStart (gamemodel):
            for player in gamemodel.players:
                if player.__type__ == LOCAL:
                    self.allowPremove = True
        gamemodel.connect("game_started", onGameStart)
        self.keybuffer = ""
        
    def __del__ (self):
        for menu, conid in self.connections.iteritems():
            menu.disconnect(conid)
        self.connections = {}
        self.view.save_board_size()

    def getPromotion(self):
        color = self.view.model.boards[-1].color
        variant = self.view.model.boards[-1].variant
        promotion = None
        glock.acquire()
        try:
            promotion = self.promotionDialog.runAndHide(color, variant)
        finally:
            glock.release()
        return promotion
        
    def emit_move_signal (self, cord0, cord1, promotion=None):
        color = self.view.model.boards[-1].color
        board = self.view.model.getBoardAtPly(self.view.shown, self.view.shownVariationIdx)
        # Ask player for which piece to promote into. If this move does not
        # include a promotion, QUEEN will be sent as a dummy value, but not used
        
        if promotion is None and board[cord0].sign == PAWN and cord1.y in (0, self.RANKS-1):
            promotion = self.getPromotion()
            if promotion is None:
                # Put back pawn moved be d'n'd
                self.view.runAnimation(redrawMisc = False)
                return
        
        if cord0.x < 0 or cord0.x > self.FILES-1:
            move = Move(lmovegen.newMove(board[cord0].piece, cord1.cord, DROP))
        else:
            move = Move(cord0, cord1, board, promotion)
        
        if self.view.model.curplayer.__type__ == LOCAL and self.view.shownIsMainLine() and \
           board.board.next is None and self.view.model.status == RUNNING:
            #self.emit("piece_moved", move, color)
        else:
            if board.board.next is None and not self.view.shownIsMainLine():
                self.view.model.add_move2variation(board, move, self.view.shownVariationIdx)
                self.view.shown += 1
            else:
                new_vari = self.view.model.add_variation(board, (move,))
                self.view.setShownBoard(new_vari[-1])
    
    def actionActivate (self, widget, key):
        """ Put actions from a menu or similar """
        if key == "call_flag":
            #self.emit("action", FLAG_CALL, None)
        elif key == "abort":
            #self.emit("action", ABORT_OFFER, None)
        elif key == "adjourn":
            #self.emit("action", ADJOURN_OFFER, None)
        elif key == "draw":
            #self.emit("action", DRAW_OFFER, None)
        elif key == "resign":
            #self.emit("action", RESIGNATION, None)
        elif key == "ask_to_move":
            #self.emit("action", HURRY_ACTION, None)
        elif key == "undo1":
            curColor = self.view.model.variations[0][-1].color
            curPlayer = self.view.model.players[curColor]
            if curPlayer.__type__ == LOCAL and self.view.model.ply > 1:
                #self.emit("action", TAKEBACK_OFFER, self.view.model.ply-2)
            else:
                #self.emit("action", TAKEBACK_OFFER, self.view.model.ply-1)
        elif key == "pause1":
            #self.emit("action", PAUSE_OFFER, None)
        elif key == "resume1":
            #self.emit("action", RESUME_OFFER, None)
    
    def shown_changed (self, view, shown):
        self.lockedPly = self.view.shown
        self.possibleBoards[self.lockedPly] = self._genPossibleBoards(self.lockedPly)
        if self.view.shown-2 in self.possibleBoards:
            del self.possibleBoards[self.view.shown-2]
    
    def moves_undone (self, gamemodel, moves):
        self.stateLock.acquire()
        try:
            self.view.selected = None
            self.view.active = None
            self.view.hover = None
            self.view.draggedPiece = None
            self.view.startAnimation()
            self.currentState = self.lockedNormalState
        finally:
            self.stateLock.release()

    def getBoard (self):
        return self.view.model.getBoardAtPly(self.view.shown, self.view.shownVariationIdx)

    def isLastPlayed(self, board):
        return board == self.view.model.boards[-1]
    
    def setLocked (self, locked):
        self.stateLock.acquire()
        try:
            if locked and self.isLastPlayed(self.getBoard()) and self.view.model.status == RUNNING:
                if self.view.model.status != RUNNING:
                    self.view.selected = None
                    self.view.active = None
                    self.view.hover = None
                    self.view.draggedPiece = None
                    self.view.startAnimation()

                if self.currentState == self.selectedState:
                    self.currentState = self.lockedSelectedState
                elif self.currentState == self.activeState:
                    self.currentState = self.lockedActiveState
                else:
                    self.currentState = self.lockedNormalState
            else:
                if self.currentState == self.lockedSelectedState:
                    self.currentState = self.selectedState
                elif self.currentState == self.lockedActiveState:
                    self.currentState = self.activeState
                else:
                    self.currentState = self.normalState
        finally:
            self.stateLock.release()
    
    def setStateSelected (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedNormalState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedSelectedState
            else:
                self.view.setPremove(None, None, None, None)
                self.currentState = self.selectedState
        finally:
            self.stateLock.release()
    
    def setStateActive (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedNormalState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedActiveState
            else:
                self.view.setPremove(None, None, None, None)
                self.currentState = self.activeState
        finally:
            self.stateLock.release()
    
    def setStateNormal (self):
        self.stateLock.acquire()
        try:
            if self.currentState in (self.lockedNormalState, self.lockedSelectedState,
                                     self.lockedActiveState):
                self.currentState = self.lockedNormalState
            else:
                self.view.setPremove(None, None, None, None)
                self.currentState = self.normalState
        finally:
            self.stateLock.release()
    
    def button_press (self, widget, event):
        return self.currentState.press(event.x, event.y, event.button)
    
    def button_release (self, widget, event):
        return self.currentState.release(event.x, event.y)
    
    def motion_notify (self, widget, event):
        return self.currentState.motion(event.x, event.y)
    
    def leave_notify (self, widget, event):
        return self.currentState.leave(event.x, event.y)

    def key_pressed (self, keyname):
        if keyname in "PNBRQKOox12345678abcdefgh":
            self.keybuffer += keyname
        elif keyname == "minus":
            self.keybuffer += "-"
        elif keyname == "at":
            self.keybuffer += "@"
        elif keyname == "Return":
            color = self.view.model.boards[-1].color
            board = self.view.model.getBoardAtPly(self.view.shown, self.view.shownVariationIdx)
            try:
                move = parseAny(board, self.keybuffer)
            except:
                self.keybuffer = ""
                return
            if validate(board, move):
                if self.view.shownIsMainLine() and board.board.next is None:
                    #self.emit("piece_moved", move, color)
                else:
                    if board.board.next is None:
                        self.view.model.add_move2variation(board, move, self.view.shownVariationIdx)
                        self.view.shown += 1
                    else:
                        new_vari = self.view.model.add_variation(board, (move,))
                        self.view.setShownBoard(new_vari[-1])
            self.keybuffer = ""
        elif keyname == "BackSpace":
            self.keybuffer = self.keybuffer[:-1] if self.keybuffer else ""

    def _genPossibleBoards(self, ply):
        possibleBoards = []
        curboard = self.view.model.getBoardAtPly(ply, self.view.shownVariationIdx)
        for lmove in lmovegen.genAllMoves(curboard.board):
            move = Move(lmove)
            board = curboard.move(move)
            possibleBoards.append(board)
        return possibleBoards