Ejemplo n.º 1
0
Archivo: Board.py Proyecto: dartato/l
def init():
    b = board()
    b[0] = [Pieces.pawn(0,x,"w",b) for x in range(12)]
    b[7] = [Pieces.pawn(7,x,"b",b) for x in range(12)]
    b[1][5] = Pieces.king(1,5,"w",b)
    b[6][6] = Pieces.king(6,6,"b",b)
    return b
Ejemplo n.º 2
0
def gen_kings(board: Board, k, bk):
    kings = {"white": Pieces.King(board, board.get_square((board.size // 2, board.size - 1)), white, k),
             "black": Pieces.King(board, board.get_square((board.size // 2, 0)), black, bk)}

    board.white_pieces.add(kings["white"])
    board.black_pieces.add(kings["black"])
    return kings
Ejemplo n.º 3
0
def pawnPromotion(flag, start_row, start_col, end_row, end_col, name_of_piece):
    attacking_list = brd.isAttacked(gc.GAME_COLOR)
    row_of_king, col_of_king = brd.findPieceOfSameColor(gc.GAME_COLOR, "King")
    if (row_of_king, col_of_king) not in attacking_list:
        brd.board[row_of_king][col_of_king].setIncheck(False)

    global pawn_with_enpassant
    color = ""
    if (flag == 0):
        if (gc.GAME_COLOR == "Black"):
            color = "White"
        else:
            color = "Black"
    else:
        color = gc.GAME_COLOR
    pawn_with_enpassant = (-1, -1)
    brd.board[start_row][start_col] = None
    if name_of_piece.lower() == "Queen".lower():
        brd.board[end_row][end_col] = Pieces.Queen(color)

    if name_of_piece.lower() == "Rook".lower():
        brd.board[end_row][end_col] = Pieces.Rook(color)

    if name_of_piece.lower() == "Bishop".lower():
        brd.board[end_row][end_col] = Pieces.Bishop(color)

    if name_of_piece.lower() == "Knight".lower():
        brd.board[end_row][end_col] = Pieces.Knight(color)

    attacking_list = brd.isAttacked(gc.GAME_COLOR)
    row_of_king, col_of_king = brd.findPieceOfSameColor(gc.GAME_COLOR, "King")
    if (row_of_king, col_of_king) not in attacking_list:
        brd.board[row_of_king][col_of_king].setIncheck(False)
Ejemplo n.º 4
0
    def return_positions(self, piece, game):
        move_able = []
        cur_row, cur_col = game.get_piece_pos(piece)
        # Refer to get_direction_of for understanding of the code statement below
        for quadrant in range(self.quadrant_corners):
            y_dir = self.get_direction_of(quadrant, self.COL_INDEX)

            if piece.get_piece_name() == Pieces.Pawn().get_piece_name():
                piece_direction = game.get_piece_directions()[
                    piece.get_color()]
                if piece_direction != y_dir:
                    continue

            elif piece.get_piece_name() == Pieces.King().get_piece_name():
                if not piece.is_moved():  # Haven't Moved
                    pass

            for distance in range(1, self.max_distance + 1):
                new_row = cur_row + distance * y_dir
                if self.is_movable(game, piece, new_row, cur_col):
                    # Will King be threaten
                    move_able.append([new_row, cur_col])
                    if game.get_space(*move_able[-1]):
                        break
                else:
                    break
        return move_able
Ejemplo n.º 5
0
 def __init__(self, name, initialPosition, blockSize):
     self.position = initialPosition
     self.positionModifier = 20
     self.orientation = 0  # Initial piece orientation in the piece dictionary
     self.name = Pieces.nameCheck(name)
     self.blocks = Pieces.getBlocks(self.name, initialPosition, self.positionModifier)
     self.blockArrangements = Pieces.positionDictionary.get(self.name)
Ejemplo n.º 6
0
    def move(self, event):
        a = self.Board._offset_x
        b = self.Board._offset_y
        l = self.Board.l
        x = (event.x - a + l/2) / l#将像素坐标转化为棋盘坐标
        y = (event.y - b + l/2) / l

        if x < 0 or y < 0 or x > 8 or y > 9:#点击位置超出棋盘,退出该函数
            return
        if not self.choose and self.Board.state[x, y][0] != -1 and ((self.Board.chess[self.Board.state[x, y][0]].kind>6 and self.xing_qi) or (self.Board.chess[self.Board.state[x, y][0]].kind<7 and not self.xing_qi)):#无选中的棋子时选中点击位置的棋子
            if self.choosed_chess:
                self.choosed_chess.not_choose()
            self.choosed_chess = self.Board.chess[self.Board.state[x, y][0]]#选中棋子
            self.choosed_chess.choose()
            self.choose = True
            return
        if self.choose and (self.choosed_chess.No != self.Board.state[x, y][0]):#有选中的棋子,并且再次点击位置与棋子位置不同
            if self.Board.state[x, y][0] != -1:#再次点击的位置有棋子
                another_chess = self.Board.chess[self.Board.state[x, y][0]]
                if (another_chess.kind > 6 and self.choosed_chess.kind > 6) or \
                (another_chess.kind < 7 and self.choosed_chess.kind <7):#棋子属于同一方,选中该棋子
                    self.choosed_chess.not_choose()
                    self.choosed_chess = another_chess
                    self.choosed_chess.choose()
                    return
                else:#棋子不属于同一方
                    if Pieces.right_move(self.Board, self.choosed_chess, x, y):#符合走动规则
                        self.che_record.qi_pu(self.listbox, self.Board, self.choosed_chess,x,y)#棋谱编辑
                        another_chess.canvas.delete(another_chess.oval)#删除该棋子,即吃子
                        another_chess.canvas.delete(another_chess.word)
                        another_chess.x = -1
                        another_chess.y = -1
    
                        self.choosed_chess.canvas.move(self.choosed_chess.oval,(x-self.choosed_chess.x)*self.choosed_chess.l,(y-self.choosed_chess.y)*self.choosed_chess.l)#移动选中的棋子
                        self.choosed_chess.canvas.move(self.choosed_chess.word,(x-self.choosed_chess.x)*self.choosed_chess.l,(y-self.choosed_chess.y)*self.choosed_chess.l)
                        self.Board.state[self.choosed_chess.x, self.choosed_chess.y] = [-1, -1]
                        self.choosed_chess.x = x
                        self.choosed_chess.y = y
                        self.Board.state[x, y] = [self.choosed_chess.No, self.choosed_chess.kind]
                        self.choose = not self.choose#移动后取消对该棋子的选中
                        self.xing_qi = not self.xing_qi
                        self.test_gameover()
                        return
            if self.Board.state[x, y][1] == -1 and Pieces.right_move(self.Board, self.choosed_chess, x, y):#选中位置无棋子,并且符合走动规则
                self.che_record.qi_pu(self.listbox, self.Board, self.choosed_chess,x,y)#棋谱编辑
    
                self.choosed_chess.canvas.move(self.choosed_chess.oval,(x-self.choosed_chess.x)*self.choosed_chess.l,(y-self.choosed_chess.y)*self.choosed_chess.l)#移动选中的棋子
                self.choosed_chess.canvas.move(self.choosed_chess.word,(x-self.choosed_chess.x)*self.choosed_chess.l,(y-self.choosed_chess.y)*self.choosed_chess.l)
                self.Board.state[self.choosed_chess.x, self.choosed_chess.y] = [-1, -1]
                self.choosed_chess.x = x
                self.choosed_chess.y = y
                self.Board.state[x, y] = [self.choosed_chess.No, self.choosed_chess.kind]
                self.choose = not self.choose#移动后取消对该棋子的选中
                self.choosed_chess.not_choose()
                self.choosed_chess.choose()
                self.xing_qi = not self.xing_qi
                return
        if self.choose and self.choosed_chess.No == self.Board.state[x, y][0]:
            self.choose = not self.choose#再次点击该棋子取消选中
            self.choosed_chess.not_choose()
Ejemplo n.º 7
0
    def place_piece_event(self, event):

        pos_x, pos_y = event.pos
        
        x, y = self.screen_to_coord(pos_x, pos_y)
        colour = self.board.player
                    
        new_event = pygame.event.wait()

        if new_event.type == pygame.KEYDOWN:
            key   = new_event.key
            piece = None

            if key == ord("a"):
                piece = Pieces.Ant(colour)

            elif key == ord("q"):
                piece = Pieces.Queen(colour)

            elif key == ord("b"):
                piece = Pieces.Beetle(colour)

            elif key == ord("g"):
                piece = Pieces.Grasshopper(colour)

            elif key == ord("s"):
                piece = Pieces.Spider(colour)
                        
            if piece:
                Moves.place_piece(self.board, x, y, piece)
                self.render_step()
Ejemplo n.º 8
0
def gen_bishops(board: Board, size, i, wh, wk, bh, bk):
    board.white_pieces.add(Pieces.Bishop(
        board, board.get_square((i, size.y - 1)), white, wh, wk))
    board.white_pieces.add(Pieces.Bishop(board, board.get_square(
        (size.size - i - 1, size.y - 1)), white, wh, wk))

    board.black_pieces.add(Pieces.Bishop(
        board, board.get_square((i, 0)), black, bh, bk))
    board.black_pieces.add(Pieces.Bishop(
        board, board.get_square((size.size - i - 1, 0)), black, bh, bk))
Ejemplo n.º 9
0
def gen_knights(board: Board, size, i, wd, wh, bd, bh):
    board.white_pieces.add(Pieces.Knight(
        board, board.get_square((i, size.y - 1)), white, wd, wh))
    board.white_pieces.add(Pieces.Knight(board, board.get_square(
        (size.size - i - 1, size.y - 1)), white, wd, wh))

    board.black_pieces.add(Pieces.Knight(
        board, board.get_square((i, 0)), black, bd, bh))
    board.black_pieces.add(Pieces.Knight(
        board, board.get_square((size.size - i - 1, 0)), black, bd, bh))
Ejemplo n.º 10
0
def gen_rooks(board: Board, size, i, wd: bool = None, wk: bool = None, bd: bool = None, bk: bool = None):
    board.white_pieces.add(Pieces.Rook(
        board, board.get_square((i, size.y - 1)), white, wd, wk))
    board.white_pieces.add(Pieces.Rook(board, board.get_square(
        (size.size - i - 1, size.y - 1)), white, wd, wk))

    board.black_pieces.add(Pieces.Rook(
        board, board.get_square((i, 0)), black, bd, bk))
    board.black_pieces.add(Pieces.Rook(
        board, board.get_square((size.size - i - 1, 0)), black, bd, bk))
Ejemplo n.º 11
0
    def attack(self, pieces, left):
        new_location = None
        self.initial_move = False

        if Pieces.location_is_empty(pieces,
                                    new_location) or Pieces.protecting_king(
                                        pieces, self.location):
            return False
        for x in pieces:
            if x.location == new_location: pieces.remove(x)
        self.location[0] = new_location[0]
        self.locatoin[1] = new_location[1]
        return True
Ejemplo n.º 12
0
def set_check(state):
    enemyKingId = 0

    if (state.turn == P.WHITE):
        enemyKingId = state.blackKingId
    elif (state.turn == P.BLACK):
        enemyKingId = state.whiteKingId

    enemyKing, enemyKingSpace = P.searchForPiece(enemyKingId, state.board)
    if (state.turn == P.WHITE
            and enemyKingSpace in P.getValidMoves(P.WHITE, state)):
        state.blackChecked = True
    elif (state.turn == P.BLACK
          and enemyKingSpace in P.getValidMoves(P.BLACK, state)):
        state.whiteChecked = True
Ejemplo n.º 13
0
def startGame(screen, board=board, size=size):
    drawBoard(size, board, screen)
    #create and draw pieces in place
    plist = []  #piece list
    for i in range(0, board):
        plist.append(Pieces((i, 0), "CPU", board))
        plist[-1].draw(screen, size, board)
    for i2 in range(0, board):
        plist.append(Pieces((i2, board - 1), "player", board))
        plist[-1].draw(screen, size, board)
    # Text at the bottom
    write("Select the Piece you want to move", 0, size, screen)
    pygame.display.update()

    return plist
Ejemplo n.º 14
0
    def return_positions(self, piece, game):
        move_able = []
        rooks = []
        if piece.moved:
            return move_able
        piece_pos = game.get_piece_pos(piece)
        # Col : 0 Index and Board Size - 1 Index for Rooks
        for col in [0, game.get_board_size() - 1]:
            other_piece = game.get_space(piece_pos[self.ROW_INDEX], col)
            if other_piece and other_piece.get_piece_name() == Pieces.Rook(
            ).get_piece_name():
                # Has rook moved and check for matching colors
                rooks.append(other_piece)
        for rook in rooks:
            rook_patterns = game.get_pattern_and_moves(rook)
            spaces_between = []
            for pattern in rook_patterns:
                for move in rook_patterns[pattern]:
                    if move[self.ROW_INDEX] == piece_pos[self.ROW_INDEX]:
                        spaces_between.append(move)
                for move in spaces_between:
                    if move:  # Check if move would be through check
                        break
                else:  # Not through check
                    pass

            if len(spaces_between) + 1 == abs(
                    piece_pos[self.COL_INDEX] -
                    game.get_piece_pos(rook)[self.COL_INDEX]):
                print("True")
            else:
                print("False")
        # Return king's directions if can move
        return move_able
Ejemplo n.º 15
0
class Square:
    color = None
    piece = None
    pr = Pieces.PeiceMkr()

    def __init__(self):
        self.color = None

    def setColor(self, nm):
        self.color = nm

    def getColor(self):
        return self.color

    def getName(self):
        temp = ""
        if self.piece != None:
            temp = self.piece.getName()
        return temp

    def mkrPiece(self, p, team, colour, no):
        self.piece = self.pr.createPiece(p, team, colour, no)

    def setPiece(self, pi):
        self.piece = None
        self.piece = pi

    def getPiece(self):
        return self.piece
Ejemplo n.º 16
0
    def __init__(self, piece_positions=range(8), pawn_positions=range(8)):
        self.sideboard, self.passant_loc = [], tuple()
        self.player_turn, self.turn_count, self.draw_count, self.passant_count = 'White', 1.0, 0, 0.0
        self.checkmate, self.active_player_in_check, self.draw = False, False, False
        colour_generator = Utils.white_black()

        # Generate empty board
        self.squares = [[Pieces.Empty(next(colour_generator), location=(row, col)) for col in range(8)] for row in range(8)]

        # instantiate pieces
        for col in piece_positions:
            type_ = Globals.BACK_LINE[col]
            self.squares[0][col] = eval('Pieces.'+type_)('Black', self, (0, col))
            self.squares[7][col] = eval('Pieces.'+type_)('White', self, (7, col))
        for col in pawn_positions:
            self.squares[1][col] = Pieces.Pawn('Black', self, (1, col))
            self.squares[6][col] = Pieces.Pawn('White', self, (6, col))

        # initialise pieces
        self.update_pieces()
Ejemplo n.º 17
0
    def move(self, pieces, inputLocation, twice=False):
        if inputLocation is not (self.location[0], self.location[1] - 1):
            return False
        elif inputLocation is not (self.location[0], self.location[1] - 2):
            return False
        print("do we get here")
        new_location = None

        if (twice is True) and (self.initial_move is False): return False
        if (twice is True) and (self.initial_move is True):
            new_location = (self.location[0], self.location[1] - 2)
        else:
            new_location = (self.location[0], self.location[1] - 1)

        if not Pieces.location_is_empty(pieces, new_location): return False
        if Pieces.protecting_king(pieces, self.location): return False
        self.initial_move = False

        self.location = new_location
        return True
Ejemplo n.º 18
0
def undo(state, movesBack):
    st = state.copy()

    st.board = st.getAndRemoveLastState(movesBack)

    #Moving back by an odd number means we're moving to a state that was during another player's turn
    if movesBack % 2 == 1:
        st.turn = P.swapTurn(st.turn)

    set_check(st)

    return st
Ejemplo n.º 19
0
 def initialize_game(self):
     for i in range(2):
         if i == 0:
             self.teams.append(Pieces.set_of_pieces("White"))
         else:
             self.teams.append(Pieces.set_of_pieces("Black"))
         #Piece position starts the same for each game
     #self.get_board_raw()
     #self.check_state_change()
     for team in self.teams:
         for piece in team.list_of_pieces:
             self.current_board_pieces[piece.current_pos] = piece
     for i in range(64):
         if self.current_board_pieces[i].__class__ == Pieces.board_piece:
             self.raw_input_state[i] = b'1'
     #Update Arduino byte state
     self.update_Arduino(self.current_board_pieces, "pieces")
     #####Needs Work
     #if (self.alive_piece_off_board == None):
     #    self.set_reset_state(self.current_byte_state)
     self.update_map()
Ejemplo n.º 20
0
 def init_board(self):
     piece_dict = {
         "P":
         lambda row, col, board, color: p.Pawn(row, col, board, color, self.
                                               special_move_mem),
         "N":
         lambda row, col, board, color: p.Knight(row, col, board, color),
         "B":
         lambda row, col, board, color: p.Bishop(row, col, board, color),
         "Q":
         lambda row, col, board, color: p.Queen(row, col, board, color),
         "K":
         lambda row, col, board, color: p.King(row, col, board, color),
         "R":
         lambda row, col, board, color: p.Rook(row, col, board, color),
     }
     for row in range(0, 8):
         for col in range(0, 8):
             piece = self.string_board[row][col]
             if piece != "..":
                 piece_color = piece[0]
                 if piece_color == 'b':
                     piece_color = "black"
                 else:
                     piece_color = "white"
                 piece_type = piece[1]
                 self.string_board[row][col] = piece_dict[piece_type](
                     row, col, self.string_board, piece_color)
                 if piece_color == "black":
                     self.black_playable_pieces.append(
                         self.string_board[row][col])
                 else:
                     self.white_playable_pieces.append(
                         self.string_board[row][col])
     return self.string_board
Ejemplo n.º 21
0
 def is_movable(self, board, piece, new_row, new_col):
     space = board.get_space(new_row, new_col)
     piece_type = piece.get_piece_name()
     if not board.is_on_board(new_row, new_col):
         return False
     elif space and space.get_color() == piece.get_color(
     ):  # Runs into same colored piece
         return False
     elif Pieces.Pawn().get_piece_name() == piece_type:
         return self.is_valid_pawn_move(board, piece, new_row, new_col,
                                        self)
     # Other
     return True
Ejemplo n.º 22
0
	def getValidMoves(self, board, piece, colour, enforceCaptures=True):
		moves = []
		fr = piece
                # First, we get a (strictly optimistic) list of plausible places this piece could move to,
                # ignoring line of sight and promotions.
                # This is faster than checking validity of all possible moves.
                destList = board.pieces[fr[0]*8+fr[1]].getPlausibleMoves(fr)
                for to in destList:
			m = Move.Move(fr, to)
			try:
				self.validate( m, board, colour, enforceCaptures )
				moves.append( m )
			except RulesViolation as e:
				pass
                # Now consider promotion moves
		promotionPieces = [Pieces.Queen(colour), Pieces.Rook(colour), Pieces.Knight(colour), Pieces.Bishop(colour), Pieces.King(colour)]
                if isinstance(board.pieces[fr[0]*8+fr[1]], Pieces.Pawn):
                        row = fr[0]
                        if colour==0 and row==1:
                                for col in [fr[1]-1, fr[1], fr[1]+1]:
                                        to = [0, col]
                                        for pp in promotionPieces:
				                m = Move.PromotionMove(fr, to, pp)
				                try:
				                	self.validate( m, board, colour, enforceCaptures )
				                	moves.append( m )
				                except RulesViolation as e:
				                	pass
                        elif colour==1 and row==6:
                                for col in [fr[1]-1, fr[1], fr[1]+1]:
                                        to = [7, col]
                                        for pp in promotionPieces:
				                m = Move.PromotionMove(fr, to, pp)
				                try:
				                	self.validate( m, board, colour, enforceCaptures )
				                	moves.append( m )
				                except RulesViolation as e:
				                	pass
		return moves
Ejemplo n.º 23
0
 def fromNotation(m, colour):
     try:
         mm = [m[0:2], m[2:4]]  # e.g. e2e4
         fr = [0, 0]
         to = [0, 0]
         conv = dict(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7)
         fr[1] = conv[mm[0][0]]
         fr[0] = 7 - (int(mm[0][1]) - 1)
         to[1] = conv[mm[1][0]]
         to[0] = 7 - (int(mm[1][1]) - 1)
         # Promotion?
         promotionDict = dict(Q=Pieces.Queen(colour),
                              R=Pieces.Rook(colour),
                              N=Pieces.Knight(colour),
                              B=Pieces.Bishop(colour),
                              K=Pieces.King(colour))
         if len(m) > 4:
             return PromotionMove(fr, to, promotionDict[m[4]])
         else:
             return Move(fr, to)
     except Exception as e:
         print e
         raise
Ejemplo n.º 24
0
    def create_pieces(self):
        # Kings
        self.pieces['white'].append(Pieces.King(True, (4, 0)))
        self.pieces['black'].append(Pieces.King(False, (4, 7)))

        # Pawns
        for x in range(8):
            self.pieces['white'].append(Pieces.Pawn(True, (x, 1)))
            #self.pieces['black'].append(Pieces.Pawn(False, (x, 6)))

        # White Pieces
        # TODO: Move List
        # TODO: Win Screen
        # TODO: Resign and draw
        # TODO: Clock
        #self.pieces['white'].append(Pieces.Knight(True, (1, 0)))
        #self.pieces['white'].append(Pieces.Knight(True, (6, 0)))
        #self.pieces['white'].append(Pieces.Bishop(True, (2, 0)))
        self.pieces['white'].append(Pieces.Bishop(True, (5, 0)))
        self.pieces['white'].append(Pieces.Rook(True, (0, 0)))
        #self.pieces['white'].append(Pieces.Rook(True, (7, 0)))
        self.pieces['white'].append(Pieces.Queen(True, (3, 0)))

        # Black Pieces
        #self.pieces['black'].append(Pieces.Knight(False, (1, 7)))
        #self.pieces['black'].append(Pieces.Knight(False, (6, 7)))
        #self.pieces['black'].append(Pieces.Bishop(False, (2, 7)))
        self.pieces['black'].append(Pieces.Bishop(False, (5, 7)))
        #self.pieces['black'].append(Pieces.Rook(False, (0, 7)))
        self.pieces['black'].append(Pieces.Rook(False, (7, 7)))
        self.pieces['black'].append(Pieces.Queen(False, (3, 7)))

        # TODO: Move this to end of turn
        # Show pieces
        for x in self.pieces['white']:
            self.pieces_grid[x.pos] = x
            self.labels[x.pos[0]][x.pos[1]].config(text=' ' + x.display + ' ',
                                                   fg='silver')
        for x in self.pieces['black']:
            self.pieces_grid[x.pos] = x
            self.labels[x.pos[0]][x.pos[1]].config(text=' ' + x.display + ' ',
                                                   fg='brown')
Ejemplo n.º 25
0
 def retractMove(self):
     if len(self.movesMade) == 0:
         return
     [move, piece] = self.movesMade.pop()
     fr, to = move.unpack()
     self.pieces[fr] = self.pieces[to]
     # Put captured piece back in the correct place in case of en passant
     if self.madeEnPassant[-1]:
         capturedPieceCol = move.to[1]
         # Offset is -1 for black, +1 for white
         if self.pieces[fr].colour == self.WHITE:
             offset = +1
         else:
             offset = -1
         capturedPieceRow = move.to[0] + offset
         self.pieces[capturedPieceRow * 8 +
                     capturedPieceCol] = Pieces.Pawn(1 -
                                                     self.pieces[fr].colour)
     else:
         self.pieces[to] = piece
     if isinstance(move, Move.PromotionMove):
         self.pieces[fr] = Pieces.Pawn(self.pieces[fr].colour)
     self.doublePawnPush.pop()
     self.madeEnPassant.pop()
Ejemplo n.º 26
0
 def movePiece(self, board, selected, row, col):
     self.curRow = row
     self.curCol = col
     self.prevRow = selected.row
     self.prevCol = selected.col
     board.table[self.prevRow][self.prevCol].occupiedBy = None
     board.table[row][col].occupiedBy = selected
     selected.row = row
     selected.col = col
     if type(selected) == type(Pieces.pawn(None, None, None)):
         selected.firstMove = False
     if self.turn == 'W':
         self.players[0].setPrevCircle(
             self.prevRow, self.prevCol, self.curRow, self.curCol)
     else:
         self.players[1].setPrevCircle(
             self.prevRow, self.prevCol, self.curRow, self.curCol)
     print("moved ", selected, 'to : ', row, ',', col)
Ejemplo n.º 27
0
def ABNegPruning (node, alpha, beta, bestMoveLst, nullMV = True):
    node.alpha = alpha
    node.beta = beta
    nextMove = None


    if node.depth == node.depthLim:
        return node.weight, nextMove
    # Checking in null move is possible (No check, can't chain, needs not to be the 0 move, no zugzwang)
    
    elif (nullMV and node.depth < node.depthLim - 2 and node.depth != 0 and checkZugzwang(node) is False):
        if (node.state.turn == P.WHITE and node.state.whiteChecked is False) or (
            node.state.turn == P.BLACK and node.state.blackChecked is False):
               
            # Copying the node and make a null move plus lower the depthLimit by R (2)
            copyNode = node.copy()
            copyNode.depthLim = node.depthLim - 2
            copyNode.state.turn = P.swapTurn(copyNode.state.turn)
            copyNode.depth += 1
            tempVal = 0
            if (beta == math.inf):
                tempVal, jnkState = ABNegPruning(node, -(1000001), -(1000000), bestMoveLst, False)
            else:
                tempVal, jnkState = ABNegPruning(node, -(beta), -(beta+1), bestMoveLst,  False)

            #print (tempVal, "beta:", beta)
            # if someNum is >= beta the return beta
            if tempVal >= beta:
                #print("I just Null Pruned! on beta")
                return beta, nextMove 
    
    node.genNextMoves()
    if len(node.nextMoves) == 0:
        return endStateCheck(node, nextMove)
    else:
        for n in node.nextMoves:
            score, jnkState = ABNegPruning(n, -node.beta, -node.alpha, bestMoveLst, nullMV)
            if score > node.alpha:
                if score >= node.beta:
                    break
                node.alpha = score
                nextMove = n
        return node.alpha, nextMove
Ejemplo n.º 28
0
def aiSearch(state, depthLim, heuristic):
    global maxNodeDepth
    global totalNodes
    global prevMove
    
    startTime = time.perf_counter()
    
    tempNode = Node(state.turn, state, 0, depthLim, heuristic) 
    # Best move list to be used in future move ordering
    bestMoveLst = [tempNode]
    
    # Irerative deepening negamax search with AB pruning
    if heuristic == NEGMAX or heuristic == NEGMAX_POS:
        for i in range(1, depthLim + 1):
            tempNode.depthLim = i
            value, node = ABNegPruning(tempNode, -math.inf, math.inf, bestMoveLst)
            bestMoveLst.append(node.state)
            #print("Current best move:", node.state, "\nCurrent best score:", value, "\nTotal Nodes:", totalNodes)
    # Min-Max search with AB pruning
    else:
        value, node = ABPruning(tempNode, -math.inf, math.inf)
        print(value)
    
    endTime = time.perf_counter()
    
    print("Turn:", P.colorToStr(state.turn))
    print("Calculation Time:", endTime - startTime, "seconds")
    print("Max Node Depth:", maxNodeDepth)
    print("Total Nodes:", totalNodes)
    print()
    
    maxNodeDepth = 0
    totalNodes = 0
    
    if (isinstance(node, Node)):
        prevMove = node.move
    
    return node, endTime - startTime
Ejemplo n.º 29
0
    def check(self, event):
        if event:
            opp = self.game.PM.get_next_player()
            pieces_opp = opp.get_pieces()
            user = self.game.PM.get_current_player()
            pieces_user = user.get_pieces()
            user_king = [p for p in pieces_user if p.get_piece_name() == Piece.King().get_piece_name() and p.get_color() == user.get_color()]
            king_location = self.game.get_piece_pos(*user_king)
            movable = []
            for p in pieces_opp:
                try:
                    for pat in p.patterns:
                        movable += pat.return_positions(p, self.game)
                except TypeError:
                    try:
                        movable += p.patterns.return_positions(p, self.game)
                    except AttributeError as e:
                        print(e)

            movable = sorted(list(set(map(tuple, movable))))
            print(movable)
            print(king_location)
            print(king_location in movable)
Ejemplo n.º 30
0
 def return_positions(self, piece, game):
     move_able = []
     cur_row, cur_col = game.get_piece_pos(piece)
     # Refer to get_direction_of for understanding of the code statement below
     for quadrant in range(self.quadrant_corners):
         row_dir, col_dir = self.get_direction_of(
             quadrant,
             self.ROW_INDEX), self.get_direction_of(quadrant,
                                                    self.COL_INDEX)
         for distance in range(1, self.max_distance + 1):
             new_row, new_col = cur_row + distance * col_dir, cur_col + distance * row_dir
             if self.is_movable(game, piece, new_row, new_col):
                 # Will King be threaten
                 if piece.get_piece_name() == Pieces.Pawn().get_piece_name(
                 ):
                     if not self.is_valid_pawn_move(game, piece, new_row,
                                                    new_col, self):
                         break
                 move_able.append([new_row, new_col])
                 if game.get_space(*move_able[-1]):
                     break
             else:
                 break
     return move_able
Ejemplo n.º 31
0
def runThroughQueue():

    global timeDelta, theEventQueue, theClock
    global idealX, idealY, boardWidth, boardHeight
    global theBoard, thePiece, thePieceColor
    global theScore, theMultiplyer

    while theEventQueue.isEmpty() == 0:
        type, info = theEventQueue.getFromQueue()
        if type == "Gamestate":
            if info == "Check For Squares":
                squareList = theBoard.findSquaresToRemove()

                if len(squareList) > 0:
                    # Squares were found, mark 'em dead.
                    # Note that by putting "Done With Blocks" on the event queue
                    #   now, it will be executed AFTER the block scores are added
                    theEventQueue.addToQueueFront("Score", "Done With Blocks")
                    for i in range(len(squareList)):
                        theEventQueue.addToQueueFront("Score", "Block Found")
                        (x, y) = squareList[i]
                        theBoard.markSquareAsDead(x, y)
            elif info == "Get New Board":
                prepareBoard()
            elif info == "Get New Piece":
                idealX = idealY = pieceX = pieceY = 0.0
                thePiece = Pieces.getPiece()
                thePieceColor = random.randint(1, 7)
            elif info == "Update Piece Position":
                updatePiecePosition(timeDelta)
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Input":
            if info == "Move Piece Down":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc <= (boardHeight - 3)):
                    if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece)  <= 0):
                        idealY += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Left":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc >= 0):
                    if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0):
                        idealX -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Right":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc <= (boardWidth - 3)):
                    if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0):
                        idealX += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Up":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc >= 0):
                    if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0):
                        idealY -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Place Piece":

                # First we get the x,y of the piece
                
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0:
                    theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor)
                    theEventQueue.addToQueueFront("Score", "Placed Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Get New Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Check For Squares")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Place")
            elif info == "Rotate Clockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateRight(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Rotate Counterclockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateLeft(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Notification":
            if info == "Can't Move":
                pass
            elif info == "Can't Place":
                pass
            elif info == "Out Of Time":
                pass
            elif info == "Piece Placed":
                pass
            elif info == "Squares Removed":
                pass
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Program":
            if info == "Help":
                help()
            elif info == "Print FPS":
                 print "FPS: %.1f" % (theClock.get_fps())
            elif info == "Quit":
                sys.exit()
            elif info == "Tick Clock":
                timeDelta = theClock.tick(60)   # Limit ourselves to 60 FPS  
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Score":
            if info == "Block Found":
                theScore = theScore + 100 * theMultiplyer
                theMultiplyer = theMultiplyer + 1
            elif info == "Done With Blocks":
                theMultiplyer = 1
            elif info == "Placed Piece":
                theScore = theScore + 5
            elif info == "Reset Score":
                theScore = 0
                theMultiplyer = 1
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Video":
            if info == "Change Culling":
                Video.changeCulling()
            elif info == "Decrease Light X":
                Video.moveLight(-0.5, 0, 0)
            elif info == "Decrease Light Y":
                Video.moveLight(0, -0.5, 0)
            elif info == "Decrease Light Z":
                Video.moveLight(0, 0, -0.5)
            elif info == "Increase Light X":
                Video.moveLight(0.5, 0, 0)
            elif info == "Increase Light Y":
                Video.moveLight(0, 0, 0.5)
            elif info == "Increase Light Z":
                Video.moveLight(0, 0, 0.5)
            elif info == "Print Light Position":
                Video.moveLight(0, 0, 0)
            elif info == "Redraw Buffer":
                draw(timeDelta)
            elif info == "Sink Blocks":
                Video.sinkEm(theBoard, timeDelta)
            elif info == "Swap Buffers":
                pygame.display.flip()
            elif info == "Toggle Lights":
                Video.toggleLights()
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        else:
            print "Event of unknown type '%s' with info '%s' disregarded." % (type, info)

    return # Done here    
