示例#1
0
def main():
    speed = 1
    x = 100
    clock = SDL.time.Clock()
    is_running = True

    SDL.init()

    screen = SDL.display.set_mode(size=(1000, 500), vsync=1)

    box = SDL.image.load(BOX_PATH).convert()
    background = SDL.image.load(BACKGROUND_PATH).convert()
    window_icon = SDL.image.load("icon.png")  # 32 x 32 pixels

    SDL.display.set_icon(window_icon)
    SDL.display.set_caption("Window Title")

    screen.blit(background, (0, 0))

    Button(BUTTON_PATH, (100, 300), button_action_1)
    Button(BUTTON_PATH, (300, 300), button_action_2)
    Button(BUTTON_PATH, (500, 300), button_action_3)

    Button.draw(screen)

    while is_running:
        is_running = input_handling()

        source_rect = (x, 100, 64, 64)
        screen.blit(source=background, dest=(x, 100), area=source_rect)

        x += speed

        screen.blit(box, (x, 100))

        if x >= 900 or x <= 10:
            speed *= -1

        SDL.display.update()

        # By calling Clock.tick(X) once per frame, the program will never run at more
        # than X frames per second. This function uses SDL_Delay function which is not
        # accurate on every platform, but does not use much CPU.

        clock.tick(FPS)
示例#2
0
 def __init__(self, controls):
     x, y = [50, 50]
     title = Text("Pokémon Game", fonts.title, colors.black, [x, y])
     y += title.height + 50
     search = Button("Look for Pokémon",
                     fonts.normal,
                     colors.black, [x, y],
                     True,
                     action="scene_change",
                     value="look")
     y += search.height + 5
     team = Button("My team", fonts.normal, colors.black, [x, y])
     y += team.height + 5
     exit = Button("Exit",
                   fonts.normal,
                   colors.black, [x, y],
                   action="shutdown")
     buttons = [search, team, exit]
     button_manager = ButtonManager(buttons, controls)
     super().__init__([title, button_manager])
示例#3
0
def input_handling():
    for event in SDL.event.get():
        if event.type in (SDL.QUIT, SDL.KEYDOWN):
            return False

        elif event.type == SDL.MOUSEBUTTONDOWN:
            left_button, middle_button, right_button = SDL.mouse.get_pressed()

            if left_button:
                position = SDL.mouse.get_pos()
                print("■☐☐ The left mouse button")

                Button.click(position)

            elif middle_button:
                print("☐■☐ The middle mouse button")

            elif right_button:
                print("☐☐■ The right mouse button")

    return True
示例#4
0
def run_game():
    #初始化游戏并创建屏幕对象
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("打飞机")

    #实例化飞机
    ship = Ship(screen)

    #储存子弹编组
    bullets = Group()

    #实例化外星人
    aliens = Group()
    gf.create_fleet(setting, screen, ship, aliens)

    #游戏状态
    states = GameStates(setting)

    #开始按钮
    play_bt = Button(screen, 'play')

    #记分板
    sb = ScoreBoard(setting, screen, states)
    #开始游戏主循环
    while True:
        #监视鼠标和键盘事件
        gf.check_events(setting, screen, ship, bullets, aliens, states,
                        play_bt, sb)
        if states.game_active:
            #更新飞机位置
            ship.update()
            #子弹更新
            gf.update_bullets(setting, screen, ship, aliens, bullets, states,
                              sb)
            #外星人更新
            gf.update_aliens(ship, aliens, bullets, setting, screen, states,
                             sb)
        #让最近的屏幕绘制可见
        gf.update_screen(setting, screen, ship, bullets, aliens, states,
                         play_bt, sb)
