Пример #1
0
def main(width=800, height=800):
    global window, history, background_batch, pieces_batch
    window = pyglet.window.Window(width=width, height=height)
    pieces_batch = pyglet.graphics.Batch()
    background_batch = pyglet.graphics.Batch()

    asset_map = assets.load_assets(pyglet)

    board_sprite = pyglet.sprite.Sprite(asset_map.board,
                                        batch=background_batch)
    for piece, image in asset_map.pieces.items():
        piece_sprite = pyglet.sprite.Sprite(image, batch=pieces_batch)
        piece_sprites[piece] = piece_sprite

    starting_board = board.create_board()

    for coords, piece in starting_board.items():
        image = asset_map.pieces[piece]
        x, y = coords
        cell_size = 480 / 8
        pyglet.sprite.Sprite(image, batch=pieces_batch)

    @window.event
    def on_draw(self):
        self.clear()
        self.background_batch.draw()
        self.pieces_batch.draw()

    pyglet.app.run()
Пример #2
0
    def create_board_post(self, board_name, board_id, current_uid = -1):
        board_info = board.get_board_info(board_id)
        if not acl.is_allowed('board', board_id, current_uid, 'create'):
            return util.render().error(error_message = _('NO_PERMISSION'), help_context='error')
        user_data = web.input()
        comment = 1 if user_data.has_key('commentable') else 0
        write_by_other = 1 if user_data.has_key('writable') else 0
        indexable = 1 if user_data.has_key('indexable') else 0
        show_avatar = 1 if user_data.has_key('show_avatar') else 0

        owner_uid = user._get_uid_from_username(user_data.owner)
        if owner_uid < 0:
            return util.render().error(error_message=_('NO_SUCH_USER_FOR_BOARD_ADMIN'), help_context='error')
        if user_data.name.strip() == '':
            return util.render().error(error_message = _('NO_NAME_SPECIFIED'), help_context='error')
        if board_name == '^root':
            new_path = posixpath.join('/', user_data.name)
        else:
            new_path = posixpath.join('/', board_name, user_data.name)
        if board._get_board_id_from_path(new_path) > 0:
            return util.render().error(error_message = _('BOARD_EXISTS'), help_context='error')

        settings = dict(path=new_path, board_owner = owner_uid,
                cover = user_data.information,
                description = user_data.description,
                type = int(user_data.type),
                guest_write = write_by_other,
                can_comment = comment,
                indexable = indexable, show_avatar = show_avatar,
                current_uid = current_uid)
        ret = board.create_board(board_id, settings)
        if ret[0] == False:
            return util.render().error(error_message = ret[1] ,help_context = 'error')
        raise web.seeother(util.link('%s') % (new_path))
Пример #3
0
 def __init__(self, player1_colour, player2_colour):
     self.player1_colour = player1_colour
     self.player2_colour = player2_colour
     self.player1 = None
     self.player2 = None
     self.board = create_board()
     print_board(self.board)
     self.clock = pygame.time.Clock()
Пример #4
0
    def test_create_board2(self):
        """ Test if the create_board function correctly sets up
        a 7x5 board initialized with 0 values.
        """

        sample_board = [
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0],
                ]

        self.assertEqual(sample_board, board.create_board(5, 7))
Пример #5
0
def find_move(board, side):
    '''
    Find a move.

    Returns: (x, y, won)
    '''
    count_results = count_paths(board, side)

    if check_draw(count_results):
        raise Draw

    value_board = create_board(0)

    # calc value
    for path, (self_count, opponent_count) in zip(PATHS, count_results):

        if self_count * opponent_count > 0:
            continue

        if self_count == 4:
            for x, y in walk_path(path):
                if board[y][x] != side:
                    return (x, y, True)

        self_value = VALUES[self_count]
        opponent_value = VALUES[opponent_count]
        value = self_value + opponent_value

        for x, y in walk_path(path):
            value_board[y][x] += value

    # find most valuable
    max_value = 0
    candidates = []
    for x in range(SIZE):
        for y in range(SIZE):
            if board[y][x] != BOARD_STAT_BLANK:
                continue
            value = value_board[y][x]
            if value > max_value:
                max_value = value
                candidates = [(x, y)]
            elif value == max_value:
                candidates.append((x, y))

    # pick one choice from the candidates
    return choice(candidates) + (False, )
Пример #6
0
    def __init__(self, rows, cols, speed):
        self.root = Tkinter.Tk()

        self._rows = rows
        self._cols = cols

        self._speed = speed 

        self._generation = 0
        self._active = False


        self._game_board = board.create_board(self._rows, self._cols)
        self._gui = gui.GuiApp(self,
                canvas_rows=self._rows, canvas_cols=self._cols, 
                speed=self._speed, generation=self._generation)
        self._gui.pack()
