Affichage des articles dont le libellé est Python. Afficher tous les articles
Affichage des articles dont le libellé est Python. Afficher tous les articles

Python Wooden Chess Board

How To Create a Wooden Chessboard in Python Using Tkinter

How To Create a Wooden Chessboard in Python Using Tkinter


In this Python Tutorial we will see How to Create a wooden chess board using Python's built-in Tkinter library.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter (GUI).
- VS Editor.






Project Source Code:




import tkinter as tk
import random
import math

class WoodenChessboard:
def __init__(self, root):
"""
Initialize the chess board application
Parameters:
root: The main Tkinter window
"""
self.root = root
self.root.title("Modern Chess Board")
# Colors for the board
self.light_square_color = "#F0D9B5" # Light cream color
self.dark_square_color = "#B58863" # Medium brown
self.border_color = "#3E2723" # Dark chocolate brown
self.text_color = "#FFFFFF" # White text for better visibility
# Board dimensions
self.square_size = 70 # Size of each square in pixels
self.board_size = 8 * self.square_size # Total board size (8x8 squares)
self.padding = 30 # Border width around the board
# Set up the canvas with padding for borders
# Canvas is the drawing area where we'll create our chess board
self.canvas = tk.Canvas(
root,
width=self.board_size + 2 * self.padding,
height=self.board_size + 2 * self.padding,
bg=self.border_color
)
self.canvas.pack(padx=10, pady=10)
# Draw the border with wood texture
self.draw_wooden_border()
# Draw the chess board squares and coordinates
self.draw_board()
def draw_wooden_border(self):
"""
Draw a wooden border with grain texture around the chess board
"""
# Calculate total width and height including border
outer_width = self.board_size + 2 * self.padding
outer_height = self.board_size + 2 * self.padding
# Draw border background
self.canvas.create_rectangle(
0, 0, outer_width, outer_height,
fill=self.border_color, outline=""
)
# Create wood grain effect with different shades of brown
grain_colors = ["#3E2723", "#4E342E", "#5D4037"]
# Draw horizontal grain lines for top and bottom borders
for y in range(0, self.padding):
# Choose a random color variation for each line
color = random.choice(grain_colors)
# Add random waviness to make the grain look natural
waviness = random.randint(0, 3)
thickness = random.randint(1, 2)

# Top border grain
y_pos = y
pts = []
# Create wavy points for the line
for x in range(0, outer_width, 5):
wave = math.sin(x/20) * waviness
pts.extend([x, y_pos + wave])
if pts:
self.canvas.create_line(pts, fill=color, width=thickness, smooth=True)
# Bottom border grain (mirror of top)
y_pos = outer_height - y
pts = []
for x in range(0, outer_width, 5):
wave = math.sin(x/20) * waviness
pts.extend([x, y_pos + wave])
if pts:
self.canvas.create_line(pts, fill=color, width=thickness, smooth=True)
# Draw vertical grain lines for left and right borders
for x in range(0, self.padding):
color = random.choice(grain_colors)
waviness = random.randint(0, 3)
thickness = random.randint(1, 2)
# Left border grain
x_pos = x
pts = []
for y in range(0, outer_height, 5):
wave = math.sin(y/20) * waviness
pts.extend([x_pos + wave, y])
if pts:
self.canvas.create_line(pts, fill=color, width=thickness, smooth=True)
# Right border grain (mirror of left)
x_pos = outer_width - x
pts = []
for y in range(0, outer_height, 5):
wave = math.sin(y/20) * waviness
pts.extend([x_pos + wave, y])
if pts:
self.canvas.create_line(pts, fill=color, width=thickness, smooth=True)
def draw_board(self):
"""
Draw the chess board with squares and coordinate labels
"""
# Draw file labels (columns: a-h)
for i in range(8):
file_label = chr(97 + i) # ASCII: 'a' is 97, so we get 'a' through 'h'
# Bottom row labels
self.canvas.create_text(
self.padding + i * self.square_size + self.square_size // 2,
self.padding + self.board_size + 15,
text=file_label,
fill=self.text_color,
font=("Arial", 12, "bold")
)

