def test_fire_wrong_turn(self):
        layout = BoardLayout(10)
        layout.append(
            ShipPosition(text='AA', row=0, column=0, orientation='horizontal'))
        nonces = create_nonces(10)

        # Send join payload to tp
        fire_req = create_fire_payload('invalid_row', '1', 'Z')

        self.validator.send(
            self.player_1.create_tp_process_request(fire_req)
        )

        # give state back to tp

        self.send_state_to_tp('invalid_row', {
            'Ships': ['AA'],
            'TargetBoard1': [['?'] * 10 for _ in range(10)],
            'TargetBoard2': [['?'] * 10 for _ in range(10)],
            'Player1': self.public_key_1,
            'Player2': self.public_key_2,
            'HashedBoard1': layout.render_hashed(nonces),
            'HashedBoard2': layout.render_hashed(nonces),
            'State': 'P2-NEXT'
        })

        self.expect_invalid()
Exemple #2
0
def do_join(args, config):
    name = args.name

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    client_for_state = BattleshipClient(base_url=url, keyfile=key_file)
    state = client_for_state.get_all_store_objects()
    if name not in state:
        raise BattleshipException(
            "No such game: {}".format(name)
        )
    game = state[name]
    ships = game['Ships']

    if name not in data['games']:
        new_layout = BoardLayout.generate(ships=ships)
        data['games'][name] = {}
        data['games'][name]['layout'] = new_layout.serialize()
        data['games'][name]['nonces'] = create_nonces(new_layout.size)

        home = os.path.expanduser("~")

        username = config.get('DEFAULT', 'username')

        data_file = os.path.join(home,
                                 ".sawtooth",
                                 "battleship-{}.data".format(username))
        with open(data_file + ".new", 'w') as fd:
            json.dump(data, fd, sort_keys=True, indent=4)
        if os.name == 'nt':
            if os.path.exists(data_file):
                os.remove(data_file)
        os.rename(data_file + ".new", data_file)
    else:
        print("Board and nonces already defined for game, reusing...")

    layout = BoardLayout.deserialize(data['games'][name]['layout'])
    nonces = data['games'][name]['nonces']

    hashed_board = layout.render_hashed(nonces)

    client = BattleshipClient(base_url=url, keyfile=key_file)
    client.join(name=name, board=hashed_board)

    if args.wait:
        client.wait_for_commit()
def do_join(args, config):
    name = args.name

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    client_for_state = BattleshipClient(base_url=url, keyfile=key_file)
    state = client_for_state.get_all_store_objects()
    if name not in state:
        raise BattleshipException(
            "No such game: {}".format(name)
        )
    game = state[name]
    ships = game['Ships']

    if name not in data['games']:
        new_layout = BoardLayout.generate(ships=ships)
        data['games'][name] = {}
        data['games'][name]['layout'] = new_layout.serialize()
        data['games'][name]['nonces'] = create_nonces(new_layout.size)

        home = os.path.expanduser("~")

        username = config.get('DEFAULT', 'username')

        data_file = os.path.join(home,
                                 ".sawtooth",
                                 "battleship-{}.data".format(username))
        with open(data_file + ".new", 'w') as fd:
            json.dump(data, fd, sort_keys=True, indent=4)
        if os.name == 'nt':
            if os.path.exists(data_file):
                os.remove(data_file)
        os.rename(data_file + ".new", data_file)
    else:
        print("Board and nonces already defined for game, reusing...")

    layout = BoardLayout.deserialize(data['games'][name]['layout'])
    nonces = data['games'][name]['nonces']

    hashed_board = layout.render_hashed(nonces)

    client = BattleshipClient(base_url=url, keyfile=key_file)
    client.join(name=name, board=hashed_board)

    if args.wait:
        client.wait_for_commit()
