-
Notifications
You must be signed in to change notification settings - Fork 213
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #82 from ojhankit/chess
Chess
- Loading branch information
Showing
11 changed files
with
533 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
Binary file added
BIN
+3.13 KB
Algorithms_and_Data_Structures/BinarySearchTree/__pycache__/bst.cpython-312.pyc
Binary file not shown.
Binary file added
BIN
+623 Bytes
Algorithms_and_Data_Structures/BinarySearchTree/__pycache__/bstnode.cpython-312.pyc
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
from bstnode import BSTnode | ||
|
||
class BST: | ||
def __init__(self): | ||
self.root = None | ||
self.num_nodes = 0 | ||
|
||
def insert(self ,value:int) -> None: | ||
if self.root is None: | ||
newnode = BSTnode(value) | ||
self.root = newnode | ||
else: | ||
self.insert_helper(self.root ,value) | ||
self.num_nodes += 1 | ||
|
||
def insert_helper(self ,root:BSTnode ,value:int) -> None: | ||
if value < root.value: | ||
if root.leftPtr is None: | ||
root.leftPtr = BSTnode(value) | ||
else: | ||
self.insert_helper(root.leftPtr, value) | ||
else: | ||
if root.rightPtr is None: | ||
root.rightPtr = BSTnode(value) | ||
else: | ||
self.insert_helper(root.rightPtr, value) | ||
|
||
def search(self ,value:int) -> bool: | ||
temp_node = self.root | ||
while temp_node is not None: | ||
if temp_node.value == value: | ||
return True | ||
elif temp_node.value > value: | ||
temp_node = temp_node.leftPtr | ||
else: | ||
temp_node = temp_node.rightPtr | ||
return False | ||
|
||
def inorder(self) -> None: | ||
self.inorder_helper(self.root) | ||
|
||
def inorder_helper(self ,root:BSTnode) -> None: | ||
if root is not None: | ||
self.inorder_helper(root.leftPtr) | ||
print(root.value, end=' ') | ||
self.inorder_helper(root.rightPtr) | ||
|
||
def get_height(self): | ||
return self.height_helper(self.root) | ||
|
||
def height_helper(self, root: BSTnode) -> int: | ||
if root is None: | ||
return -1 | ||
else: | ||
left_height = self.height_helper(root.leftPtr) | ||
right_height = self.height_helper(root.rightPtr) | ||
return 1 + max(left_height, right_height) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
class BSTnode: | ||
|
||
def __init__(self ,value:int) -> None: | ||
self.value = value | ||
self.leftPtr = None | ||
self.rightPtr = None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
from bst import BST | ||
|
||
def main(): | ||
bst = BST() | ||
|
||
while True: | ||
print("\n" + "="*30) | ||
print("Binary Search Tree Menu") | ||
print("="*30) | ||
print("1. Insert a value") | ||
print("2. Search for a value") | ||
print("3. Display in-order traversal") | ||
print("4. Get tree height") | ||
print("5. Exit") | ||
print("="*30) | ||
|
||
try: | ||
choice = int(input("Enter your choice (1-5): ")) | ||
except ValueError: | ||
print("Invalid input. Please enter a number between 1 and 5.") | ||
continue | ||
|
||
if choice == 1: | ||
value = int(input("Enter the value to insert: ")) | ||
bst.insert(value) | ||
print(f"Value {value} inserted into the BST.") | ||
|
||
elif choice == 2: | ||
value = int(input("Enter the value to search: ")) | ||
found = bst.search(value) | ||
if found: | ||
print(f"Value {value} found in the BST.") | ||
else: | ||
print(f"Value {value} not found in the BST.") | ||
|
||
elif choice == 3: | ||
print("In-order traversal of the BST: ", end="") | ||
bst.inorder() | ||
print() | ||
|
||
elif choice == 4: | ||
height = bst.get_height() | ||
print(f"Height of the BST: {height}") | ||
|
||
elif choice == 5: | ||
print("Exiting program.") | ||
break | ||
|
||
else: | ||
print("Invalid choice. Please select a number between 1 and 5.") | ||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
__pycache__ | ||
test.py |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
from piece import Piece ,King ,Knight ,Queen ,Rook ,Bishop ,Pawn | ||
|
||
class Board: | ||
|
||
def __init__(self): | ||
#print("Board class constructor called") | ||
self.board = self.create_board() | ||
self.setup_pieces() | ||
|
||
def create_board(self): | ||
""" have to create a 8x8 matrix for the representation of chess_board """ | ||
chess_board = [] | ||
for _ in range(8): | ||
chess_board.append([None] * 8) | ||
|
||
return chess_board | ||
|
||
def setup_pieces(self): | ||
""" | ||
our board should look like :- | ||
R KN B Q KI B KN R | ||
P P P P P P P P | ||
. . . . . . . . | ||
. . . . . . . . | ||
. . . . . . . . | ||
. . . . . . . . | ||
P P P P P P P P | ||
R KN B Q KI B KN R | ||
Where R = Rook | ||
KN = Knight | ||
B = Bishop | ||
Q = Queen | ||
KI = King | ||
P = Pawn | ||
""" | ||
|
||
""" set up pawn """ | ||
for col in range(8): | ||
self.board[1][col] = Pawn('white') | ||
self.board[6][col] = Pawn('black') | ||
|
||
piece_order = [Rook ,Knight ,Bishop ,Queen ,King ,Bishop ,Knight ,Rook] | ||
|
||
""" setting up black piece """ | ||
for col ,piece in enumerate(piece_order): | ||
self.board[0][col] = piece('white') | ||
|
||
""" setting up white piece """ | ||
for col ,piece in enumerate(piece_order): | ||
self.board[7][col] = piece('black') | ||
|
||
def move_pieces(self ,start_position:tuple[int ,int] ,end_position:tuple[int ,int]) -> bool: | ||
|
||
row_initial ,col_initial = start_position[0],start_position[1] | ||
row_final ,col_final = end_position[0],end_position[1] | ||
|
||
piece = self.board[row_initial][col_initial] | ||
|
||
if piece is None: | ||
print("No piece at the given position") | ||
return False | ||
|
||
if piece.is_valid_move(start_position ,end_position ,self.board): | ||
target_piece = self.board[row_final][col_final] | ||
|
||
if target_piece is not None: | ||
if target_piece.color != piece.color: | ||
print(f"Capturing {target_piece.symbol()} at {end_position}") | ||
else: | ||
print("Invalid move: Cannot capture your own piece") | ||
return False | ||
|
||
# Move the piece to the new location | ||
self.board[row_final][col_final] = piece | ||
self.board[row_initial][col_initial] = None | ||
print(f"Moved {piece.symbol()} to {end_position}") | ||
return True | ||
|
||
else: | ||
print("Invalid move") | ||
return False | ||
|
||
def print_board(self): | ||
print(" ", end='') # Initial space before column labels | ||
for col in range(8): | ||
print(f" {col} ", end='') | ||
print() # Newline after column labels | ||
|
||
# Printing the board with row numbers | ||
for row_idx, row in enumerate(self.board): | ||
print(f"{row_idx} ", end='') # Print row numbers with space | ||
for piece in row: | ||
# Print the symbol for each piece or '.' if the spot is empty, each padded to 3 spaces | ||
print(f"{piece.symbol() if piece else '.'} ", end='') | ||
print() # Newline after each row | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
from piece import Piece ,Pawn ,Rook ,Bishop ,Queen ,King ,Knight | ||
from board import Board | ||
|
||
class Game: | ||
|
||
def __init__(self ,color): | ||
self.board = Board() | ||
self.current_color = color | ||
self.is_over = False | ||
|
||
def switch_turns(self): | ||
|
||
self.current_color = 'black' if self.current_color == "white" else "white" | ||
|
||
def is_checkmate(self ,color:str) -> bool: | ||
pass | ||
|
||
def is_in_check(self ,color:str) -> bool: | ||
|
||
king_position = None | ||
""" finding king's position """ | ||
for i in range(8): | ||
for j in range(8): | ||
piece = self.board.board[i][j] | ||
if piece is not None and isinstance(piece,King) and piece.color == color: | ||
king_position = (i,j) | ||
break | ||
|
||
opponent_color = 'black' if color == 'white' else 'white' | ||
for i in range(8): | ||
for j in range(8): | ||
piece = self.board.board[i][j] | ||
if piece is not None and piece.color == opponent_color: | ||
if piece.is_valid_move((i,j),king_position,self.board): | ||
return True # king is in check | ||
|
||
return False | ||
|
||
def play(self): | ||
|
||
while not self.is_over: | ||
self.board.print_board() | ||
print(f"{self.current_color.capitalize()} is playing") | ||
|
||
start_position = self.get_user_input("Enter the start position (row ,col)") | ||
if self.board.board[start_position[0]][start_position[1]] is not None: | ||
piece = self.board.board[start_position[0]][start_position[1]] | ||
print(f"{piece.color} {piece.__class__.__name__} selected") | ||
end_position = self.get_user_input("Enter the end position (row ,col)") | ||
|
||
if self.board.move_pieces(start_position ,end_position): | ||
if self.check_game_(self.current_color): | ||
self.is_over = True | ||
self.switch_turns() | ||
|
||
else: | ||
print("Invalid move.. Please Take Another move") | ||
|
||
def get_user_input(self, prompt: str) -> tuple[int, int]: | ||
"""take the input from user and convert to a tuple of integers.""" | ||
while True: | ||
try: | ||
user_input = input(prompt) | ||
row, col = map(int, user_input.split(",")) | ||
if 0 <= row < 8 and 0 <= col < 8: | ||
return (row, col) | ||
else: | ||
print("Invalid input.. Enter values between 0 and 7.") | ||
except ValueError: | ||
print("Invalid input format.. Use row,col format.") | ||
|
||
def check_game_(self ,color:str) -> bool: | ||
""" """ | ||
if self.is_checkmate(color): | ||
pass | ||
if self.is_in_check(color): | ||
print(f"{color} King is in check") | ||
return False | ||
|
||
|
||
if __name__ == "__main__": | ||
object = Game(color=input('Select color : black or white ')) | ||
object.play() |
Oops, something went wrong.