# Top row labels
self.canvas.create_text(
self.padding + i * self.square_size + self.square_size // 2,
self.padding - 15,
text=file_label,
fill=self.text_color,
font=("Arial", 12, "bold")
)
# Draw rank labels (rows: 1-8)
for i in range(8):
rank_label = str(8 - i) # Count down from 8 to 1 (chess notation)
# Left side labels
self.canvas.create_text(
self.padding - 15,
self.padding + i * self.square_size + self.square_size // 2,
text=rank_label,
fill=self.text_color,
font=("Arial", 12, "bold")
)
# Right side labels
self.canvas.create_text(
self.padding + self.board_size + 15,
self.padding + i * self.square_size + self.square_size // 2,
text=rank_label,
fill=self.text_color,
font=("Arial", 12, "bold")
)
# Draw all 64 squares of the chess board
for row in range(8):
for col in range(8):
# Determine if this is a light or dark square
# If row+col is even, it's a light square; if odd, it's dark
is_light = (row + col) % 2 == 0
base_color = self.light_square_color if is_light else self.dark_square_color
# Calculate the position of the square on the canvas
x1 = self.padding + col * self.square_size
y1 = self.padding + row * self.square_size
x2 = x1 + self.square_size
y2 = y1 + self.square_size
# Create the square
square_id = self.canvas.create_rectangle(
x1, y1, x2, y2,
fill=base_color,
outline="", # No outline for a cleaner look
tags=f"square_{row}_{col}" # Tag to identify the square later if needed
)
# Add subtle wood grain texture to each square
self.add_wood_grain(x1, y1, x2, y2, is_light)
def add_wood_grain(self, x1, y1, x2, y2, is_light):
"""
Add subtle wood grain texture to a square
Parameters:
x1, y1: Top-left corner coordinates
x2, y2: Bottom-right corner coordinates
is_light: Boolean indicating if it's a light square
"""
if is_light:
# Light square grain (vertical lines with slight variation)
grain_color = "#E5C99E" # Slightly darker than the light square
grain_spacing = 4 # Space between grain lines

for i in range(int(x1) + 2, int(x2), grain_spacing):
# Add randomness to make grain look natural
waviness = random.randint(0, 2)
thickness = random.choice([1, 1, 2]) # Mostly thin lines

# Create a wavy line for the grain effect
points = []
for y in range(int(y1), int(y2), 5):
wave = math.sin(y/10) * waviness
points.extend([i + wave, y])

if points:
self.canvas.create_line(
points,
fill=grain_color,
width=thickness,
smooth=True
)
else:
# Dark square grain (more subtle)
grain_color = "#A07855" # Slightly lighter than the dark square
grain_spacing = 6

for i in range(int(x1) + 3, int(x2), grain_spacing):
waviness = random.randint(0, 1)
# Create subtle grain lines
points = []
for y in range(int(y1), int(y2), 10):
wave = math.sin(y/15) * waviness
points.extend([i + wave, y])

if points:
self.canvas.create_line(
points,
fill=grain_color,
width=1,
smooth=True
)



# Run the application
if __name__ == "__main__":
root = tk.Tk()
# Configure the window
root.configure(bg="#2C2C2C") # Dark background for modern look
# Create the chess board
app = WoodenChessboard(root)
# Start the application
root.mainloop()



The Final Result:








Python Memory Game Source Code

How To Create Memory Game in Python Using Tkinter

How To Create Memory Game in Python Using Tkinter


In this Python Tutorial we will see How to Create a Memory Game (card-matching game) with smooth animations, multiple difficulty levels, and a dark theme interface.