示例#5
0
def run(mode):
    # Initialize game and create a screen object
    pygame.init()
    ai_settings = Settings(mode)

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Space Invasion")

    # Make the Play button.
    play_button = Button(ai_settings, screen, "Play")

    # Create an instance to store game statistics.
    stats = GameStats(ai_settings)

    # Make a ship
    ship = Ship(ai_settings, screen)

    # Make a group to store bullets in.
    bullets = Group()

    # Make a group of aliens.
    aliens = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    game_over = False

    # Start the main loop for the game
    while not game_over:
        # Watch for the keyboard and mouse events
        gf.check_events(ai_settings, screen, stats, play_button, ship, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets,
                             mode)

        gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets,
                         play_button)
    def __init__(self, name, width, height, buttons, hands):
        self.name = name
        self.width = width
        self.height = height

        self.buttons = list()
        for button in buttons:
            self.buttons.append(Button(
                id=button['id'],
                location=button['location'],
                size=button['size']
            ))

        self.buttons = sorted(self.buttons, key=lambda button: button.id)

        self._check_buttons_overlapping()

        self.hands = list()
        for hand in hands:
            self.hands.append(Hand(fingers=hand['fingers']))
示例#7
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Inwazja OBCYCH!')

    play_button = Button(screen, ai_settings, 'Rozpocznij gre')

    stats = GameStats(ai_settings)
    ship = Ship(screen, ai_settings)
    bullets = Group()  # przechowywanie pociskow
    aliens = Group()

    gf.create_fleet(ai_settings, screen, ship, aliens)

    while True:
        gf.check_events(screen, ai_settings, stats, ship, aliens, bullets, play_button)
        gf.update_screen(screen, ai_settings, stats, ship, aliens, bullets, play_button)
        if stats.game_active:
            ship.update()
            gf.update_bullets(screen, ai_settings, ship, aliens, bullets)
            gf.update_aliens(screen, ai_settings, stats, ship, aliens, bullets)
示例#8
0
buttons = [
    # [ text, function, height ]
    ["test", printTest, fullb],
    ["Help", help, fullb],
    ["Reset", reset, fullb],
    ["size ^", increaseSize, halfb],
    ["size v", decreaseSize, halfb],
    ["flat", flat, halfb],
    ["to cube", toCube, halfb],
    ["density ^", increaseDensity, halfb]
]
buttonobj = []
buttonMargin = 2
buttonY = buttonMargin+0
for b in buttons:
    buttonobj.append(Button((buttonMargin, buttonY, TOOLBAR_WIDTH-buttonMargin*2, b[2]), b[1], b[0]))
    buttonY += b[2] + buttonMargin

# game variables
gameClock = pygame.time.Clock()
FPS = 60
FRAME = 0
MINE_DENSITY = 0.1 / 3
mouse = [0, 0]
dragSensitivity = 1/50
PI = 3.1415926535
current_layer = 0
click = False
button = -1
mousedown = False
gameover = False
示例#9
0
    -79.5, 21.8, 70.225, 80.112, 82.992, 84.15, 84.61, 84.85, 84.972, 85.027,
    85.055, 85.065, 85.07, 85.074, 85.077, 85.079, 85.08, 85.0805
]
clock = pygame.time.Clock()
running = True
pressed = False
buttons = pygame.sprite.Group()
labels = pygame.sprite.Group()

from classes.button import Button
from classes.labl import Label
from classes.map import Map

cur_map = Map()
result = Label('', 'black', 10, 60)
scheme = Button('  Схема  ', 'red', width - 50, height - 390, angle=270)
sputnik = Button('  Спутник  ', 'blue', width - 50, height - 265, angle=270)
hybrid = Button('  Гибрид  ', 'green', width - 50, height - 130, angle=270)
search = Button(
    '  Искать  ',
    'black',
    width - 90,
    5,
)
post = Button('  Почтовый индекс  ', 'black', width - 470, 50)

cancel = Button('  Сброс поискового результата  ', 'black', width - 287, 50)
text_input = text_input.TextInput(font_family='font.ttf',
                                  font_size=30,
                                  repeat_keys_initial_ms=400,
                                  repeat_keys_interval_ms=30)
