0% found this document useful (0 votes)
117 views17 pages

Python Chess Game Code Example

This Python program implements a graphical chess game using the Pygame library. It defines functions for displaying the chess board, pieces, and handling game events like moves. Color constants are defined for various chess board designs. The main screen allows the user to start a new game or load a saved game. Moves are checked for validity and the program can search ahead a few ply to evaluate moves.

Uploaded by

Baby SINS
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views17 pages

Python Chess Game Code Example

This Python program implements a graphical chess game using the Pygame library. It defines functions for displaying the chess board, pieces, and handling game events like moves. Color constants are defined for various chess board designs. The main screen allows the user to start a new game or load a saved game. Moves are checked for validity and the program can search ahead a few ply to evaluate moves.

Uploaded by

Baby SINS
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Computer

Science
Python Project

Submitted by: Submitted to:


Eshan Negi [Link] Jha
Class : XII-A

Board Roll No :
Certificate
Acknowledgement
import pygame, chess
from random import choice
from traceback import format_exc
from sys import stderr
from time import strftime
from copy import deepcopy
[Link]()
()
from tkinter import *
import os

# Designing window for registration

def register():
global register_screen
register_screen = Toplevel(main_screen)
register_screen.title("Register")
register_screen.geometry("300x250")

global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()

Label(register_screen, text="Please enter details below",


bg="yellow").pack()
Label(register_screen, text="").pack()
username_lable = Label(register_screen, text="Username * ")
username_lable.pack()
username_entry = Entry(register_screen, textvariable=username)
username_entry.pack()
password_lable = Label(register_screen, text="Password * ")
password_lable.pack()
password_entry = Entry(register_screen, textvariable=password,
show='*')
password_entry.pack()
Label(register_screen, text="").pack()
Button(register_screen, text="Register", width=10, height=1,
bg="yellow", command = register_user).pack()

# Designing window for login

def login():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Login")
login_screen.geometry("300x250")
Label(login_screen, text="Please enter details below to login").pack()
Label(login_screen, text="").pack()

global username_verify
global password_verify

username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry

Label(login_screen, text="Username * ").pack()


username_login_entry = Entry(login_screen,
textvariable=username_verify)
username_login_entry.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password * ").pack()
password_login_entry = Entry(login_screen,
textvariable=password_verify, show= '*')
password_login_entry.pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login", width=10, height=1, command =
login_verify).pack()

# Implementing event on register button

def register_user():

username_info = [Link]()
password_info = [Link]()

file = open(username_info, "w")


[Link](username_info + "\n")
[Link](password_info)
[Link]()

username_entry.delete(0, END)
password_entry.delete(0, END)

Label(register_screen, text="Registration Success", fg="green",


font=("calibri", 11)).pack()

# Implementing event on login button

def login_verify():
username1 = username_verify.get()
password1 = password_verify.get()
username_login_entry.delete(0, END)
password_login_entry.delete(0, END)

list_of_files = [Link]()
if username1 in list_of_files:
file1 = open(username1, "r")
verify = [Link]().splitlines()
if password1 in verify:
login_sucess()

else:
password_not_recognised()

else:
user_not_found()

# Designing popup for login success

def login_sucess():
global login_success_screen
login_success_screen = Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login Success").pack()
Button(login_success_screen, text="OK",
command=delete_login_success).pack()

# Designing popup for login invalid password

def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen = Toplevel(login_screen)
password_not_recog_screen.title("Success")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen, text="Invalid Password ").pack()
Button(password_not_recog_screen, text="OK",
command=delete_password_not_recognised).pack()

# Designing popup for user not found

def user_not_found():
global user_not_found_screen
user_not_found_screen = Toplevel(login_screen)
user_not_found_screen.title("Success")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen, text="User Not Found").pack()
Button(user_not_found_screen, text="OK",
command=delete_user_not_found_screen).pack()

# Deleting popups

def delete_login_success():
login_success_screen.destroy()

def delete_password_not_recognised():
password_not_recog_screen.destroy()

def delete_user_not_found_screen():
user_not_found_screen.destroy()

# Designing Main(first) window

def main_account_screen():
global main_screen
main_screen = Tk()
main_screen.geometry("300x250")
main_screen.title("Account Login")
Label(text="Select Your Choice", bg="yellow", width="300", height="2",
font=("Calibri", 13)).pack()
Label(text="").pack()
Button(text="Login", height="2", width="30", command = login).pack()
Label(text="").pack()
Button(text="Register", height="2", width="30",
command=register).pack()
main_screen.mainloop()

