GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — develop (#14)
by Theo
01:55
created

ChessBoard.export()   D

Complexity

Conditions 8

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 8.0032

Importance

Changes 0
Metric Value
cc 8
c 0
b 0
f 0
dl 0
loc 35
rs 4
ccs 26
cts 27
cp 0.963
crap 8.0032
1
# pylint: disable=R0902
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
# disabling too many instance attributes for now.
3
# once I implement enpassant and castling,
4
# I shouldn't need some of the FEN attributes.
5 1
import json
6
7 1
from .. import standard_chess_json
8 1
from .base import Board
9 1
from ..piece import Piece
10
11 1
from ..movement import get_all_potential_end_locations
12 1
from .. import movement
13
14 1
map_fen_to_piece_name = {
15
    'k': "king",
16
    'q': "queen",
17
    'n': "knight",
18
    'b': "bishop",
19
    'r': "rook",
20
    'p': "pawn"
21
}
22
23
24 1
class ChessBoard(Board):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
25
26 1
    def __init__(self, existing_board=None):
27 1
        super().__init__(8, 8)
28 1
        self.pieces = []
29 1
        self.players = {}
30 1
        self.end_game = {}
31
32 1
        self.standard_chess = standard_chess_json
33
34 1
        if not existing_board:
35 1
            existing_board = self.load_json()
36
37 1
        self.initialize_board(existing_board)
38 1
        if existing_board and existing_board['players']['current'] == "Player 1":
39 1
            self.current_players_turn = "w"
40
        else:
41
            self.current_players_turn = "b"
42
43
        # FEN data I should take into account
44 1
        self.castling_opportunities = "KQkq"
45 1
        self.en_passant_target_square = "-"
46 1
        self.half_move_clock = 0
47 1
        self.full_move_number = 1
48
49 1
    def __getitem__(self, key):
50 1
        return self.board[key]
51
52 1
    def __setitem__(self, key, value):
53 1
        self.board[key] = value
54
55 1
    def __iter__(self):
56 1
        for key in self.board:
57 1
            yield key
58
59 1
    def __len__(self):
60 1
        return len(self.board)
61
62 1
    def generate_fen(self):
63
        """Generates a FEN representation of the board."""
64 1
        board = ""
65
        # FEN notation starts in the top left
66 1
        for row in range(self.rows - 1, -1, -1):
67 1
            num_missing = 0
68 1
            for column in range(0, self.columns):
69 1
                key = (row, column)
70 1
                piece = self[key]
71
72 1
                if piece:
73 1
                    prepend = ''
74 1
                    if num_missing:
75 1
                        prepend = str(num_missing)
76 1
                    board += prepend + repr(piece)
77 1
                    num_missing = 0
78
                else:
79 1
                    num_missing += 1
80 1
            if num_missing:
81 1
                board += str(num_missing)
82 1
            board += "/"
83
84 1
        other_info = " {cpt} {co} {epts} {hmc} {fmn}".format(cpt=self.current_players_turn,
85
                                                             co=self.castling_opportunities,
86
                                                             epts=self.en_passant_target_square,
87
                                                             hmc=self.half_move_clock,
88
                                                             fmn=self.full_move_number)
89 1
        fen = board[0:-1] + other_info
90 1
        return fen
91
92 1
    def import_fen_board(self, fen_board):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
93 1
        json_data = self.load_json()
94 1
        board_data, self.current_players_turn, self.castling_opportunities,\
95
            self.en_passant_target_square, self.half_move_clock,\
96
            self.full_move_number = fen_board.split(' ')
97 1
        rows = board_data.split('/')
98 1
        for row in range(self.rows - 1, -1, -1):
99 1
            fen_row = rows[7 - row]
100 1
            actual_column = 0
101 1
            for column in range(0, len(fen_row)):
102 1
                try:
103 1
                    num_missing = int(fen_row[actual_column])
104 1
                    for column in range(0, num_missing):
105 1
                        self[(row, actual_column)] = None
106 1
                        actual_column += 1
107 1
                except ValueError:
108 1
                    name = map_fen_to_piece_name[fen_row[actual_column].lower()]
109 1
                    color = "black" if fen_row[actual_column].islower() else "white"
110 1
                    moves = self.get_piece_moves(name, json_data)
111 1
                    self[(row, column)] = Piece(name, color, moves)
112 1
                    actual_column += 1
113
114 1
    def export(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
115 1
        json_data = {}
116 1
        json_data['pieces'] = {}
117 1
        for piece in self.pieces:
118 1
            json_data['pieces'][piece.kind] = {'moves': piece.moves}
119
120 1
        json_data['players'] = self.players
121 1
        if self.current_players_turn == 'w':
122 1
            json_data['players']['current'] = "Player 1"
123
        else:
124
            json_data['players']['current'] = "Player 2"
125
126 1
        map_color_to_name = {}
127 1
        json_board = {}
128 1
        for player in self.players:
129 1
            if player != 'current':
130 1
                map_color_to_name[self.players[player]['color']] = player
131 1
                json_board[player] = {}
132
133 1
        for location in self:
134 1
            piece = self[location]
135 1
            if piece:
136 1
                player = map_color_to_name[piece.color]
137 1
                if piece.kind in json_board[player]:
138 1
                    json_board[player][piece.kind].append({"position": list(location), "move_count": piece.move_count})
139
                else:
140 1
                    json_board[player][piece.kind] = [{"position": list(location), "move_count": piece.move_count}]
141
142 1
        json_data['board'] = json_board
143
144 1
        json_data['end_game'] = self.end_game
145
146 1
        print("export data is:")
147 1
        print(json_data)
148 1
        return json_data
149
150 1
    def initialize_board(self, json_data):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
151 1
        json_board = json_data['board']
152
153 1
        self.end_game = json_data['end_game']
154 1
        for player in ['Player 1', 'Player 2']:
155 1
            players_data = json_data['players']
156 1
            color = players_data[player]['color']
157
158 1
            self.players[player] = players_data[player]
159
160 1
            player_pieces = json_board[player]
161 1
            for piece in player_pieces:
162 1
                name = piece
163 1
                moves = self.get_piece_moves(name, json_data)
164 1
                a_piece = Piece(name, color, moves)
165 1
                a_piece.move_count = 0  # something... is this in json???
166 1
                self.pieces.append(a_piece)
167
168 1
                for position_moves_dict in player_pieces[piece]:
169 1
                    location = position_moves_dict['position']
170 1
                    a_piece.move_count = position_moves_dict['move_count']
171 1
                    self[tuple(location)] = a_piece
172
173 1
        if json_data['players']['current'] == "Player 1":
174 1
            self.current_players_turn = 'w'
175
        else:
176
            self.current_players_turn = 'b'
177
178 1
    def clear_board(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
179 1
        for location in self:
180 1
            self[location] = None
181
182 1
    @staticmethod
183
    def get_piece_moves(name, json_data):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
184 1
        return json_data['pieces'][name]['moves']
185
186 1
    def load_json(self):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
187 1
        filename = self.standard_chess
188 1
        data = None
189 1
        with open(filename) as data_file:
190 1
            data = json.load(data_file)
191
192 1
        return data
193
194 1
    def end_locations_for_piece_at_location(self, start_location):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
195 1
        piece = self[start_location]
196 1
        if not piece:
197
            return []
198 1
        player_direction = None
199 1
        for player in self.players:
200 1
            if piece.color == self.players[player]['color']:
201 1
                player_direction = self.players[player]['direction']
202 1
                break
203
204 1
        all_end_points = []
205 1
        for move in piece.moves:
206 1
            directions = move['directions']
207 1
            conditions = [getattr(movement, condition) for condition in move['conditions'] if hasattr(movement, condition)]
208 1
            ends = get_all_potential_end_locations(start_location, directions, self)
209 1
            for condition in conditions:
210
                # print("ends before condition: {} are: {}".format(condition, ends))
211 1
                ends = condition(self, start_location, directions, ends, player_direction)
212
                # print("ends after condition: {} are: {}".format(condition, ends))
213 1
            all_end_points += ends
214 1
        return all_end_points
215
216 1
    def move(self, start_location, end_location):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
217 1
        if self.is_valid_move(start_location, end_location):
218 1
            if self.current_players_turn == 'w':
219 1
                if self[start_location].color == 'black':
220
                    print('black trying to move, but whites turn')
221
                    return False
222 1
                self.current_players_turn = 'b'
223
            else:
224
                if self[start_location].color == 'white':
225
                    print('white trying to move, but blacks turn')
226
                    return False
227
                self.full_move_number += 1
228
                self.current_players_turn = 'w'
229 1
            print("is valid move")
230 1
            is_capture = self[end_location] is not None
231 1
            self[end_location] = self[start_location]
232 1
            self[start_location] = None
233 1
            self[end_location].move_count += 1
234 1
            if self[end_location].kind != "pawn" and not is_capture:
235 1
                self.half_move_clock += 1
236
            else:
237
                self.half_move_clock = 0
238 1
            return True
239 1
        print('is not valid move')
240 1
        return False
241
242 1
    def is_valid_move(self, start_location, end_location):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
243 1
        possible_moves = self.valid_moves(start_location)
244 1
        if end_location in possible_moves:
245 1
            return True
246 1
        return False
247
248 1
    def valid_moves(self, start_location):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
249 1
        return self.end_locations_for_piece_at_location(start_location)
250
251 1
    @property
252
    def board(self):
253
        return self._board
254