Пример #7
0
def main():

    # Load the dictionary.
    dictionary = Dictionary.load(DICTIONARY_FILENAME)
    board = Board()

    # Keep track of the winning solution at each round.
    winners = []

    # List of letters we can still pick from.
    bag = get_full_bag()

    # Rack starts out empty. Keep track of current and last rack state.
    rack = ""
    old_rack = ""
    count = 0

    # Keep track of current and last board state,
    update_board = None
    old_board = None

    # Baxter's score
    my_score = 0

    #Create classifier
    classify = CNN_Model()

    # Create video feeds
    # cam = cv2.VideoCapture(1)
    # print cam.isOpened()

    # Keep playing until we're out of tiles or solutions.
    while count < 8:
        count+=1
        # Fill up our rack.
        print "Bag: %s" % "".join(bag)
        old_rack = rack

        # Updates rack with current rack from video feed.
        # cam1 = cv2.VideoCapture(1)
        # print cam1.isOpened()
        cam1 = 1
        rack = get_rack(classify,cam1)
        # cam1.release()
        cv2.destroyAllWindows()

        # Get a list of possible solutions. These aren't all necessarily legal.
        solutions = board.generate_solutions(rack, dictionary)

        solution = board.find_best_solution(solutions, dictionary)

        if solution:
            print "Winner: %s" % solution

            # Play the winning solution.
            board.create_board()
            print("I suggest you play the word:"+solution.word)
            #speech.speak(solution)
        else:
            # Should put letters back in bag.
            break
        print board
        
        # Wait for "Enter" press, signifying the player has completed his/her turn.
        #wait = raw_input("Press enter when finished with move")

        # Get word that was just played on the board by fetching the new board state.
        # cam1.release()
        # del cam1
        # cam1 = cv2.VideoCapture(0)
        # while not cam1.isOpened():
        #     cam1.release()
        #     del cam1
        #     cam1 = cv2.VideoCapture(0)

        update_board = get_board(classify,cam1)
        # cam1.release()
        
        move,letter_placed_on_board = board.get_played_word(update_board,old_board,dictionary)
        print ("The word"+move+"was just played")

        if (move == solution.word):
            print("Player listened to Baxter")
        else:
            print("defied Baxter")




        print "Baxter's Score: %d" % my_score

        generate_rack(rack,old_rack,bag)

        for char in letter_placed_on_board:
            rack = rack.replace(char,"")

    print "Baxter's Score: %d" % my_score
    print "Baxter's Words:"
    for rack, winner in winners:
        print "    %s: %s" % (rack, winner)
Пример #8
0
from common import BOARD_STAT_BLANK, BOARD_STAT_BLACK, BOARD_STAT_WHITE,\
    PLAYER_HINTS, SPLIT_LINE, input_move, other_side
from board import create_board, clear_board, render_board, render_draw
from path import PATHS, count_paths, check_draw

rounds = 0
board = create_board(BOARD_STAT_BLANK)
side = BOARD_STAT_BLACK


def main_pvp():
    '''Entry point of PvP mode.'''
    global rounds, side
    rounds = 1
    side = BOARD_STAT_BLACK
    clear_board(board)
    loop_pvp()


def loop_pvp():
    '''Game loop of PvP.'''
    global rounds, side

    # info
    print()
    print(SPLIT_LINE)
    print()
    render_board(board)
    print()
    print('Round {} -- {}'.format(rounds, PLAYER_HINTS[side]))
    print()
Пример #9
0
"""
Do the actual game computation in here, then give the outputs to pygame
Main control center of the game + engine
"""
import board
import pieces as p
import settings as sett

master_board = board.create_board()
turn_number = 1
# if odd, white's turn, if even, black's turn


def start_game():
    # White pieces
    wr1 = p.Rook(sett.files[0], sett.rows[0], sett.piece_types[0],
                 sett.teams[0])
    wkn1 = p.Knight(sett.files[1], sett.rows[0], sett.piece_types[1],
                    sett.teams[0])
    wb1 = p.Bishop(sett.files[2], sett.rows[0], sett.piece_types[2],
                   sett.teams[0])
    wq = p.Queen(sett.files[3], sett.rows[0], sett.piece_types[3],
                 sett.teams[0])
    wk = p.King(sett.files[4], sett.rows[0], sett.piece_types[4],
                sett.teams[0])
    wb2 = p.Bishop(sett.files[5], sett.rows[0], sett.piece_types[2],
                   sett.teams[0])
    wkn2 = p.Knight(sett.files[6], sett.rows[0], sett.piece_types[1],
                    sett.teams[0])
    wr2 = p.Rook(sett.files[7], sett.rows[0], sett.piece_types[0],
                 sett.teams[0])