main_account_screen()

SQUARE_SIDE = 50
AI_SEARCH_DEPTH = 2

RED_CHECK = (240, 150, 150)


WHITE = (255, 255, 255)
BLUE_LIGHT = (140, 184, 219)
BLUE_DARK = (91, 131, 159)
GRAY_LIGHT = (240, 240, 240)
GRAY_DARK = (200, 200, 200)
CHESSWEBSITE_LIGHT = (212, 202, 190)
CHESSWEBSITE_DARK = (100, 92, 89)
LICHESS_LIGHT = (240, 217, 181)
LICHESS_DARK = (181, 136, 99)
LICHESS_GRAY_LIGHT = (164, 164, 164)
LICHESS_GRAY_DARK = (136, 136, 136)

BOARD_COLORS = [(GRAY_LIGHT, GRAY_DARK),


(BLUE_LIGHT, BLUE_DARK),
(WHITE, BLUE_LIGHT),
(CHESSWEBSITE_LIGHT, CHESSWEBSITE_DARK),
(LICHESS_LIGHT, LICHESS_DARK),
(LICHESS_GRAY_LIGHT, LICHESS_GRAY_DARK)]
BOARD_COLOR = choice(BOARD_COLORS)

BLACK_KING = [Link]('images/black_king.png')
BLACK_QUEEN = [Link]('images/black_queen.png')
BLACK_ROOK = [Link]('images/black_rook.png')
BLACK_BISHOP = [Link]('images/black_bishop.png')
BLACK_KNIGHT = [Link]('images/black_knight.png')
BLACK_PAWN = [Link]('images/black_pawn.png')
BLACK_JOKER = [Link]('images/black_joker.png')

WHITE_KING = [Link]('images/white_king.png')
WHITE_QUEEN = [Link]('images/white_queen.png')
WHITE_ROOK = [Link]('images/white_rook.png')
WHITE_BISHOP = [Link]('images/white_bishop.png')
WHITE_KNIGHT = [Link]('images/white_knight.png')
WHITE_PAWN = [Link]('images/white_pawn.png')
WHITE_JOKER = [Link]('images/white_joker.png')

CLOCK = [Link]()
CLOCK_TICK = 15

SCREEN = [Link].set_mode((8*SQUARE_SIDE, 8*SQUARE_SIDE),


[Link])
SCREEN_TITLE = 'Chess Game'

[Link].set_icon([Link]('images/chess_icon.ico'))
[Link].set_caption(SCREEN_TITLE)

def resize_screen(square_side_len):
global SQUARE_SIDE
global SCREEN
SCREEN = [Link].set_mode((8*square_side_len,
8*square_side_len), [Link])
SQUARE_SIDE = square_side_len

def print_empty_board():
[Link](BOARD_COLOR[0])
paint_dark_squares(BOARD_COLOR[1])

def paint_square(square, square_color):


col = [Link](square[0])
row = [Link](square[1])
[Link](SCREEN, square_color,
(SQUARE_SIDE*col,SQUARE_SIDE*row,SQUARE_SIDE,SQUARE_SIDE), 0)

def paint_dark_squares(square_color):
for position in chess.single_gen(chess.DARK_SQUARES):
paint_square(chess.bb2str(position), square_color)

def get_square_rect(square):
col = [Link](square[0])
row = [Link](square[1])
return [Link]((col*SQUARE_SIDE, row*SQUARE_SIDE),
(SQUARE_SIDE,SQUARE_SIDE))

def coord2str(position, color=[Link]):


if color == [Link]:
file_index = int(position[0]/SQUARE_SIDE)
rank_index = 7 - int(position[1]/SQUARE_SIDE)
return [Link][file_index] + [Link][rank_index]
if color == [Link]:
file_index = 7 - int(position[0]/SQUARE_SIDE)
rank_index = int(position[1]/SQUARE_SIDE)
return [Link][file_index] + [Link][rank_index]

def print_board(board, color=[Link]):


if color == [Link]:
printed_board = board
if color == [Link]:
printed_board = chess.rotate_board(board)

print_empty_board()

if chess.is_check(board, [Link]):
paint_square(chess.bb2str(chess.get_king(printed_board,
[Link])), RED_CHECK)
if chess.is_check(board, [Link]):
paint_square(chess.bb2str(chess.get_king(printed_board,
[Link])), RED_CHECK)