def main():
    '''
    The block size is 20 x 20 pixels
    There are magic numbers everywhere, which means this is not very maintainable at the moment
    Also... wall-o-text
    '''
    # Initialize
    pygame.init()
    screenSize = (350, 400)
    screen = pygame.display.set_mode(screenSize)
    pygame.display.set_caption('Destroy all blocks! DO EEET!')
    pygame.mouse.set_visible(False)

    # Create the background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    backgroundColor = (250, 250, 250)
    background.fill(backgroundColor)

    # Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare game objects
    clock = pygame.time.Clock()
    keyHandler = KeyHandler()
    board = Board((10, 21))
    board.addTetramino(Pieces.getRandomName())

    # Text stuff
    textX = 210
    scoreY = 150
    levelY = 220
    scoreHeight = 15
    headerHeight = 25
    fontFile = 'resources/interstate-black.ttf'

    # Score
    scoreFont = pygame.font.Font(fontFile, scoreHeight)
    scoreSurface = scoreFont.render(str(board.score), 1, (25, 25, 25))
    scorePosition = (textX, scoreY)

    # Level
    levelSurface = scoreFont.render(str(board.blockSpeed), 1, (25, 25, 25))
    levelPosition = (textX, levelY)

    # Score label
    headerFont = pygame.font.Font(fontFile, headerHeight)
    scoreHeader = headerFont.render('Score:', 1, (50, 120, 200))

    # Level label
    levelHeader = headerFont.render('Level:', 1, (200, 50, 0))

    # Piece preview
    piecePreview = pygame.Surface((80, 40))
    piecePreview = piecePreview.convert()
    piecePreview.fill(backgroundColor)
    previewPositionLocal = (0, 0)
    previewPositionGlobal = (textX, 40)
    tetramino = Tetramino(Pieces.getRandomName(), previewPositionLocal, 20)
    tetramino.draw(piecePreview)

    # We need to whiteout the score and level text regions before each new rendering of it
    scoreEraser = pygame.Surface((140, scoreHeight))
    scoreEraser = scoreEraser.convert()
    scoreEraser.fill(backgroundColor)
    levelEraser = pygame.Surface((140, scoreHeight))
    levelEraser = levelEraser.convert()
    levelEraser.fill(backgroundColor)

    # Divides the board space from the information space
    divider = pygame.Surface((5, 400))
    divider = divider.convert()
    divider.fill((125, 125, 125))

    # Blit All the Things!
    background.blit(divider, (200, 0))
    background.blit(scoreHeader, (textX, scoreY - 30))
    background.blit(scoreEraser, scorePosition)
    background.blit(levelHeader, (textX, levelY - 30))
    background.blit(levelEraser, levelPosition)
    background.blit(scoreSurface, scorePosition)
    background.blit(levelSurface, levelPosition)
    background.blit(piecePreview, (textX, 40))
    pygame.display.flip()

    cooldownCounter = 0
    cooldownMax = 30
    lineClearCounter = 0
    lineClearDelay = 10
    collision = False
    gameOver = False
    mainLoopRun = True
    exitProgram = False

    # Main Loop
    while mainLoopRun:
        clock.tick(60)

        # Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                mainLoopRun = False
                exitProgram = True

        # Quick exit for ESC key
        if pygame.key.get_pressed()[pygame.K_ESCAPE]:
            mainLoopRun = False
            exitProgram = True

        # Delay between collisions (and line clears) and the next piece getting loaded
        if collision:
            if lineClearCounter >= lineClearDelay:
                lineClearCounter = 0
                collision = False
                gameOver = board.addTetramino(tetramino.name)
                tetramino = Tetramino(Pieces.getRandomName(), previewPositionLocal, 20)
                piecePreview.fill(backgroundColor)  # erase it before getting the next one
                tetramino.draw(piecePreview)
            else:
                lineClearCounter += 1

        # Move things based on current state
        if not gameOver and not collision:
            # Hard Drop
            if pygame.key.get_pressed()[pygame.K_SPACE]:
                board.hardDrop()
                collision = True
            else:
                keyHandler.handleKeys(pygame.key.get_pressed(), board)
                collision = board.drop()

        # Close game if it ended after a period of time
        if cooldownCounter >= cooldownMax:
            mainLoopRun = False

        if gameOver:
            cooldownCounter += 1

        # Draw everything
        scoreSurface = scoreFont.render(str(board.score), 1, (25, 25, 25))
        levelSurface = scoreFont.render(str(board.blockSpeed), 1, (25, 25, 25))
        background.blit(scoreEraser, scorePosition)
        background.blit(scoreSurface, scorePosition)
        background.blit(levelEraser, levelPosition)
        background.blit(levelSurface, levelPosition)
        background.blit(piecePreview, previewPositionGlobal)
        screen.blit(background, (0, 0))
        board.draw(screen)
        pygame.display.flip()

    # Game over
    endGameSurface = pygame.Surface(screenSize, pygame.SRCALPHA)
    endGameSurface.fill((125, 125, 125, 100))
    gameOverText = headerFont.render('GAME OVER', 1, (0, 0, 0))
    endGameSurface.blit(gameOverText, (100, 175))
    screen.blit(endGameSurface, (0, 0))
    pygame.display.flip()

    # Wait for user to exit the program
    while not exitProgram:
        for event in pygame.event.get():
            if event.type == QUIT:
                exitProgram = True
        if pygame.key.get_pressed()[pygame.K_ESCAPE]:
            exitProgram = True
    pygame.quit()