Пример #10
0
def test_create_board():
    size = 3
    board = create_board(size)
    for x in range(size):
        for y in range(size):
            assert board[x][y] == (x,y)
Пример #11
0
def test_iter():
    grid = create_board()
    for square in grid:
        print square
Пример #12
0
    def __init__(self, players, maximum_rounds=5000, print_debug=False, custom_settings=False, city_edges=None, \
                 edges=None,
                 deck=None,
                 destinations=None, num_cars=45):
        if not custom_settings:
            self._city_edges, self._edges = create_board()
            self._deck, self._destinations = init_decks()
            self._num_cars = self.DEFAULT_NUM_CARS
        else:
            self._city_edges = city_edges
            self._edges = edges
            self._deck = deck
            self._destinations = destinations

            self._num_cars = num_cars

        self.print_debug = print_debug
        self._maximum_rounds = maximum_rounds
        self._rounds_count = 0
        self.gui = None
        self._scoring = get_scoring()
        self._double_edges = dict()
        self._players = players

        # Select 5 face up cards.
        # noinspection PyUnusedLocal
        self._face_up_cards = [self._deck.pop() for x in range(5)]

        # Initialize edge claims
        self._edge_claims = {edge: None for edge in self._edges}
        if len(players) < 4:  # tracking double edges in 2 and 3 player games
            self._track_double_edges()

        # Visible scores are set to zero.
        self._visible_scores = {player.name: 0 for player in self._players}

        # Initialize info for all players.
        self._player_info = {}
        for player in players:
            # initialize the player info first
            self._player_info[player] = PlayerInfo()
            player_info = self._player_info[player]
            # set player's number of cars
            player_info.num_cars = num_cars

            # Give each player a hand of 5 cards from the top of the deck.
            # noinspection PyUnusedLocal
            hand = Hand(
                [self._deck.pop() for x in range(self.STARTING_HAND_SIZE)])
            player_info.hand = hand

            # Give each player 3 destinations.
            possible_destinations = [
                self._destinations.pop(),
                self._destinations.pop(),
                self._destinations.pop()
            ]
            player.initialize_game(self)
            if self.print_debug:
                print player, "is selecting initial tickets"

            destinations = player.select_starting_destinations(
                self, possible_destinations)

            if len(destinations) < 2:
                raise Exception(
                    "Failure",
                    FailureCause.str(FailureCause.not_enough_destinations))

            score = 0
            for destination in destinations:
                # Make sure the destination card is in the possible_destination cards set
                if destination not in possible_destinations:
                    raise Exception(
                        "Failure",
                        FailureCause.str(FailureCause.wrong_destination_card))

                # Reduce score by all incomplete destinations.
                score -= destination.value

            if self.print_debug:
                print player, "selected tickets", destinations

            # set the selected destinations
            player_info.destinations = destinations

            # set the player's calculated score
            player_info.score = score

        # Set the first player to have the first turn.
        self._current_player_index = 0

        # The number of actions the player has left to take this turn.
        self._num_actions_remaining = 2

        self._game_is_over = False

        self._discards = []

        # Create the sets for events that will trigger when the game ends or begins.
        self._turn_ended_events = set()
        self._game_ended_events = set()

        # Store a history of all actions taken.
        self._history = []