def do_genstats(args, config):
    count = args.count
    size = args.size
    ships = ["AAAAA", "BBBB", "CCC", "DD", "DD", "SSS", "SSS"]
    # Create a board which contains a count of the number of time
    # a space was used.
    count_board = [[0] * size for i in range(size)]
    for i in range(0, count):
        layout = BoardLayout.generate(size=size, ships=ships)
        board = layout.render()
        for row in range(0, size):
            for col in range(0, size):
                if board[row][col] != '-':
                    count_board[row][col] += 1

    print("Percentages Board")
    print("-----------------")

    # Print the board of percentages.
    print("  ", end=' ')
    for i in range(0, size):
        print("  {}".format(chr(ord('A') + i)), end=' ')
    print()

    for row in range(0, size):
        print("%2d" % (row + 1), end=' ')
        for space in count_board[row]:
            print("%3.0f" % (float(space) / float(count) * 100, ), end=' ')
        print()

    print()
    print("Total Games Created: {}".format(count))
    def test_join_game_valid(self):
        layout = BoardLayout.generate(self.test_ships)
        nonces = create_nonces(10)

        # Send join payload to tp

        join_req = create_join_payload('join_game', layout, nonces)
        self.validator.send(
            self.player_1.create_tp_process_request(join_req)
        )

        # give state back to tp

        self.send_state_to_tp('join_game', {
            'Ships': self.test_ships,
            'State': 'NEW'
        })

        # mock state set
        LOGGER.debug('state update')
        self.update_state('join_game', {
            'Ships': self.test_ships,
            'TargetBoard1': [['?'] * 10 for _ in range(10)],
            'Player1': self.public_key_1,
            'HashedBoard1': layout.render_hashed(nonces),
            'State': 'NEW'
        })

        self.expect_ok()
def do_genstats(args, config):
    count = args.count
    size = args.size
    ships = ["AAAAA", "BBBB", "CCC", "DD", "DD", "SSS", "SSS"]
    # Create a board which contains a count of the number of time
    # a space was used.
    count_board = [[0] * size for i in range(size)]
    for i in xrange(0, count):
        layout = BoardLayout.generate(size=size, ships=ships)
        board = layout.render()
        for row in xrange(0, size):
            for col in xrange(0, size):
                if board[row][col] != '-':
                    count_board[row][col] += 1

    print("Percentages Board")
    print("-----------------")

    # Print the board of percentages.
    print("  ", end=' ')
    for i in xrange(0, size):
        print("  {}".format(chr(ord('A') + i)), end=' ')
    print()

    for row in xrange(0, size):
        print("%2d" % (row + 1), end=' ')
        for space in count_board[row]:
            print("%3.0f" % (float(space) / float(count) * 100,), end=' ')
        print()

    print()
    print("Total Games Created: {}".format(count))
def do_genstats(args, config):
    count = args.count
    size = args.size

    # Create a board which contains a count of the number of time
    # a space was used.
    count_board = [[0] * size for i in range(size)]
    for i in xrange(0, count):
        layout = BoardLayout.generate(size=size)
        board = layout.render()
        for row in xrange(0, size):
            for col in xrange(0, size):
                if board[row][col] != '-':
                    count_board[row][col] += 1

    print "Percentages Board"
    print "-----------------"

    # Print the board of percentages.
    print "  ",
    for i in xrange(0, size):
        print "  {}".format(chr(ord('A') + i)),
    print

    for row in xrange(0, size):
        print "%2d" % (row + 1),
        for space in count_board[row]:
            print "%3.0f" % (float(space) / float(count) * 100, ),
        print

    print
    print "Total Games Created: {}".format(count)
