예제 #1
0
 def __init__(self):
     self.boards = {
         # player 1, 2
         1: {
             # boards 1 -> ship board
             # 2-> attack board
             1: Board(),
             2: Board()
         },
         2: {
             # boards 1 -> ship board
             # 2-> attack board
             1: Board(),
             2: Board()
         }
     }
예제 #2
0
 def __init__(self):
     board = Board([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
     super().__init__(players=[
         HumanPlayer(name="Mikolaj", symbol='x'),
         HumanPlayer(name="Arek", symbol='o')
     ],
                      state=MemoryState(board, moves=['x', 'o']))
예제 #3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.title("Drunkard walk")
        self.resizable(False, False)
        self.controller = EventController(self)

        board = Board()

        self.controller.set_board(board)

        main_frame = ttk.Frame(self, padding=(20, 10, 10, 10))
        main_frame.pack(fill="both", expand=True)
        interface_frame = InterfaceFrame(main_frame,
                                         self.controller,
                                         padding=(20, 10, 10, 10))
        interface_frame.pack(side="left", fill="x")
        board_frame = BoardFrame(main_frame,
                                 board,
                                 self.controller,
                                 padding=(10, 10, 10, 10))
        board_frame.pack(side="left", fill="both")

        output_frame = OutputFrame(self,
                                   self.controller,
                                   padding=(20, 10, 20, 10))
        output_frame.pack(side="bottom", fill="both", expand=True)
예제 #4
0
 def __init__(self):
     board = Board([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
     super().__init__(players=[
         HumanPlayer(name="Humek", symbol='x'),
         ComputerPlayer(name="Comp", symbol='o')
     ],
                      state=MemoryState(board, moves=['x', 'o']))
예제 #5
0
    def initialize_board(self, board_size, players_list):

        self.__game_dao.set_ladders()
        self.__game_dao.set_snakes()
        self.__board = Board(board_size)

        for player in players_list:
            self.__game_dao.add_player(player)
예제 #6
0
    def build(self, testMode=True):
        """
        Initiate objects and views.
        """
        ''' init game objects '''
        self.deck = Deck()
        self.evaluator = Evaluator()

        self.player = []
        self.player.append(Player(0))
        self.player.append(Player(1))
        # board stands for public cards on board
        self.board = Board()

        # In test mode, both player select right-most cards for the turn automatically
        self.testMode = testMode
        ''' create view objects '''
        # Scatter that can be rotated to display players
        scatter_bot = ScatterLayout(do_rotation=False,
                                    do_translation=False,
                                    do_scale=False,
                                    size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    },
                                    rotation=0)
        # For player on top, the widget rotates 180 degree
        scatter_top = ScatterLayout(do_rotation=False,
                                    do_translation=False,
                                    do_scale=False,
                                    size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    },
                                    rotation=180)

        box = PlayerDeck()
        box2 = PlayerDeck()
        publicArea = PublicArea()
        box.build(self, "player1", 0, self.testMode)
        box2.build(self, "player2", 1, self.testMode)
        publicArea.build()

        scatter_bot.add_widget(box)
        scatter_top.add_widget(box2)

        self.add_widget(scatter_bot)
        self.add_widget(scatter_top)
        self.add_widget(publicArea)

        # register id of view objects
        self.ids[box.id] = box
        self.ids[box2.id] = box2
        self.ids[publicArea.id] = publicArea
예제 #7
0
def parse_file(file_name):

    tiles = []
    with open(file_name) as f:
        num_lines = int(f.readline())

        for i in range(num_lines):
            line = [int(tile) for tile in f.readline().split(' ')]
            tiles.append(line)

    return Board(tiles)
예제 #8
0
 def board(self):
     threshold = GlobalProperties.histeresis
     board = sr.get_state()
     r = 0  # repeat - how many times was this state
     while not _is_valid(board, self.board_size) or r < threshold:
         pboard = board
         board = sr.get_state()
         if diff(pboard, board)[0] == 0:
             r += 1
         else:
             r = 0
     return Board(board)
예제 #9
0
 def load(I, path):
     """
     Reset the board and load history from given path.
     """
     with open(path, mode='r', encoding='utf-8') as f:
         history = json.load(f, object_hook=Turn.from_json)
     board = Board()
     for turn in history:
         for src, dst in turn.moves:
             board = board.move(src, dst)
     I.board = board
     I.history = history
예제 #10
0
def play_game(ngames=100):
    verbose = ngames == 1

    cost_of_hut = 0.05
    cost_of_station = 3
    ntrees = 9
    ngardens = 3
    ncurses = 3
    """
    IDEAL GAME SCENARIOS:
        selfish vs. selfish: RARELY WIN
        selfish vs. default: MOSTLY WIN -> SELFISH
        selfish vs. generous: ALWAYS WIN -> SELFISH
        generous vs. generous: RARELY WIN
    """
    player_types = ["reasonable", "reasonable"]  #
    # player_types = ["default", "generous"] #
    # player_types = ["super-selfish", "super-selfish"] #
    # player_types = ["selfish", "reasonable"] #
    # player_types = ["selfish", "selfish"] #
    # player_types = ["reasonable", "selfish"] #
    # player_types = ["selfish", "super-selfish"] #
    # player_types = ["super-selfish", "reasonable"] #
    # player_types = ["super-selfish", "generous"] #
    # player_types = ["selfish", "default"] # 8/10, all S
    # player_types = ["selfish", "generous"] # 5/10, all S
    # player_types = ["generous", "generous"] # 0/10
    # player_types = ["reasonable", "reasonable"] # 0/10

    board = Board((6, 6), {
        "hut": cost_of_hut,
        "station": cost_of_station
    },
                  ntrees=ntrees)
    deck = Deck({"garden": ngardens, "curse": ncurses})
    g = Game(board, deck, verbose=verbose)
    ps = get_players(player_types)
    ss = []
    ws = []
    for i in xrange(ngames):
        status, winner = g.play(ps, print_end_status=False)
        ss.append(status)
        ws.append(winner)
        g.reset()

    import collections
    print '=================='
    print collections.Counter(ws)
    print collections.Counter(ss)
예제 #11
0
파일: html.py 프로젝트: mcroitor/olive-gui
def render(entry, settings):

    board = Board()
    board.fromAlgebraic(entry["algebraic"])

    html = pdf.ExportDocument.header(entry, settings['lang'])
    html += board_to_html(board, settings['diagram_font'])
    html += entry['stipulation'] + ' ' + board.getPiecesCount() + "<br/>\n"
    html += pdf.ExportDocument.solver(entry, settings['lang']) + "<br/>\n"
    html += pdf.ExportDocument.legend(board) + "<br/><br/>\n"
    if 'solution' in entry:
        html += solution_to_html(entry['solution'], settings['inline_font'])
    if 'keywords' in entry:
        html += "<br/>\n" + ', '.join(entry['keywords']) + "<br/>\n"
    if 'comments' in entry:
        html += "<br/>\n" + "<br/>\n".join(entry['comments']) + "<br/>\n"
    html += "<br/><br/>\n"

    return html
예제 #12
0
    def post(self):
        user = users.get_current_user()
        if user:
            key_user = ndb.Key(User, user.email())
            user_details = key_user.get()
            board = Board()
            board.boardTitle = self.request.get('title').strip()
            board.owner = user.email()
            board.users.append(user_details)
            boardKey = board.put()
            boardKeyId = boardKey.get().key.id()
            if user_details:
                if user_details.boards: key_dict = user_details.boards
                else: key_dict = {}
                key_dict[boardKeyId] = boardKey.urlsafe()
                userModel = User(key=key_user, boards=key_dict, email=user.email())
                userModel.put()

            self.add_message('Task Board created successfully.', 'success')
            self.redirect('/boards', abort=False)
            return
        else:
            self.redirect('/', abort=False)
예제 #13
0
def main():
    # get players
    player1, player2 = initialisePlayer()
    # build board
    boardConfig = {
        "size": initialiseBoard()
        # "size": 5
    }
    board = Board(**boardConfig)
    gameController = GameController(board)

    # reset
    gameController.resetBoard()
    gameController.printBoard()

    # build battleship and place
    ships = initialiseShip()
    for ship in ships:
        gameController.place(Battleship(**ship))
        gameController.printBoard()
    
    # player attacks
    print(gameController.attack(**playerAttack()))
    gameController.printBoard()
예제 #14
0
    def get_board_stats(self, project_name: str, board_name: str) -> Task:

        board_data = self._get_board(project_name, board_name)

        board = Board(project_name, board_name)

        for column in board.columns:
            tasks = create_tasks_from_dict(column.tasks)
            board.add_column(column['title'], tasks)


        # tasks = list()
        # for project in my_dashboard:
        #     task = Task(project['project_name'], project['title'], project['priority'], project['column_name'],
        #                 project['assignee_username'], project['date_due'])
        #     tasks.append(task)
        #
        # if printable:
        #     table = self.get_summary_tasks(tasks)
        #     print(table)
        #
        # return tasks

        pass
예제 #15
0
 def test_default(self):
     board = Board()
     self.assertEqual(board.tiles, [[None, None, None, None],
                                    [None, None, None, None],
                                    [None, None, None, None],
                                    [None, None, None, None]])
예제 #16
0
 def __init__(self):
     self.board1 = Board(10, 22, StackBot())
     self.board2 = Board(10, 22, RandomBot())
예제 #17
0
from model import Board
from pyqt import GofWindow
from PyQt5.QtWidgets import QApplication
import sys

if __name__ == '__main__':
    app = QApplication(sys.argv)
    board = Board((35, 35))
    win = GofWindow(board)
    win.show()
    sys.exit(app.exec_())
예제 #18
0
port = 5005
backlog = 5
maxsize = 1024

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(backlog)
input = [
    server,
]

var = 1
print("Serwer started")
print("Waiting for players")

new_game = Board()

for x in range(2):
    inputready, outputready, exceptready = select.select(input, [], [])
    print("Waiting for second player")

    for s in inputready:
        if s == server:
            client, address = server.accept()
            input.append(client)
            print('new client added%s' % str(address))
            if (var == 2):
                input[1].send(str.encode("oponent found"))
                input[2].send(str.encode("oponent found"))
            var += 1
예제 #19
0
 def __init__(I, white=None, black=None):
     I.board = Board()
     I.history = []
     I.black = black or ConsolePlayer()
     I.white = white or ComputerPlayer(WHITE, strategy.safe)
예제 #20
0
 def test_3x5(self):
     board = Board(rows=3, cols=5)
     self.assertEqual(board.tiles, [[None, None, None, None, None],
                              [None, None, None, None, None],
                              [None, None, None, None, None]])
예제 #21
0
                    continue
            except KeyError:
                pass

            heapq.heappush(heap, child)
            inheap[commaHash(child.board.seq)] = 1
            dic['max_search_depth'] = max(dic['max_search_depth'], child.depth)

    return None


method = sys.argv[1]
board = sys.argv[2].split(',')

N = int(math.sqrt(len(board)))
root = State(Board(board, N), 0)

bottom = None
goal = []
for ch in range(N**2):
    goal.append(str(ch))

if method == 'bfs':

    start_time = time.time()
    bottom = bfs(root, goal)
    dic['running_time'] = '%s' % round(time.time() - start_time, 8)

elif method == 'dfs':

    start_time = time.time()
예제 #22
0
파일: main.py 프로젝트: astralhpi/sudoku
from model import Board, Problem
from view import SudokuScreen
from view.widget import *

Config.set('graphics', 'width', '320')
Config.set('graphics', 'height', '480')

Builder.load_file('kv/sudoku.kv')
LabelBase.register('SeoulNamsan',
                   fn_regular='static/font/SeoulNamsanM.ttf',
                   fn_bold='static/font/SeoulNamsanB.ttf')

problem = Problem.loads(
    "800523910162489075350170420425008009690000"
    "057700600234037062041540317692016954003",
    "87452391616248937535917642842573816969324185"
    "7781695234937862541548317692216954783", 9)
board = Board(problem)

sm = ScreenManager()
sm.switch_to(SudokuScreen(board_model=board))


class SudokuApp(App):
    def build(self):
        return sm


if __name__ == '__main__':
    SudokuApp().run()
예제 #23
0
    if row == 4:
        return (Board.FIFTH_ROW_TOP_BORDER + Board.FIFTH_ROW_BOTTOM_BORDER) / 2
    if row == 5:
        return (Board.SIXTH_ROW_TOP_BORDER + Board.SIXTH_ROW_BOTTOM_BORDER) / 2


# Initializes the pygame modules
pygame.init()

# The window of the game
display = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
display_width, display_height = pygame.display.get_surface().get_size()
pygame.display.set_caption('ConnectFour')

# Initialize the board and discs
board = Board.Board(display_width, display_height)
disc_array = [
    Disc.Disc("Red") if i % 2 == 0 else Disc.Disc("Yellow") for i in range(42)
]
for disc in disc_array:
    disc.x = (Board.FIRST_COLUMN_LEFT_BORDER +
              Board.FIRST_COLUMN_RIGHT_BORDER) / 2
    disc.y = Board.TOP_BOARD_SPACE - Disc.DISC_PIXEL_DIAMETER / 2 - 5
disc_used_array = []
move = (0, 0)
row_position = None

# Disc number in the array
disc_number = 0

# Create a scoreboard and set its position to the right of the board
예제 #24
0
 def __init__(I, south=None, north=None):
     I.board = Board()
     I.history = []
     I.south = south or ConsolePlayer()
     I.north = north or ComputerPlayer(safe)