for position in chess.colored_piece_gen(printed_board, [Link],


[Link]):
[Link]([Link](BLACK_KING,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_QUEEN,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_ROOK,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_BISHOP,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_KNIGHT,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_PAWN,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](BLACK_JOKER,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))

for position in chess.colored_piece_gen(printed_board, [Link],


[Link]):
[Link]([Link](WHITE_KING,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_QUEEN,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_ROOK,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_BISHOP,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_KNIGHT,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_PAWN,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))
for position in chess.colored_piece_gen(printed_board, [Link],
[Link]):
[Link]([Link](WHITE_JOKER,
(SQUARE_SIDE,SQUARE_SIDE)), get_square_rect(chess.bb2str(position)))

[Link]()

def set_title(title):
[Link].set_caption(title)
[Link]()

def make_AI_move(game, color):


set_title(SCREEN_TITLE + ' - Calculating move...')
new_game = chess.make_move(game, chess.get_AI_move(game,
AI_SEARCH_DEPTH))
set_title(SCREEN_TITLE)
print_board(new_game.board, color)
return new_game

def try_move(game, attempted_move):


for move in chess.legal_moves(game, game.to_move):
if move == attempted_move:
game = chess.make_move(game, move)
return game

def play_as(game, color):


run = True
ongoing = True
joker = 0

try:
while run:
[Link](CLOCK_TICK)
print_board([Link], color)

if chess.game_ended(game):
set_title(SCREEN_TITLE + ' - ' + chess.get_outcome(game))
ongoing = False

if ongoing and game.to_move == chess.opposing_color(color):


game = make_AI_move(game, color)

if chess.game_ended(game):
set_title(SCREEN_TITLE + ' - ' + chess.get_outcome(game))
ongoing = False

for event in [Link]():


if [Link] == [Link]:
run = False

if [Link] == [Link]:
leaving_square = coord2str([Link], color)

if [Link] == [Link]:
arriving_square = coord2str([Link], color)

if ongoing and game.to_move == color:


move = (chess.str2bb(leaving_square),
chess.str2bb(arriving_square))
game = try_move(game, move)
print_board([Link], color)

if [Link] == [Link]:
if [Link] == pygame.K_ESCAPE or [Link] == 113:
run = False
if [Link] == 104 and ongoing: # H key
game = make_AI_move(game, color)
if [Link] == 117: # U key
game = chess.unmake_move(game)
game = chess.unmake_move(game)
set_title(SCREEN_TITLE)
print_board([Link], color)
ongoing = True
if [Link] == 99: # C key
global BOARD_COLOR
new_colors = deepcopy(BOARD_COLORS)
new_colors.remove(BOARD_COLOR)
BOARD_COLOR = choice(new_colors)
print_board([Link], color)
if [Link] == 112 or [Link] == 100: # P or D key
print(game.get_move_list() + '\n')
print('\n'.join(game.position_history))
if [Link] == 101: # E key
print('eval = ' +
str(chess.evaluate_game(game)/100))
if [Link] == 106: # J key
joker += 1
if joker == 13 and chess.get_queen([Link],
color):
queen_index =
chess.bb2index(chess.get_queen([Link], color))
[Link][queen_index] = color|[Link]
print_board([Link], color)

if [Link] == [Link]:
if SCREEN.get_height() != event.h:
resize_screen(int(event.h/8.0))
elif SCREEN.get_width() != event.w:
resize_screen(int(event.w/8.0))
print_board([Link], color)
except:
print(format_exc(), file=stderr)
bug_file = open('bug_report.txt', 'a')
bug_file.write('----- ' + strftime('%x %X') + ' -----\n')
bug_file.write(format_exc())
bug_file.write('\nPlaying as WHITE:\n\t' if color == [Link]
else '\nPlaying as BLACK:\n\t')
bug_file.write(game.get_move_list() + '\n\t')
bug_file.write('\n\t'.join(game.position_history))
bug_file.write('\n-----------------------------\n\n')
bug_file.close()

def play_as_white(game=[Link]()):
return play_as(game, [Link])

def play_as_black(game=[Link]()):
return play_as(game, [Link])

def play_random_color(game=[Link]()):
color = choice([[Link], [Link]])
play_as(game, color)

# [Link] = True
play_random_color()
Output

You might also like