def do_genstats(args, config):
    count = args.count
    size = args.size

    # Create a board which contains a count of the number of time
    # a space was used.
    count_board = [[0] * size for i in range(size)]
    for i in xrange(0, count):
        layout = BoardLayout.generate(size=size)
        board = layout.render()
        for row in xrange(0, size):
            for col in xrange(0, size):
                if board[row][col] != '-':
                    count_board[row][col] += 1

    print "Percentages Board"
    print "-----------------"

    # Print the board of percentages.
    print "  ",
    for i in xrange(0, size):
        print "  {}".format(chr(ord('A') + i)),
    print

    for row in xrange(0, size):
        print "%2d" % (row + 1),
        for space in count_board[row]:
            print "%3.0f" % (float(space) / float(count) * 100,),
        print

    print
    print "Total Games Created: {}".format(count)
    def test_join_nonexistent_game(self):
        layout = BoardLayout.generate(self.test_ships)
        nonces = create_nonces(10)

        # Send join payload to tp
        join_req = create_join_payload('nonexistent_game', layout, nonces)
        self.validator.send(
            self.player_1.create_tp_process_request(join_req)
        )

        # give state back to tp

        self.send_state_to_tp('nonexistent_game')

        self.expect_invalid()
def do_fire(args, config):
    name = args.name
    column = args.column
    row = args.row

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    if name not in data['games']:
        raise BattleshipException(
            "no such game in local database: {}".format(name))

    client = BattleshipClient(base_url=url, keyfile=key_file, wait=args.wait)
    state = client.list_games()

    if name not in state:
        raise BattleshipException(
            "no such game: {}".format(name))
    state_game = state[name]

    reveal_space = None
    reveal_nonce = None

    if 'LastFireColumn' in state_game:
        last_col = ord(state_game['LastFireColumn']) - ord('A')
        last_row = int(state_game['LastFireRow']) - 1

        layout = BoardLayout.deserialize(data['games'][name]['layout'])
        nonces = data['games'][name]['nonces']

        reveal_space = layout.render()[last_row][last_col]
        reveal_nonce = nonces[last_row][last_col]

    response = client.fire(
        name=name,
        column=column,
        row=row,
        reveal_space=reveal_space,
        reveal_nonce=reveal_nonce)

    print(response)
def do_fire(args, config):
    name = args.name
    column = args.column
    row = args.row

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    if name not in data['games']:
        raise BattleshipException(
            "no such game in local database: {}".format(name))

    client = BattleshipClient(base_url=url, keyfile=key_file)
    state = client.get_all_store_objects()

    if name not in state:
        raise BattleshipException(
            "no such game: {}".format(name))
    state_game = state[name]

    reveal_space = None
    reveal_nonce = None

    if 'LastFireColumn' in state_game:
        last_col = ord(state_game['LastFireColumn']) - ord('A')
        last_row = int(state_game['LastFireRow']) - 1

        layout = BoardLayout.deserialize(data['games'][name]['layout'])
        nonces = data['games'][name]['nonces']

        reveal_space = layout.render()[last_row][last_col]
        reveal_nonce = nonces[last_row][last_col]

    client.fire(name=name,
                column=column,
                row=row,
                reveal_space=reveal_space,
                reveal_nonce=reveal_nonce)

    if args.wait:
        client.wait_for_commit()