Пример #13
0
def main():
    # creating boards for player1 and player2
    board1 = create_board()
    board2 = create_board()

    # input players' name
    player1_name = input('First players name: ')
    player2_name = input('Second players name: ')

    # creating ships on player1's board
    ship1_ver1 = gen_random_ship(board1, 4, "ver")
    ship1_ver2 = gen_random_ship(board1, 3, "ver")
    ship1_hor1 = gen_random_ship(board1, 2, "hor")
    ship1_hor2 = gen_random_ship(board1, 3, "hor")

    # creating ships on player2's board
    ship2_ver1 = gen_random_ship(board2, 4, "ver")
    ship2_ver2 = gen_random_ship(board2, 3, "ver")
    ship2_hor1 = gen_random_ship(board2, 3, "hor")
    ship2_hor2 = gen_random_ship(board2, 2, "hor")

    print_board(board1)

    while True:
        print("\033[1;34;40m \n")
        print(ship1_ver1)
        print(ship1_ver2)
        print(ship1_hor1)
        print(ship2_ver1)
        print(ship2_ver2)
        print(ship2_hor2)

        # board, guessing, hit count for player1
        player(board1, player1_name)
        print_board(board1)
        if hit_ship(board1, ship1_ver1, 4, "ver") \
           or hit_ship(board1, ship1_ver2, 3, "ver") \
           or hit_ship(board1, ship1_hor1, 2, "hor") \
           or hit_ship(board1, ship1_hor2, 3, "hor"):
            print("It was a boat")

        # end play for player1
        if all_fleet_hit(board1, 12):
            answer = input(
                "{} WIN. Game over \n New game? Y/N".format(player1_name))
            if answer == "Y":
                main()
            else:
                exit()

        # board, guessing, hit count for player2
        print("\033[0;32;47m \n")
        print_board(board2)
        player(board2, player2_name)
        print_board(board2)
        if hit_ship(board2, ship2_ver1, 4, "ver") \
           or hit_ship(board2, ship2_ver2, 3, "ver") \
           or hit_ship(board2, ship2_hor2, 2, "hor")\
           or hit_ship(board2, ship2_hor1, 3, "hor"):
            print("It was a boat")

        # end play for player2
        if all_fleet_hit(board2, 12):
            answer2 = input(
                "{} WIN. Game over \n New game? Y/N".format(player2_name))
            if answer2 == "Y":
                main()
            else:
                exit()
Пример #14
0
 def setUp(self):
     board.create_board()
Пример #15
0
def main():
    # Load the dictionary.
    dictionary = Dictionary.load(DICTIONARY_FILENAME)
    board = Board()

    # Keep track of the winning solution at each round.
    winners = []

    # List of letters we can still pick from.
    bag = get_full_bag()


    # Rack starts out empty.
    rack = ""
    old_rack = ""
    count = 0
    # Baxter's score
    my_score = 0
    # Opponent's score
    opp_score = 0
    # Parameter setting the minimum point defiticit of Baxter's opponent\
    # before Baxter attempts to manipulate his teammate to play low-scoring words
    manip_threshold = 50
    # Keep playing until we're out of tiles or solutions.
    while count < 8:
        count = count +1 
        # Fill up our rack.
        print "Bag: %s" % "".join(bag)
        
        update_board = None
        old_board = None
        # rack = get_rack()
        #if not rack:
        #    break
        old_rack = rack
        rack = scrabblerack.boardtrainer('')
        print rack
        

        # start_time = 0
        # elapsed_time = 0
        # wait_time = 8*60
        # while (elapsed_time < wait_time)
        #old_board = updated_board
        #updated_board = board.create_board()
        
        #rack = get_rack()
        #     if rack:
        #        generate_rack(rack,old_rack,bag)
        #         break
        #opp_score = opp_score + board.opponent_word_score(update_board,old_board,dictionary)
        # opp_score = opp_score + board.opponent_word_score(dictionary)
        #         elapsed_time = time.time() - start_time
        #generate_rack(rack,old_rack,bag)

        # Get a list of possible solutions. These aren't all necessarily legal.
        solutions = board.generate_solutions(rack, dictionary)
        #rack = generate_rack(rack,old_rack,bag)

        # Weed out the illegal solutions and score the rest, returning the
        # highest-scoring solution.
        
        # sets the percentile of the word's score
        low_score_param = 1/2
        if (my_score > (opp_score + manip_threshold) or my_score > 500):
            solution  = board.find_suboptimal_solution(solutions, dictionary, low_score_param)
        else: solution = board.find_best_solution(solutions, dictionary)

        if solution:
            print "Winner: %s" % solution

            # Play the winning solution.
            board.add_solution(solution)
            winners.append((rack, solution))
            my_score = my_score + solution.score

            # Deplete the rack of the used tiles.
            rack = solution.get_new_rack(rack)
        else:
            # Should put letters back in bag.
            break
        print board
        board.create_board()
        speech.speak(solution)

        word = raw_input("What word would you like to play? ")
        row = raw_input("What row does it start at? ")
        col = raw_input("What column does it start at? ")
        direc = raw_input("Is it oriented vertically or horizontally? ")
        #indices = raw_input("indices? ")
        # if (dir == 'horizontally'): dir = direction.Direction(0,1)
        # else: direction.Direction(1,0)
        #opp_score = opp_score + board.opponent_word_score(row,col,dir,word,dictionary,indices)
        row = int(row)
        col = int(col)
        opp_score = opp_score + board.opponent_word_score(row,col,word,direc,dictionary)


        print "Baxter's Score: %d" % my_score
        print "Opponent's Score: %d" % opp_score

    print "Baxter's Score: %d" % my_score
    print "Opponent's Score: %d" % opp_score
    print "Baxter's Words:"
    for rack, winner in winners:
        print "    %s: %s" % (rack, winner)