Ejemplo n.º 33
0
                moves2.remove(move2)
                found = True
                break
        
        if not found:
            break
    
    return len(moves2) == 0

board = B.Board(True)


"""------------PAWN TESTS----------"""

pawnStart = deepcopy(board)
pawnStart.board[1][1] = P.Pawn(0, P.WHITE)

pawnStartBlocked1 = deepcopy(pawnStart)
pawnStartBlocked1.board[1][2] = P.Pawn(1, P.BLACK)
pawnStartBlocked1.unmoved.remove(1)

pawnStartBlocked2 = deepcopy(pawnStart)
pawnStartBlocked2.board[1][3] = P.Pawn(1, P.BLACK)
pawnStartBlocked2.unmoved.remove(1)

pawnCaptureAndPassent = deepcopy(board)
pawnCaptureAndPassent.board[4][4] = P.Pawn(0, P.WHITE)
pawnCaptureAndPassent.board[3][4] = P.Pawn(1, P.BLACK)
pawnCaptureAndPassent.board[5][5] = P.Pawn(2, P.BLACK)
pawnCaptureAndPassent.passentable = (3, 4)
pawnCaptureAndPassent.unmoved.remove(0)
Ejemplo n.º 34
0
def runThroughQueue():

    global timeDelta, theEventQueue, theClock
    global idealX, idealY, boardWidth, boardHeight
    global theBoard, thePiece, thePieceColor
    global theScore, theMultiplyer, gameTime, countFrom
    global theHighScore, highScoreHasChanged

    while theEventQueue.isEmpty() == 0:
        type, info, tuple = theEventQueue.getFromQueue()
        if type == "Gamestate":
            if info == "Check For Squares":
                squareList = theBoard.findSquaresToRemove()

                if len(squareList) > 0:
                    # Squares were found, mark 'em dead.
                    # Note that by putting "Done With Blocks" on the event queue
                    #   now, it will be executed AFTER the block scores are added
                    for i in range(len(squareList)):
                        dataTuple = (i + 1) * 100
                        theEventQueue.addToQueueFront("Score", "Block Found",
                                                      dataTuple)
                        (x, y) = squareList[i]
                        theBoard.markSquareAsDead(x, y)
            elif info == "Get New Board":
                prepareBoard()
            elif info == "Get New Piece":
                idealX = idealY = pieceX = pieceY = 0.0
                thePiece = Pieces.getPiece()
                thePieceColor = random.randint(1, 7)
            elif info == "Out of Time":
                theEventQueue.addToQueueFront("Input", "Place Piece", "Forced")
            elif info == "Update Piece Position":
                updatePiecePosition(timeDelta)
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Input":
            if info == "Move Piece Down":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc <= (boardHeight - 3)):
                    if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece) <=
                            0):
                        idealY += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification",
                                                      "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Left":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc >= 0):
                    if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <=
                            0):
                        idealX -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification",
                                                      "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Right":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc <= (boardWidth - 3)):
                    if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <=
                            0):
                        idealX += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification",
                                                      "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Up":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc >= 0):
                    if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <=
                            0):
                        idealY -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification",
                                                      "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Place Piece":

                # First we get the x,y of the piece

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0:
                    countFrom = gameTime  # Resets the countdown, move to event?
                    theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor)
                    theEventQueue.addToQueueFront("Score", "Placed Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Get New Piece")
                    theEventQueue.addToQueueFront("Gamestate",
                                                  "Check For Squares")
                else:
                    if tuple == "Forced":
                        theEventQueue.addToQueueFront("Gamestate", "Game Over")
                        theEventQueue.addToQueueFront("Notification",
                                                      "Game Over")
                    else:
                        theEventQueue.addToQueueFront("Notification",
                                                      "Can't Place")
            elif info == "Rotate Clockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateRight(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Rotate Counterclockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateLeft(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Notification":
            if info == "Can't Move":
                pass
            elif info == "Can't Place":
                pass
            elif info == "Game Over":
                pass
            elif info == "Got High Score":
                pass
            elif info == "Out Of Time":
                pass
            elif info == "Piece Placed":
                pass
            elif info == "Squares Removed":
                pass
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Program":
            if info == "Game Over":
                # Game over stuff goes here
                pass
            elif info == "Get Highscore":
                getTheHighScore()
                highScoreHasChanged = False
            elif info == "Help":
                help()
            elif info == "Print FPS":
                print "FPS: %.1f" % (theClock.get_fps())
            elif info == "Quit":
                sys.exit()
            elif info == "Save Highscore":
                if highScoreHasChanged:
                    saveTheHighScore()
            elif info == "Tick Clock":
                timeDelta = theClock.tick(60)  # Limit ourselves to 60 FPS
                gameTime = gameTime + timeDelta
                if abs(gameTime - countFrom) > 10000:
                    countFrom = gameTime
                    theEventQueue.addToQueueFront("Gamestate", "Out of Time")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Score":
            if info == "Add To Score":
                oldScore = theScore

                theScore = theScore + tuple

                if (theScore > theHighScore):
                    if (oldScore < theHighScore):
                        highScoreHasChanged = True
                        theEventQueue.addToQueueFront("Notification",
                                                      "Got High Score")
                    theHighScore = theScore
            elif info == "Block Found":
                if tuple == None:
                    theEventQueue.addToQueueFront("Score", "Add To Score",
                                                  100 * theMultiplyer)
                else:
                    theEventQueue.addToQueueFront("Score", "Add To Score",
                                                  tuple * theMultiplyer)
            elif info == "Placed Piece":
                theEventQueue.addToQueueFront("Score", "Add To Score", 5)
            elif info == "Reset Score":
                theScore = 0
                theMultiplyer = 1
            elif info == "Reset High Score":
                theHighScore = 0
                highScoreHasChanged = True
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Video":
            if info == "Change Culling":
                Video.changeCulling()
            elif info == "Decrease Light X":
                Video.moveLight(-0.5, 0, 0)
            elif info == "Decrease Light Y":
                Video.moveLight(0, -0.5, 0)
            elif info == "Decrease Light Z":
                Video.moveLight(0, 0, -0.5)
            elif info == "Increase Light X":
                Video.moveLight(0.5, 0, 0)
            elif info == "Increase Light Y":
                Video.moveLight(0, 0, 0.5)
            elif info == "Increase Light Z":
                Video.moveLight(0, 0, 0.5)
            elif info == "Print Light Position":
                Video.moveLight(0, 0, 0)
            elif info == "Redraw Buffer":
                draw(timeDelta)
            elif info == "Sink Blocks":
                Video.sinkEm(theBoard, timeDelta)
            elif info == "Swap Buffers":
                pygame.display.flip()
            elif info == "Toggle Lights":
                Video.toggleLights()
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        else:
            print "Event of unknown type '%s' with info '%s' disregarded." % (
                type, info)

    return  # Done here