The Game Features:
- Multiple Difficulty Levels: 4x4 (16 cards, 8 pairs), 4x5 (20 cards, 10 pairs), and 5x6 grid sizes (30 cards, 15 pairs).
Card Matching: Automatic pair detection.
Move counter and timerThe game tracks moves, elapsed time, and provides detailed performance statistics.

What We Are Gonna Use In This Project:

- Python Programming Language.
- VS Editor.




if you want the source code click on the download button below




Project Source Code:


    
     - Create frame for cards.
     

def create_game_grid(self):
# Create frame to hold all cards
self.cards_frame = tk.Frame(self.game_frame, bg=self.colors['bg'])
# Center the grid in the game area
self.cards_frame.pack(expand=True)

# Initialize cards list and get symbol pairs
self.cards = [] # Empty list to store card widgets

# Get grid dimensions for current difficulty
rows, cols = self.difficulty_levels[self.current_difficulty]["grid"]
# Double the symbols list for pairs
symbols = self.difficulty_levels[self.current_difficulty]["symbols"] * 2

# Randomly shuffle symbols to place them on the grid
random.shuffle(symbols)
# Store shuffled symbols for later reference
self.symbols = symbols

# Create cards in grid
for i in range(rows): # Loop through each row
for j in range(cols): # Loop through each column in current row
card_idx = i*cols+j # Calculate linear index from row and column

# Create card canvas
# Create canvas with fixed size And Set background And remove border
card = tk.Canvas(self.cards_frame, width=80, height=100,
bg=self.colors['card_bg'], highlightthickness=0)
# Position card in grid with spacing
card.grid(row=i, column=j, padx=5, pady=5)
# Bind click event
card.bind("<Button-1>", lambda e, idx=card_idx: self.on_card_click(idx))

# Create card back (visible initially)
# Create card shape And Add colored border
card.create_rectangle(5, 5, 75, 95, fill=self.colors['card_bg'],
outline=self.colors['card_fg'], width=2)
# Add question mark and Set text color
card.create_text(40, 50, text="?", font=("Helvetica", 24, "bold"),
fill=self.colors['card_fg'])

# Create card front (hidden initially)
# Create card shape
# Add colored border
# Hide initially and add tag for later reference
card.create_rectangle(5, 5, 75, 95, fill=self.colors['card_fg'],
outline=self.colors['card_bg'], width=2,
state='hidden', tags=('front',))
# Add symbol text
# Use bold font for symbol
# Set text color
# Hide initially and add tag
card.create_text(40, 50, text=self.symbols[card_idx],
font=("Helvetica", 24, "bold"),
fill=self.colors['card_bg'],
state='hidden', tags=('symbol',))

self.cards.append(card) # Add card to list for later reference



    
     - Handles click events on cards.
     

def on_card_click(self, idx):
# Start timer on first click
if self.start_time is None: # If this is the first click of the game
self.start_time = time.time() # Record start time
self.update_time() # Start timer updates

# Ignore invalid clicks
if idx in self.revealed or idx in self.matched_cards or len(self.revealed) == 2:
# Skip if card is already revealed, matched, or 2 cards are already flipped
return

# Reveal the clicked card
self.reveal_card(idx) # Show the card face
self.revealed.append(idx) # Add to list of revealed cards

# If two cards are revealed, check for a match
if len(self.revealed) == 2: # When two cards have been flipped
self.moves += 1 # Increment move counter
self.moves_label.config(text=f"Moves: {self.moves}") # Update moves display
self.master.after(500, self.check_match) # schedule match check after a delay


    
    
     - Reveal and Hide Cards


def reveal_card(self, idx):
card = self.cards[idx] # Get the card canvas widget
card.itemconfig('front', state='normal') # Show the card front
card.itemconfig('symbol', state='normal') # Show the symbol

def hide_card(self, idx):
card = self.cards[idx] # Get the card canvas widget
card.itemconfig('front', state='hidden') # Hide the card front
card.itemconfig('symbol', state='hidden') # Hide the symbol



     - Method to check for a match between flipped cards.