示例#10
0
def initialize_background_play_pause():
    PP_INTERRUPT = Button(BUTTON_PLAYPAUSE)  # Create class
    PP_THREAD = Thread(target=PP_INTERRUPT.run)  # Create Thread
    PP_THREAD.start()  # Start Thread
示例#11
0
class Game:

    #Game class constructor
    def __init__(self,window, gamemode):
        self._init()
        self.window = window
        self.lastMove = None
        self.winner = None
        self.gamemode = gamemode
        self.button = None
        self.time = None

    #method to update the game state
    def update(self, time_elapsed):
        if time_elapsed != None:
            self.time = time_elapsed
        
        self.drawBoard()
        self.drawSideBoard()
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    #private method to initialize class attributes
    def _init(self):
        self.selected = None
        self.board = Board()
        self.player = 1
        self.valid_moves = []
        self.lastMove = None
        self.boards = {}
        self.hintSquarePiece = None
        self.hintSquareToMove = None
        self.nodes = 0

    #method to draw the game board on screen
    def drawBoard(self):
        self.window.fill((76,188,228))
        
        for row in range(ROWS):
            for col in range(COLS):
                if (col, row) == self.hintSquarePiece:
                    pygame.draw.rect(self.window, GREEN, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 0)
                else:
                    pygame.draw.rect(self.window, BLUE, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 0)

                pygame.draw.rect(self.window, BLACK, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 1)


        for row in range(ROWS):
            for col in range(COLS):
                piece = self.board.board[row][col]
                if piece != 0:
                    self.window.blit(color_dic[piece], (SQUARE_SIZE * col - 10, SQUARE_SIZE * row - 10))

    #method to draw the right side of the screen
    def drawSideBoard(self):
        if self.player == 1:
            myfont = pygame.font.SysFont('', 60)
            sideboard_title = myfont.render('BLACK TURN', True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 50))
            self.window.blit(sideboard_title, text_rect)
        elif self.player == 2:
            myfont = pygame.font.SysFont('', 60)
            sideboard_title = myfont.render('WHITE TURN', True, WHITE)
            text_rect = sideboard_title.get_rect(center=(1000, 50))
            self.window.blit(sideboard_title, text_rect)

        if self.gamemode == 1 or (self.gamemode == 2 and self.player == 1):
            self.button = Button(BLUE, 850, 150, 300, 100, 'Press for a hint')
            self.button.draw(self.window, True)
        elif self.gamemode == 3 or (self.gamemode == 2 and self.player == 2):
            self.button = Button(BLUE, 825, 150, 350, 100, 'Press for computer play')
            self.button.draw(self.window, True)
            

        if (self.gamemode == 3 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("AI move took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)
        elif (self.gamemode == 1 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("Hint calc. took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)
        elif (self.gamemode == 2 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("Calculation took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)

        if self.winner != None and self.winner != -1:
            myfont = pygame.font.SysFont('', 60)
            if self.winner == 1:
                sideboard_title = myfont.render('BLACK WINS!', True, (0,0,0))
                text_rect = sideboard_title.get_rect(center=(1000, 700))
                self.window.blit(sideboard_title, text_rect)
            elif self.winner == 2:
                sideboard_title = myfont.render('WHITE WINS!', True, (255,255,255))
                text_rect = sideboard_title.get_rect(center=(1000, 700))
                self.window.blit(sideboard_title, text_rect)
            elif self.winner == 0:
                sideboard_title = myfont.render('TIE!', True, (72,68,68))
                text_rect = sideboard_title.get_rect(center=(1000, 650))
                self.window.blit(sideboard_title, text_rect)
            
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render('Press ENTER to continue', True, (72,68,68))
            text_rect = sideboard_title.get_rect(center=(1000, 750))
            self.window.blit(sideboard_title, text_rect)

    #method to reset the game state
    def reset(self):
       self._init()

    #method to get the current player (turn)
    def getPlayer(self):
        return self.player

    #method to get the last move made
    def getLastMove(self):
        return self.lastMove

    #method to get the current board
    def getBoard(self):
        return self.board

    #method to update the last move made
    def updateLastMove(self,row,col):
        self.lastMove = row,col

    #method that shows to the player what are the possible moves for the selected piece
    def select(self,row,col):
        if self.selected:
            result = self.move(row,col)
            if not result:
                self.selected = None
                self.select(row,col)
        
        piece = self.board.get_piece(row,col)
        if piece == self.player:
            self.selected = (row,col)
            self.valid_moves = self.board.get_valid_moves(row, col)
            return True
        
        return False

    #method that moves a piece and changes turn
    def move(self,row,col):
        piece = self.board.get_piece(row,col)
        if self.selected and piece == 0 and (row,col) in self.valid_moves:
            oldRow, oldCol = self.selected
            self.board.move_piece(oldRow,oldCol, row, col)
            self.updateLastMove(row,col)
            self.change_turn()
        else:
            return False
        
        return True

    #method that executes the ai move
    def ai_move(self, row, col):
        oldRow, oldCol = self.selected
        self.board.move_piece(oldRow,oldCol, row, col)
        self.updateLastMove(row,col)
        self.change_turn()

    #method that changes the turn
    def change_turn(self):
        self.valid_moves = []
        self.player = 3 - self.player
        self.hintSquarePiece = None
        self.hintSquareToMove = None
        if self.board.board_as_string() in self.boards.keys():
            self.boards[self.board.board_as_string()] += 1
        else:
            self.boards.update({self.board.board_as_string() : 1})

    #method that draws the valid moves on the screen
    def draw_valid_moves(self,moves):
        for move in moves:
            row, col = move
            if (row, col) == self.hintSquareToMove:
                self.window.blit(GREEN_DOT,(SQUARE_SIZE*col+66,SQUARE_SIZE*row+66))
            else:
                self.window.blit(GRAY_DOT,(SQUARE_SIZE*col+66,SQUARE_SIZE*row+66))

    #method that verifies if the game is over or not
    def checkWin(self):
        if self.lastMove == None :
            return -1
        if self.boards[self.board.board_as_string()] == 3:
            self.winner = 0
            return 0   
        row, col = self.lastMove
        self.winner = self.board.threeInRow(row,col, 3-self.player)  
        return self.board.threeInRow(row,col, 3-self.player)

    #method that evaluates the score of the board on easy level
    def easyLevelHeuristics(self, row, col, player):
        if self.board.threeInRow(row, col, player) == player:
            return 1000

        else:
            return 0

    #method that evaluates the score of the board on medium level
    def mediumLevelHeuristics(self, row, col, player):
        if self.board.threeInRow(row, col, player) == player:
            return 1000

        elif self.board.twoInRow(row, col, player) == player:
            return 200

        else:
            return 0

    #method that evaluates the score of the board on hard level (best heuristic)
    def hardLevelHeuristics(self, row, col, player):
        if self.board.threeInRow(row, col, player) == player:
            return 1000

        elif self.board.twoInRow(row, col, player) == player:
            return 200

        elif self.board.twoPiecesClose(row, col, player) == player:
            return 100

        else:
            return 0


    #method that chooses the heuristic according to the level selected in the menu
    def chooseHeuristics(self, level, row, col, player):
        if level == 1:
            return self.easyLevelHeuristics(row, col, player)
        elif level == 3:
            return self.mediumLevelHeuristics(row, col, player)
        elif level == 6:
            return self.hardLevelHeuristics(row, col, player)

    #method that implements the maximum part of the minimax with alpha-beta cuts algorithm 
    def max_with_alpha_beta_cuts(self, lastRow, lastCol, maxDepth, alpha, beta, player, ordering, level):

        maxv = -2000

        depth = maxDepth - 1

        finalRow = None
        finalCol = None
        finalOldRow = None
        finalOldCol = None

        opponent = 3 - player

        result = self.chooseHeuristics(level, lastRow, lastCol, opponent)
        x = random.randint(0,9)/10

        if result == 1000:
            return (-result - depth - x, 0, 0, 0, 0)

        elif result != 1000 and depth == -1:
            return (-result - depth - x, 0, 0, 0, 0)


        if player == 1:
            pieces = deepcopy(self.board.get_black_pieces())

        else:
            pieces = deepcopy(self.board.get_white_pieces())


        for piece in pieces:
            oldRow, oldCol = piece
            possibleMoves = self.board.get_valid_moves(oldRow, oldCol)
            orderedMoves = []

            if ordering != None:
                for i in range(0, len(possibleMoves)):
                    moveRow, moveCol = possibleMoves[i]
                    self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                    evaluation = self.chooseHeuristics(level, lastRow, lastCol, player)
                    orderedMoves.append((moveRow, moveCol, evaluation))

                    self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering)

            else:               
                orderedMoves = possibleMoves


            for i in range(0,len(orderedMoves)):
                self.nodes += 1
                if ordering != None:
                    moveRow, moveCol, score = orderedMoves[i]
                else:
                    moveRow, moveCol = orderedMoves[i]

                self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                (m, min_old_row, min_old_col, min_row, min_col) = self.min_with_alpha_beta_cuts(moveRow, moveCol, depth, alpha, beta, opponent, ordering, level)

                if m > maxv:
                    maxv = m
                    finalRow = moveRow
                    finalCol = moveCol
                    finalOldRow = oldRow
                    finalOldCol = oldCol

                self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                if maxv >= beta:
                    return (maxv, finalOldRow, finalOldCol, finalRow, finalCol)

                if maxv > alpha:
                    alpha = maxv
                

        return (maxv, finalOldRow, finalOldCol, finalRow, finalCol)


    #method that implements the minimum part of the minimax with alpha-beta cuts algorithm 
    def min_with_alpha_beta_cuts(self, lastRow, lastCol, maxDepth, alpha, beta, player, ordering, level):

        minv = 2000

        finalRow = None
        finalCol = None
        finalOldRow = None
        finalOldCol = None

        depth = maxDepth - 1

        opponent = 3 - player

        result = self.chooseHeuristics(level, lastRow, lastCol, opponent)
        x = random.randint(0,9)/10

        if result == 1000:
            return (result + depth + x, 0, 0, 0, 0)

        elif result != 1000 and depth == -1:
            return (result + depth + x, 0, 0, 0, 0)


        if player == 1:
            pieces = deepcopy(self.board.get_black_pieces())

        else:
            pieces = deepcopy(self.board.get_white_pieces())


        
        for piece in pieces:
            oldRow, oldCol = piece
            possibleMoves = self.board.get_valid_moves(oldRow, oldCol)
            orderedMoves = []

            if ordering != None:
                for i in range(0, len(possibleMoves)):
                    moveRow, moveCol = possibleMoves[i]
                    self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                    evaluation = self.chooseHeuristics(level, lastRow, lastCol, player)
                    orderedMoves.append((moveRow, moveCol, evaluation))

                    self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering)

            else:               
                orderedMoves = possibleMoves

        
            for i in range(0,len(orderedMoves)):
                self.nodes += 1
                if ordering != None:
                    moveRow, moveCol, score = orderedMoves[i]
                else:
                    moveRow, moveCol = orderedMoves[i]

                self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                (m, max_old_row, max_old_col, max_row, max_col) = self.max_with_alpha_beta_cuts(moveRow, moveCol, depth, alpha, beta, opponent, ordering, level)

                if m < minv:
                    minv = m
                    finalRow = moveRow
                    finalCol = moveCol
                    finalOldRow = oldRow
                    finalOldCol = oldCol

                self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                if minv <= alpha :
                    return (minv, finalOldRow , finalOldCol ,finalRow, finalCol)

                if minv < beta:
                    beta = minv


        return (minv, finalOldRow , finalOldCol ,finalRow, finalCol)


    #method that implements the maximum part of the minimax algorithm 
    def max(self, lastRow, lastCol, maxDepth, player, ordering, level):

        maxv = -2000

        depth = maxDepth - 1

        finalRow = None
        finalCol = None
        finalOldRow = None
        finalOldCol = None

        opponent = 3 - player

        result = self.chooseHeuristics(level, lastRow, lastCol, opponent)
        x = random.randint(0,9)/10

        if result == 1000:
            return (-result - depth - x, 0, 0, 0, 0)

        elif result != 1000 and depth == -1:
            return (-result - depth - x, 0, 0, 0, 0)


        if player == 1:
            pieces = deepcopy(self.board.get_black_pieces())

        else:
            pieces = deepcopy(self.board.get_white_pieces())

        for piece in pieces:
            oldRow, oldCol = piece
            possibleMoves = self.board.get_valid_moves(oldRow, oldCol)
            orderedMoves = []

            if ordering != None:
                for i in range(0, len(possibleMoves)):
                    moveRow, moveCol = possibleMoves[i]
                    self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                    evaluation = self.chooseHeuristics(level, lastRow, lastCol, player)
                    orderedMoves.append((moveRow, moveCol, evaluation))

                    self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering)

            else:               
                orderedMoves = possibleMoves 


            for i in range(0,len(orderedMoves)):
                self.nodes += 1
                
                if ordering != None:
                    moveRow, moveCol, score = orderedMoves[i]
                else:
                    moveRow, moveCol = orderedMoves[i]

                self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                (m, min_old_row, min_old_col, min_row, min_col) = self.min(moveRow, moveCol, depth, opponent, ordering, level)

                if m > maxv:
                    maxv = m
                    finalRow = moveRow
                    finalCol = moveCol
                    finalOldRow = oldRow
                    finalOldCol = oldCol

                self.board.move_piece(moveRow,moveCol, oldRow, oldCol)
                

        return (maxv, finalOldRow, finalOldCol, finalRow, finalCol)

                    
    #method that implements the minimum part of the minimax algorithm 
    def min(self, lastRow, lastCol, maxDepth, player, ordering, level):

        minv = 2000

        finalRow = None
        finalCol = None
        finalOldRow = None
        finalOldCol = None

        depth = maxDepth - 1

        opponent = 3 - player

        result = self.chooseHeuristics(level, lastRow, lastCol, opponent)
        x = random.randint(0,9)/10

        if result == 1000:
            return (result + depth + x, 0, 0, 0, 0)

        elif result != 1000 and depth == -1:
            return (result + depth + x, 0, 0, 0, 0)


        if player == 1:
            pieces = deepcopy(self.board.get_black_pieces())

        else:
            pieces = deepcopy(self.board.get_white_pieces())

        for piece in pieces:
            oldRow, oldCol = piece
            possibleMoves = self.board.get_valid_moves(oldRow, oldCol)
            orderedMoves = []

            if ordering != None:
                for i in range(0, len(possibleMoves)):
                    moveRow, moveCol = possibleMoves[i]
                    self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                    evaluation = self.chooseHeuristics(level, lastRow, lastCol, player)
                    orderedMoves.append((moveRow, moveCol, evaluation))

                    self.board.move_piece(moveRow,moveCol, oldRow, oldCol)

                orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering)

            else:               
                orderedMoves = possibleMoves

        
            for i in range(0,len(orderedMoves)):
                self.nodes += 1
                if ordering != None:
                    moveRow, moveCol, score = orderedMoves[i]
                else:
                    moveRow, moveCol = orderedMoves[i]

                self.board.move_piece(oldRow, oldCol, moveRow,moveCol)
                (m, max_old_row, max_old_col, max_row, max_col) = self.max(moveRow, moveCol, depth, opponent, ordering, level)

                if m < minv:
                    minv = m
                    finalRow = moveRow
                    finalCol = moveCol
                    finalOldRow = oldRow
                    finalOldCol = oldCol

                self.board.move_piece(moveRow,moveCol, oldRow, oldCol)


        return (minv, finalOldRow , finalOldCol ,finalRow, finalCol)
示例#12
0
    def drawSideBoard(self):
        if self.player == 1:
            myfont = pygame.font.SysFont('', 60)
            sideboard_title = myfont.render('BLACK TURN', True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 50))
            self.window.blit(sideboard_title, text_rect)
        elif self.player == 2:
            myfont = pygame.font.SysFont('', 60)
            sideboard_title = myfont.render('WHITE TURN', True, WHITE)
            text_rect = sideboard_title.get_rect(center=(1000, 50))
            self.window.blit(sideboard_title, text_rect)

        if self.gamemode == 1 or (self.gamemode == 2 and self.player == 1):
            self.button = Button(BLUE, 850, 150, 300, 100, 'Press for a hint')
            self.button.draw(self.window, True)
        elif self.gamemode == 3 or (self.gamemode == 2 and self.player == 2):
            self.button = Button(BLUE, 825, 150, 350, 100, 'Press for computer play')
            self.button.draw(self.window, True)
            

        if (self.gamemode == 3 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("AI move took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)
        elif (self.gamemode == 1 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("Hint calc. took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)
        elif (self.gamemode == 2 and self.time != None):
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render("Calculation took: " + str(round(self.time,5)) + " s", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 300))
            self.window.blit(sideboard_title, text_rect)
            sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK)
            text_rect = sideboard_title.get_rect(center=(1000, 350))
            self.window.blit(sideboard_title, text_rect)

        if self.winner != None and self.winner != -1:
            myfont = pygame.font.SysFont('', 60)
            if self.winner == 1:
                sideboard_title = myfont.render('BLACK WINS!', True, (0,0,0))
                text_rect = sideboard_title.get_rect(center=(1000, 700))
                self.window.blit(sideboard_title, text_rect)
            elif self.winner == 2:
                sideboard_title = myfont.render('WHITE WINS!', True, (255,255,255))
                text_rect = sideboard_title.get_rect(center=(1000, 700))
                self.window.blit(sideboard_title, text_rect)
            elif self.winner == 0:
                sideboard_title = myfont.render('TIE!', True, (72,68,68))
                text_rect = sideboard_title.get_rect(center=(1000, 650))
                self.window.blit(sideboard_title, text_rect)
            
            myfont = pygame.font.SysFont('', 40)
            sideboard_title = myfont.render('Press ENTER to continue', True, (72,68,68))
            text_rect = sideboard_title.get_rect(center=(1000, 750))
            self.window.blit(sideboard_title, text_rect)
示例#13
0
    def get_objects(self) -> list:
        game_state = GameState.get_instance()
        """Return all objects in current room"""
        if self.rooms[self._y][self._x] is None:
            self.load_room(self._x, self._y)
        # TODO: refactor :)
        objects = []
        for y, row in enumerate(self.rooms[self._y][self._x]):
            for x, tile in enumerate(row):
                if tile == '#':
                    objects.append(Wall(x * 16, y * 16))
                elif tile == '$':
                    objects.append(Teleport(x * 16, y * 16))
                elif tile == '{':
                    objects.append(Door(x * 16, y * 16))
                elif tile == '}':
                    objects.append(Door(x * 16, y * 16, 'right'))
                elif tile == ']':
                    objects.append(Door(x * 16, y * 16, 'up'))
                elif tile == '[':
                    objects.append(Door(x * 16, y * 16, 'down'))
                elif tile == 'r':

                    objects.append(Rock(x * 16 + 1, y * 16 + 1))
                elif tile == 'k':
                    inventory = Inventory.get_instance()
                    if not inventory.checkKey():
                        objects.append(Key(x * 16, y * 16, 1))
                elif tile == 'l':
                    objects.append(Key(x * 16, y * 16, 2))
                elif tile == 'g':
                    objects.append(Ghost(x * 16, y * 16))
                elif tile == 'b':
                    objects.append(Button(x * 16, y * 16))
                elif tile == 't':
                    objects.append(Trellis(x * 16, y * 16))

                elif tile == 'e':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load('img/dungeon_wall_broken.png').
                            convert_alpha()))
                elif tile == 'j':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load('img/dungeon_spiders_web.png').
                            convert_alpha()))
                elif tile == 'a':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/dungeon_bones.png').convert_alpha()))
                elif tile == 'c':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/dungeon_skull.png').convert_alpha()))
                elif tile == 'h':
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/candy_rainbow_wall.png').convert_alpha()))
                elif tile == 'm':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/candy_wall.png').convert_alpha()))
                elif tile == 'd':
                    objects.append(
                        Monster(x * 16, y * 16, 20, 'sounds/demon.ogg',
                                'img/demon_0.png', 'demon', 5))

                elif tile == 'n':
                    objects.append(
                        Monster(x * 16, y * 16, 15, 'sounds/demon.ogg',
                                'img/candy_mob_0.png', 'candy_mob', 0))

                elif tile == 'o':
                    objects.append(
                        Monster(x * 16, y * 16, 20, 'sounds/demon.ogg',
                                'img/rainbow_mob_0.png', 'rainbow_mob', 2))
                elif tile == 'z':
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load('img/dungeon_background2.png').
                            convert_alpha()))
                elif tile == 'p':
                    objects.append(
                        Trellis(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/krata2.png').convert_alpha()))
                elif tile == 'q':
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load('img/candy_rainbow_wall2.png').
                            convert_alpha()))
                elif tile == 'x':
                    objects.append(Rainbow_1(x * 16, y * 16))
                elif tile == '&':
                    objects.append(Rainbow_2(x * 16, y * 16))
                elif tile == 's':
                    objects.append(Key(x * 16, y * 16, 3))
                elif tile == 'u':
                    objects.append(Key(x * 16, y * 16, 4))
                elif tile == '+':
                    objects.append(Button_rainbow1(x * 16, y * 16))

                elif tile == '-':
                    objects.append(Button_rainbow2(x * 16, y * 16))

                elif tile == 'f':
                    objects.append(Background(x * 16, y * 16))
                elif tile == 'v':
                    objects.append(Saw(x * 16, y * 16))
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/saw_track.png').convert_alpha()))
                elif tile == '|':
                    objects.append(Saw(x * 16, y * 16, False))
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/saw_track_v.png').convert_alpha()))
                elif tile == '=':
                    objects.append(
                        Item(
                            "hp_potion", "hp_potion",
                            pygame.image.load(
                                'img/hp_potion.png').convert_alpha(), x * 16,
                            y * 16))
                elif tile == 'y':
                    objects.append(
                        Monster(x * 16, y * 16, 12, 'sounds/demon.ogg',
                                'img/dr_pehape_0.png', 'dr_pehape', 0, 4,
                                False))
                    game_state.sound = pygame.mixer.Sound('sounds/boss_t.ogg')
                elif tile == '*':
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/saw_track.png').convert_alpha()))
                elif tile == '@':
                    objects.append(
                        Background(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/saw_track_v.png').convert_alpha()))
                elif tile == '`':
                    objects.append(Resp(x * 16, y * 16))
                elif tile == ',':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece1.png').convert_alpha(),
                            "rocket"))
                elif tile == '<':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece2.png').convert_alpha(),
                            "rocket"))
                elif tile == '.':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece3.png').convert_alpha(),
                            "rocket"))
                elif tile == '>':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece4.png').convert_alpha(),
                            "rocket"))
                elif tile == ';':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece5.png').convert_alpha(),
                            "rocket"))
                elif tile == ':':
                    objects.append(
                        Wall(
                            x * 16, y * 16,
                            pygame.image.load(
                                'img/rocket_piece6.png').convert_alpha(),
                            "rocket"))
                elif tile == '?':
                    objects.append(Trellis_rainbow1(x * 16, y * 16))
                elif tile == '/':
                    objects.append(Trellis_rainbow2(x * 16, y * 16))

        return objects