Ejemplo n.º 35
0
def runThroughQueue():
    """Go through the queue and deal with the events in it."""

    global timeDelta, theEventQueue, theClock
    global idealX, idealY, boardWidth, boardHeight
    global theBoard, thePiece, thePieceColor
    global theScore, theMultiplyer, gameTime, countFrom
    global theHighScore, highScoreHasChanged

    while theEventQueue.isEmpty() == 0:
        type, info, tuple = theEventQueue.getFromQueue()
        if type == "Gamestate":
            if info == "Check For Squares":
                squareList = theBoard.findSquaresToRemove()

                if len(squareList) > 0:
                    # Squares were found, mark 'em dead.
                    # Note that by putting "Done With Blocks" on the event queue
                    #   now, it will be executed AFTER the block scores are added
                    for i in range(len(squareList)):
                        dataTuple = (i + 1) * 100
                        theEventQueue.addToQueueFront("Score", "Block Found", dataTuple)
                        (x, y) = squareList[i]
                        theBoard.markSquareAsDead(x, y)
            elif info == "Get New Board":
                prepareBoard()
            elif info == "Get New Piece":
                idealX = idealY = pieceX = pieceY = 0.0
                thePiece = Pieces.getPiece()
                thePieceColor = random.randint(1, 7)
            elif info == "Out of Time":
                theEventQueue.addToQueueFront("Input", "Place Piece", "Forced")
            elif info == "Update Piece Position":
                updatePiecePosition(timeDelta)
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Input":
            if info == "Move Piece Down":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc <= (boardHeight - 3)):
                    if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece)  <= 0):
                        idealY += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Left":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc >= 0):
                    if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0):
                        idealX -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Right":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc <= (boardWidth - 3)):
                    if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0):
                        idealX += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Up":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc >= 0):
                    if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0):
                        idealY -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Place Piece":

                # First we get the x,y of the piece
                
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0:
                    countFrom = gameTime    # Resets the countdown, move to event?
                    theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor)
                    theEventQueue.addToQueueFront("Score", "Placed Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Get New Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Check For Squares")
                else:
                    if tuple == "Forced":
                        theEventQueue.addToQueueFront("Program", "Game Over")
                        theEventQueue.addToQueueFront("Notification", "Game Over")
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Place")
            elif info == "Rotate Clockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateRight(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Rotate Counterclockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateLeft(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Notification":
            if info == "Can't Move":
                Sound.playSound("Bad Move")
            elif info == "Can't Place":
                Sound.playSound("Bad Place")
            elif info == "Game Over":
                Sound.playSound("Game Over")
            elif info == "Got High Score":
                Sound.playSound("Got High")
            elif info == "Out Of Time":
                Sound.playSound("Forced")
            elif info == "Piece Placed":
                Sound.playSound("Place")
            elif info == "Squares Removed":
                Sound.playSound("Removed")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Program":
            if info == "Game Over":
                # Game over stuff goes here
                # For now, just quit
                theEventQueue.addToQueueFront("Program", "Quit")
                theEventQueue.addToQueueFront("Program", "Save Highscore")
            elif info == "Get Highscore":
                getTheHighScore()
                highScoreHasChanged = False
            elif info == "Help":
                help()
            elif info == "Print FPS":
                 print "FPS: %.1f" % (theClock.get_fps())
            elif info == "Quit":
                sys.exit()
            elif info == "Save Highscore":
                if highScoreHasChanged:
                    saveTheHighScore()
            elif info == "Tick Clock":
                timeDelta = theClock.tick(60)   # Limit ourselves to 60 FPS
                gameTime = gameTime + timeDelta
                if abs(gameTime - countFrom) > 10000:
                    countFrom = gameTime
                    theEventQueue.addToQueueFront("Gamestate", "Out of Time")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Score":
            if info == "Add To Score":
                oldScore = theScore

                theScore = theScore + tuple

                if (theScore > theHighScore):
                    if (oldScore < theHighScore):
                        highScoreHasChanged = True
                        theEventQueue.addToQueueFront("Notification", "Got High Score")
                    theHighScore = theScore
            elif info == "Block Found":
                if tuple == None:
                    theEventQueue.addToQueueFront("Score", "Add To Score", 100 * theMultiplyer)
                else:
                    theEventQueue.addToQueueFront("Score", "Add To Score", tuple * theMultiplyer)
            elif info == "Placed Piece":
                theEventQueue.addToQueueFront("Score", "Add To Score", 5)
            elif info == "Reset Score":
                theScore = 0
                theMultiplyer = 1
            elif info == "Reset High Score":
                theHighScore = 0
                highScoreHasChanged = True
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Video":
            if info == "Change Culling":
                Video.changeCulling()
            elif info == "Decrease Light X":
                Video.moveLight(-0.5, 0, 0)
            elif info == "Decrease Light Y":
                Video.moveLight(0, -0.5, 0)
            elif info == "Decrease Light Z":
                Video.moveLight(0, 0, -0.5)
            elif info == "Increase Light X":
                Video.moveLight(0.5, 0, 0)
            elif info == "Increase Light Y":
                Video.moveLight(0, 0, 0.5)
            elif info == "Increase Light Z":
                Video.moveLight(0, 0, 0.5)
            elif info == "Print Light Position":
                Video.moveLight(0, 0, 0)
            elif info == "Redraw Buffer":
                draw(timeDelta)
            elif info == "Sink Blocks":
                Video.sinkEm(theBoard, timeDelta)
            elif info == "Swap Buffers":
                pygame.display.flip()
            elif info == "Toggle Lights":
                Video.toggleLights()
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        else:
            print "Event of unknown type '%s' with info '%s' disregarded." % (type, info)

    return # Done here