def check_match(self):
idx1, idx2 = self.revealed # Get indices of the two revealed cards
if self.symbols[idx1] == self.symbols[idx2]: # If symbols match
# Match found
self.matched_pairs += 1 # Increment matched pairs counter
self.matched_cards.extend([idx1, idx2]) # Add both cards to matched list

# Highlight matched cards
for idx in [idx1, idx2]: # For each matched card
card = self.cards[idx] # Get card widget
# Change to green color to indicate match
card.itemconfig('front', fill="#8bc34a")

# Check if game is over
if self.matched_pairs == len(self.symbols) // 2: # If all pairs are found
# Schedule game over screen after delay
self.master.after(500, self.game_over)

else: # If symbols don't match
# No match
self.hide_card(idx1) # Flip first card back
self.hide_card(idx2) # Flip second card back
self.revealed.clear() # Clear the revealed cards list for next move


    
     - Start a New Game.

def new_game(self):
# Reset game state
self.game_solved = False # Reset game solved flag
self.revealed.clear() # Clear revealed cards list
self.matched_cards.clear() # Clear matched cards list
self.matched_pairs = 0 # Reset matched pairs counter
self.moves = 0 # Reset moves counter
self.start_time = None # Reset start time

# Reset labels
self.moves_label.config(text="Moves: 0") # Reset moves display
self.time_label.config(text="Time: 0:00") # Reset time display

# Recreate the game grid
self.cards_frame.destroy() # Remove old card grid
self.create_game_grid() # Create new shuffled grid


    

     - Method to display the congratulations dialog when the game is won.


def game_over(self):
self.game_solved = True # Mark game as completed
elapsed_time = int(time.time() - self.start_time) # Calculate total game time
minutes, seconds = divmod(elapsed_time, 60) # Convert to minutes and seconds

# Create game over window
game_over_window = tk.Toplevel(self.master) # Create new popup window
game_over_window.title("Game Over") # Set window title
game_over_window.geometry("350x350") # Set window size
game_over_window.configure(bg=self.colors['gameover_bg']) # Set background
game_over_window.grab_set() # Make window modal
game_over_window.transient(self.master) # Set as transient to main window