def do_genstats(args, config):
    count = args.count
    size = args.size
    ships = ["AAAAA", "BBBB", "CCC", "DD", "DD", "SSS", "SSS"]
    # Create a board which contains a count of the number of time
    # a space was used.
    count_board = [[0] * size for i in range(size)]
    for i in range(0, count):
        layout = BoardLayout.generate(size=size, ships=ships)
        board = layout.render()
        for row in range(0, size):
            for col in range(0, size):
                if board[row][col] != '-':
                    count_board[row][col] += 1

    print("Percentages Board")
    print("-----------------")

    # Print the board of percentages.
    print("  ", end=' ')
    def test_fire_game_won(self):
        # Create test board
        layout = BoardLayout(10)
        layout.append(
            ShipPosition(text='AA', row=0, column=0, orientation='horizontal'))
        nonces = create_nonces(10)

        # Player 2 fires
        fire_req = \
            create_fire_payload('fire_game', '1', 'B', 'A', nonces[0][1])

        self.validator.send(
            self.player_2.create_tp_process_request(fire_req))

        target_board1 = [['?'] * 10 for _ in range(10)]
        target_board1[0][0] = 'H'

        self.send_state_to_tp('fire_game', {
            'Ships': ['AA'],
            'TargetBoard1': target_board1,
            'TargetBoard2': [['?'] * 10 for _ in range(10)],
            'Player1': self.public_key_1,
            'Player2': self.public_key_2,
            'HashedBoard1': layout.render_hashed(nonces),
            'HashedBoard2': layout.render_hashed(nonces),
            'State': 'P2-NEXT',
            'LastFireRow': '1',
            'LastFireColumn': 'B'
        }, self.player_2)

        target_board1[0][1] = 'H'

        self.update_state('fire_game', {
            'Ships': ['AA'],
            'TargetBoard1': target_board1,
            'TargetBoard2': [['?'] * 10 for _ in range(10)],
            'Player1': self.public_key_1,
            'Player2': self.public_key_2,
            'HashedBoard1': layout.render_hashed(nonces),
            'HashedBoard2': layout.render_hashed(nonces),
            'LastFireRow': '1',
            'LastFireColumn': 'B',
            'State': 'P1-WIN'
        }, self.player_2)

        self.expect_ok()
    def test_join_game_too_many_players(self):
        layout = BoardLayout.generate(self.test_ships)
        nonces = create_nonces(10)

        # Send join payload to tp
        join_req = create_join_payload('full_game', layout, nonces)
        self.validator.send(
            self.player_1.create_tp_process_request(join_req)
        )

        # give state back to tp

        self.send_state_to_tp('full_game', {
            'Ships': self.test_ships,
            'TargetBoard1': [['?'] * 10 for _ in range(10)],
            'TargetBoard2': [['?'] * 10 for _ in range(10)],
            'Player1': self.public_key_1,
            'Player2': self.public_key_2,
            'HashedBoard1': layout.render_hashed(nonces),
            'HashedBoard2': layout.render_hashed(nonces),
            'State': 'P1-NEXT'
        })

        self.expect_invalid()
def do_show(args, config):
    name = args.name

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    client = BattleshipClient(base_url=url, keyfile=key_file)
    state = client.list_games()

    if name not in state:
        raise BattleshipException('no such game: {}'.format(name))

    game = state[name]

    player1 = ''
    player2 = ''
    if 'Player1' in game:
        player1 = game['Player1']
    if 'Player2' in game:
        player2 = game['Player2']
    game_state = game['State']

    print("GAME:     : {}".format(name))
    print("PLAYER 1  : {}".format(player1))
    print("PLAYER 2  : {}".format(player2))
    print("STATE     : {}".format(game_state))

    # figure out the proper user's target board, given the public_key
    priv_filename = config.get('DEFAULT', 'key_file')
    if priv_filename.endswith(".priv"):
        public_key_filename = priv_filename[0:-len(".priv")] + ".pub"
    else:
        public_key_filename = priv_filename + ".pub"
    public_key_file = open(public_key_filename, mode='r')
    public_key = public_key_file.readline().rstrip('\n')

    if 'Player1' in game and public_key == game['Player1']:
        target_board_name = 'TargetBoard1'
    elif 'Player2' in game and public_key == game['Player2']:
        target_board_name = 'TargetBoard2'
    else:
        raise BattleshipException("Player hasn't joined game.")

    # figure out who fired last and who is calling do_show
    # to determine which board * is diplayed on to
    # show pending shot
    if 'LastFireRow' in game and 'LastFireColumn' in game:
        last_fire = (int(game['LastFireRow']) - 1,
                     int(ord(game['LastFireColumn'])) - ord('A'))
    else:
        last_fire = None

    if game_state == 'P1-NEXT' and target_board_name == 'TargetBoard1':
        # player 2 last shot and player 1 is looking
        will_be_on_target_board = False
    elif game_state == 'P1-NEXT' and target_board_name == 'TargetBoard2':
        # player 2 last shot and player 2 is looking
        will_be_on_target_board = True
    elif game_state == 'P2-NEXT' and target_board_name == 'TargetBoard1':
        # player 1 last shot and player 1 is looking
        will_be_on_target_board = True
    elif game_state == 'P2-NEXT' and target_board_name == 'TargetBoard2':
        # player 1 last shot and player 2 is looking
        will_be_on_target_board = False
    else:
        last_fire = None
        will_be_on_target_board = False

    if target_board_name in game:
        target_board = game[target_board_name]
        size = len(target_board)

        print()
        print("  Target Board")
        print_board(target_board,
                    size,
                    is_target_board=True,
                    pending_on_target_board=will_be_on_target_board,
                    last_fire=last_fire)

    if name in data['games']:
        layout = BoardLayout.deserialize(data['games'][name]['layout'])
        board = layout.render()
        size = len(board)

        print()
        print("  Secret Board")
        print_board(board,
                    size,
                    is_target_board=False,
                    pending_on_target_board=will_be_on_target_board,
                    last_fire=last_fire)