# Center the game over window on screen
x = self.master.winfo_x() + (self.master.winfo_width() // 2) - (350 // 2)
y = self.master.winfo_y() + (self.master.winfo_height() // 2) - (350 // 2)
game_over_window.geometry(f"+{x}+{y}")

# Create congratulations label
tk.Label(game_over_window, text="Congratulations!",
font=("Helvetica", 28, "bold"),
bg=self.colors['gameover_bg'], fg=self.colors['text']).pack(pady=(20, 30))

# Create stats frame
stats_frame = tk.Frame(game_over_window, bg=self.colors['gameover_bg'])
stats_frame.pack(pady=(0, 30)) # Add padding below frame

# Display stats
        # Show difficulty level
self.create_stat_label(stats_frame, "Difficulty", self.current_difficulty)
        # Show total moves
self.create_stat_label(stats_frame, "Moves", str(self.moves))
        # Show total time
self.create_stat_label(stats_frame, "Time", f"{minutes}:{seconds:02d}")
# Play again button
play_again_button = tk.Button(game_over_window, text="Play Again",
font=self.custom_font,
bg=self.colors['button_bg'], fg=self.colors['button_fg'],
relief=tk.FLAT,
command=lambda: [game_over_window.destroy(), self.new_game()])
play_again_button.pack(pady=20) # Add padding around button

# Add hover effect to play again button
play_again_button.bind("<Enter>",
            lambda e: e.widget.config(bg="#5dbb5e")) # Lighten on hover
play_again_button.bind("<Leave>",
            lambda e: e.widget.config(bg=self.colors['button_bg'])) # Restore on leave




The Final Result:

Python Memory Game Source Code

Python Memory Game

Python Memory Game Using Tkinter


if you want the full source code click on the download button below




disclaimer: you will get the source code, and to make it work in your machine is your responsibility and to debug any error/exception is your responsibility this project is for the students who want to see an example and read the code not to get and run.





Python Tkinter Line Chart

How to Create a Line Chart In Python Tkinter

How to Create a Line Chart In Python Tkinter


In this Python tutorial we will create a line chart using the Tkinter library for the graphical user interface. 
We will make a GUI application that displays a line chart with labeled axes and data points. 
It uses the tkinter library to draw the chart, which includes grid lines, labels, and a title. 

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:


import tkinter as tk

class LineChart(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.padding = 30
self.label_padding = 40
self.axis_label_padding = 20
self.max_vertical_labels = 5
self.max_horizontal_labels = 5

self.vertical_labels = ["0", "25", "50", "75", "100"]
self.horizontal_labels = ["Label 1", "Label 2", "Label 3", "Label 4",
        "Label 5"]

self.draw_chart()


def draw_chart(self):
# Calculate canvas dimensions and starting points
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
x_start = self.padding + self.label_padding + self.axis_label_padding
y_start = height - self.padding - self.label_padding
x_end = width - self.padding
y_end = self.padding + self.label_padding

# Calculate step size for vertical and horizontal labels
y_step = (y_start - y_end) / (self.max_vertical_labels - 1)
x_step = (x_end - x_start) / (self.max_horizontal_labels - 1)

# Draw vertical labels
for i in range(self.max_vertical_labels):
y = y_start - i * y_step
self.draw_vertical_label(self.vertical_labels[i], self.padding / 2, y)

# Draw horizontal labels
for i in range(self.max_horizontal_labels):
x = x_start + i * x_step
self.draw_horizontal_label(self.horizontal_labels[i], x,
            height - (self.padding / 2))

# Sample data
data = [50, 90, 30, 80, 10]
max_value = max(data)

# Draw the rectangle representing the chart area
self.create_rectangle(x_start, y_end, x_end, y_start, fill="white",
        outline="black")

# Draw horizontal grid lines
y_grid_count = len(self.horizontal_labels)
for i in range(y_grid_count):
y = y_start - i * y_step
self.create_line(x_start, y, x_end, y, fill="black")
# Draw vertical grid lines
x_grid_count = len(self.vertical_labels)
for i in range(x_grid_count):
x = x_start + i * x_step
self.create_line(x, y_end, x, y_start, fill="black")

# Draw data points and connecting lines
for i in range(len(data)):
# Calculate the x and y coordinates for the current data point
x = x_start + i * x_step
y = y_start - (data[i] / 100) * (y_start - y_end)
# Draw a circular data point at the calculated coordinates
self.create_oval(x-10, y-10, x+10, y+10, fill="red")

# Draw a connecting line between the current data point
            # and the previous one
if i > 0:
# Calculate the x and y coordinates for the previous data point
prev_x = x_start + (i - 1) * x_step
prev_y = y_start - (data[i - 1] / 100) * (y_start - y_end)
# Draw a line connecting the previous and current data points
self.create_line(prev_x, prev_y, x, y, width=2, fill="blue")


chart_title = "Chart Title"
self.create_text(width / 2, self.padding, text=chart_title,
            font=("Arial", 20, "bold"), fill="yellow")




def draw_vertical_label(self, label, x, y):
self.create_text(x + 30, y, text=label, fill="#ecf0f1",
        font=("Arial", 10, "bold"))
def draw_horizontal_label(self, label, x, y):
self.create_text(x, y, text=label, fill="#ecf0f1", font=("Arial", 10, "bold"))



class LineChartApp(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.line_chart = LineChart(self, width=800, height=600, background="#2c3e50")
self.line_chart.pack()


if __name__ == "__main__":
root = tk.Tk()
root.title("Line Chart")
app = LineChartApp(root)
root.mainloop()



The Final Result:

Python Tkinter Line Chart