def do_show(args, config):
    name = args.name

    url = config.get('DEFAULT', 'url')
    key_file = config.get('DEFAULT', 'key_file')

    data = load_data(config)

    client = BattleshipClient(base_url=url, keyfile=key_file)
    state = client.get_all_store_objects()

    if name not in state:
        raise BattleshipException('no such game: {}'.format(name))

    game = state[name]

    player1 = ''
    player2 = ''
    if 'Player1' in game:
        player1 = game['Player1']
    if 'Player2' in game:
        player2 = game['Player2']
    game_state = game['State']

    print("GAME:     : {}".format(name))
    print("PLAYER 1  : {}".format(player1))
    print("PLAYER 2  : {}".format(player2))
    print("STATE     : {}".format(game_state))

    # figure out the proper user's target board, given the addr
    wif_filename = config.get('DEFAULT', 'key_file')
    if wif_filename.endswith(".wif"):
        addr_filename = wif_filename[0:-len(".wif")] + ".addr"
    else:
        addr_filename = wif_filename + ".addr"
    addr_file = file(addr_filename, mode='r')
    addr = addr_file.readline().rstrip('\n')

    if 'Player1' in game and addr == game['Player1']:
        target_board_name = 'TargetBoard1'
    elif 'Player2' in game and addr == game['Player2']:
        target_board_name = 'TargetBoard2'
    else:
        raise BattleshipException("Player hasn't joined game.")

    # figure out who fired last and who is calling do_show
    # to determine which board * is diplayed on to
    # show pending shot
    if 'LastFireRow' in game and 'LastFireColumn' in game:
        last_fire = (int(game['LastFireRow']) - 1,
                     int(ord(game['LastFireColumn'])) - ord('A'))
    else:
        last_fire = None

    if game_state == 'P1-NEXT' and target_board_name == 'TargetBoard1':
        # player 2 last shot and player 1 is looking
        will_be_on_target_board = False
    elif game_state == 'P1-NEXT' and target_board_name == 'TargetBoard2':
        # player 2 last shot and player 2 is looking
        will_be_on_target_board = True
    elif game_state == 'P2-NEXT' and target_board_name == 'TargetBoard1':
        # player 1 last shot and player 1 is looking
        will_be_on_target_board = True
    elif game_state == 'P2-NEXT' and target_board_name == 'TargetBoard2':
        # player 1 last shot and player 2 is looking
        will_be_on_target_board = False
    else:
        last_fire = None
        will_be_on_target_board = False

    if target_board_name in game:
        target_board = game[target_board_name]
        size = len(target_board)

        print()
        print("  Target Board")
        print_board(target_board, size, is_target_board=True,
                    pending_on_target_board=will_be_on_target_board,
                    last_fire=last_fire)

    if name in data['games']:
        layout = BoardLayout.deserialize(data['games'][name]['layout'])
        board = layout.render()
        size = len(board)

        print()
        print("  Secret Board")
        print_board(board, size, is_target_board=False,
                    pending_on_target_board=will_be_on_target_board,
                    last_fire=last_fire)