Coding_knowledge
81.6K subscribers
65 photos
8 videos
587 files
227 links
💡 Your Coding Journey Starts Here!

Get free courses, coding resources, internships, job updates & much more.
Stay ahead in tech with us! ❤️🚀


Join our WhatsApp group👇
https://whatsapp.com/channel/0029Vaa7CVhCRs1rxJzy1n3D
Download Telegram
Introduction:
The “Binary-Decimal Converter” Python project is an ideal starting point for individuals venturing into the world of programming, especially those who are new to Python. This project introduces the basics of graphical user interface (GUI) development using the tkinter library while offering a practical application in the form of a number conversion tool.

The project is structured intuitively, featuring clear buttons to select the conversion direction: “Decimal to Binary” and “Binary to Decimal”. These buttons act as the gateway to initiate the conversion process. The interface further comprises an input field where users can enter the number they wish to convert, followed by a “Convert” button that triggers the conversion calculation. Upon conversion, the result is displayed in an output label, providing immediate feedback.

One remarkable aspect of the project is its error handling. The system gracefully manages unexpected inputs, such as non-numeric characters or invalid binary digits, ensuring that the user experience remains frustration-free. import tkinter as tk







Code:-

def decimal_to_binary():
try:
decimal_num = int(input_field.get())
binary_num = bin(decimal_num).replace("0b", "")
output_label.config(text=f"Binary: {binary_num}")
except ValueError:
output_label.config(text="Invalid input. Please enter a decimal number.")

def binary_to_decimal():
try:
binary_num = input_field.get()
decimal_num = int(binary_num, 2)
output_label.config(text=f"Decimal: {decimal_num}")
except ValueError:
output_label.config(text="Invalid input. Please enter a valid binary number.")

def clear_output():
output_label.config(text="")

root = tk.Tk()
root.title("Binary-Decimal Converter")

menu_frame = tk.Frame(root)
menu_frame.pack()

decimal_to_binary_button = tk.Button(menu_frame, text="Decimal to Binary", command=decimal_to_binary)
decimal_to_binary_button.pack(side=tk.LEFT)

binary_to_decimal_button = tk.Button(menu_frame, text="Binary to Decimal", command=binary_to_decimal)
binary_to_decimal_button.pack(side=tk.LEFT)

clear_button = tk.Button(root, text="Clear", command=clear_output)
clear_button.pack()

input_field = tk.Entry(root)
input_field.pack()

convert_button = tk.Button(root, text="Convert", command=lambda: None) # Placeholder for now
convert_button.pack()

output_label = tk.Label(root, text="", pady=10)
output_label.pack()

root.mainloop().







Explanation:
Importing the Library:

At the beginning, we’re telling Python to use a special toolbox of code called tkinter. It’s like a kit that helps us make windows and buttons in our program.

Functions for Conversion:

We define two functions:

decimal_to_binary(): This function takes a regular number (decimal) and turns it into a binary number. For example, it changes 10 to “1010”.

binary_to_decimal(): This function takes a binary number and turns it into a regular number. So, “1010” becomes 10.

Clearing Output:

We also have a function called clear_output(). This one just cleans up the space where the result appears.

Creating the Window:

We create the main window (the program’s screen) and give it a name, “Binary-Decimal Converter”.

Buttons for Conversion:

We make a little section at the top with buttons: “Decimal to Binary” and “Binary to Decimal”. These buttons will help us choose what kind of conversion we want to do.

Input Field:

Then we create a spot where you can type in a number. It’s like a text box.

Convert Button:

Next is a “Convert” button. Right now, it doesn’t do anything, but we’ll make it work soon.

Output Label:

Below that, there’s a spot where the result will show up. It starts out empty.

Putting Everything Together:

The root.mainloop() part keeps the window open. It’s like saying, “Hey, computer, show this window and let us click buttons and type things.”
👍7🔥21
Introduction:
tkinter is a GUI library provided by Python to create GUI applications. In this project, with the help of this library, we are going to build up the notepad, a text editor. The notepad will have two main menu items: File & edit. The functionalities of these menu items will also be there.

Explanation:
First of all, we will import the tkinter library. With this, we will also import the “filedailog” module from tkinter which will provide the classes and factory functions for creating file selection windows.

Now, we will initiate a class named “Notepad ” by using the “class” keyword. During this process, we will pass the parameter as “tk. Tk” which will create the root object for our GUI application. Under this, we will define a “__init__” constructor with self,*args,**kwargs as parameters.

Under this constructor, we will define the title by using “.title” and create a Text widget with the help of the “.Text()” method and will make this widget fill the entire frame with the “.pack()” method.

For the notepad to show the menu bar we will create the menu widget with the help of “.Menu()”.

The functionalities provided by the File menu in this project will be: New, Open, save and exit.

and the functionalities provided by the edit menu will be: cut, copy, and paste

The following options will be created by using the “.add_cascade()” method. This method will create a new hierarchical menu by associating the given menu with the parent menu. While doing so, we will pass the user-defined functions which will carry the particular functionality, under the “command” parameter. By this, both main menu items will get created.



Code-:

import tkinter as tk
from tkinter import filedialog

class Notepad(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)

# Set the title for the notepad
self.title("Notepad")

# Create a text widget
self.text = tk.Text(self, wrap="word")
self.text.pack(side="top", fill="both", expand=True)

# Create a menu bar
self.menu = tk.Menu(self)
self.config(menu=self.menu)

# Create a file menu
file_menu = tk.Menu(self.menu)
self.menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.quit)

# Create an edit menu
edit_menu = tk.Menu(self.menu)
self.menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Cut", command=self.cut)
edit_menu.add_command(label="Copy", command=self.copy)
edit_menu.add_command(label="Paste", command=self.paste)

def new_file(self):
self.text.delete("1.0", "end")
self.title("Notepad")

def open_file(self):
file = filedialog.askopenfile(parent=self, mode="rb", title="Open a file")
if file:
contents = file.read()
self.text.delete("1.0", "end")
self.text.insert("1.0", contents)
file.close()
self.title(file.name + " - Notepad")

def save_file(self):
file = filedialog.asksaveasfile(mode="w", defaultextension=".txt", filetypes=[("Text Documents", "*.txt"), ("All Files", "*.*")])
if file:
contents = self.text.get("1.0", "end")
file.write(contents)
file.close()
self.title(file.name + " - Notepad")

def cut(self):
self.text.event_generate("<<Cut>>")

def copy(self):
self.text.event_generate("<<Copy>>")

def paste(self):
self.text.event_generate("<<Paste>>")

if name == "__main__":
notepad = Notepad()
notepad.mainloop()



Let’s discuss all the user-defined functions which will be needed to add functionalities to
👍73🥰1
Output
👍9🔥5
Number guessing game in Python 😍

Analysis:

Explanation 1: If the User inputs range, let’s say from 1 to 100. And compiler randomly selected 42 as the integer. And now the guessing game started, so the user entered 50 as his/her first guess. The compiler shows “Try Again! You guessed too high”. That’s mean the random number (i.e., 42) doesn’t fall in the range from 50 to 100. That’s the importance of guessing half of the range. And again, the user guesses half of 50 (Could you tell me why?). So the half of 50 is 25. The user enters 25 as his/her second guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! The user guessed half of this range, so that, user guessed 37 as his/her third guess. This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her fourth guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fifth guess. This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her sixth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her seventh guess.

Explanation 2: If the User inputs range, let’s say from 1 to 50. And compiler randomly selected 42 as the integer. And now the guessing game started. So the half of 50 is 25. The user enters 25 as his/her First guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! User guessed half of this range, so that, user guessed 37 as his/her second guess. This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her third guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fourth guess. This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her fifth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her sixth guess.

Total Number of Guesses = 6

So, the minimum number of guesses depends upon range. And the compiler must calculate the minimum number of guessing depends upon the range, on its own. For this, we have a formula:-

Minimum number of guessing = log2(Upper bound – lower bound + 1)

Algorithm: Below are the Steps:
User inputs the lower bound and upper bound of the range.
The compiler generates a random integer between the range and store it in a variable for future references.
For repetitive guessing, a while loop will be initialized.
If the user guessed a number which is greater than a randomly selected number, the user gets an output “Try Again! You guessed too high“
Else If the user guessed a number which is smaller than a randomly selected number, the user gets an output “Try Again! You guessed too small”
And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ” Output.
Else if the user didn’t guess the integer in the minimum number of guesses,
👍3
Output :-
👍3
Coding_knowledge pinned Deleted message
Python – Cows and Bulls game Cows and Bulls is a pen and paper code-breaking game usually played between 2 players. In this, a player tries to guess a secret code number chosen by the second player. The rules are as follows:
A player will create a secret code, usually a 4-digit number. This number should have no repeated digits. Another player makes a guess (4 digit number) to crack the secret number. Upon making a guess, 2 hints will be provided- Cows and Bulls. Bulls indicate the number of correct digits in the correct position and cows indicates the number of correct digits in the wrong position. For example, if the secret code is 1234 and the guessed number is 1246 then we have 2 BULLS (for the exact matches of digits 1 and 2) and 1 COW (for the match of digit 4 in the wrong position) The player keeps on guessing until the secret code is cracked. The player who guesses in the minimum number of tries wins.
To create this game in Python, the computer generates a secret code and the user will have to guess the code. Break it down into these blocks: Generate a secret code- Generate a random 4-digit number and check that it does not have any repeated digits.
Generate hint or response- Take the generated 4-digit secret number and the guessed number (input). Find the common digits with exact matches (bulls) and the common digits in the wrong position (cows). Repeat with each guess until you have 4 bulls (an exact match) or you run out of tries. Constraint: The secret code and the guessed code should be of 4-digits (between 1000 and 9999) and have no repeated numbers.
#code :-# Import required module import random
# Returns list of digits # of a number def getDigits(num):
return [int(i) for i in str(num)] # Returns True if number has
# no duplicate digits # otherwise False def noDuplicates(num): num_li = getDigits(num)
if len(num_li) == len(set(num_li)): return True else: return False
# Generates a 4 digit number
# with no repeated digits def generateNum(): while True: num = random.randint(1000,9999)
if noDuplicates(num): return num
# Returns common digits with exact # matches (bulls) and the common # digits in wrong position (cows) def numOfBullsCows(num,guess):
bull_cow = [0,0] num_li = getDigits(num) guess_li = getDigits(guess)
for i,j in zip(num_li,guess_li): # common digit present if j in num_li:
# common digit exact match if j == i: bull_cow[0] += 1
# common digit match but in wrong position else: bull_cow[1] += 1
return bull_cow
# Secret Code num = generateNum() tries =int(input('Enter number of tries: '))
# Play game until correct guess # or till no tries left while tries > 0:
guess = int(input("Enter your guess: ")) if not noDuplicates(guess): print("Number should not have repeated digits. Try again.")
continue if guess < 1000 or guess > 9999: print("Enter 4 digit number only. Try again.")
continue bull_cow = numOfBullsCows(num,guess) print(f"{bull_cow[0]} bulls, {bull_cow[1]} cows")
tries -=1 if bull_cow[0] == 4: print("You guessed right!")
breakelse: print(f"You ran out of tries. Number was {num}")
4👍1🔥1
Flappy Bird Game Using Pythpn 😍😍

Introduction:

In this project, we have created a game using the “Pygame” module in python. The game is named “Flappy Bird”. Most of you have played this game on your mobile phones and now it’s time to code this game by yourself. If you haven’t played this before, not an issue, let’s cover this introduction with these few lines. The game is a side-scroller where the player controls a bird, attempting to fly between columns of green pipes without hitting them, and scores for the same.


Explanation:
The most basic need to work under the module is to import them. With the help of the “import” keyword, we will import all the libraries needed. Along with “pygame”, we will also import the “sys”, “time”, and “random” modules.Before talking about the process in which we have to code, let’s discuss the raw elements first and along with them the objectives as well:
*Firstly, for making this game the raw elements which will be needed:A birdA background image
A floor imagePipe imageGame over message image* After discussing the elements, let’s discuss the objectives under which these elements will be used:
We need to create an animation that will treat the user’s eye as if the bird is moving ahead and by moving the base we will do so.To make the bird fly and rotate.Create the pipes at the top and bottom and show them in animation as well.
For maintaining the rules, we have to code for setting the parameters for scoring a point and losing the game by hitting the pipes and surfacesThe basic steps are to initialize the pygame module by the “.init()” method and set the frames per second by the “pygame.time.Clock() “method of the “random” module.First of all, to create a game window we will use the “pygame.display.set_mode(width, height)” method and to set the caption of our window we will use “pygame.display.set_caption( )”.
Now we will make a game loop using a “while” loop under this we will run a “for” loop for getting the events with the help of “pygame.event.get()” and to check the event type we will make use of “.type”. firstly, we will check for the quit event with the help of “pygame. QUIT”.In this project, we will make 5 user-defined functions named:
draw_floor( )create_pipes( )pipe_animation( )
draw_score( )score_update( )Now starting with the game, the most basic need is to set a background image for our window screen. Firstly, we will load the image and then we will blit it on the screen, the blitting means to draw that particular image. To load the image we will use “pygame.image.load(‘image path or image name’)” and “screen. blit(‘source’,’ position’)” is being used to blit the particular image on the screen under the game loop. With the help of these two functions and the variable named “back_img” we will set the background image, and to update the game window with the changes we will use the “pygame.display.update()” function.
After drawing the background image we will need a floor image and with the same process under the variable named “floor_img”, we will load and then blit the floor image on the game window.The next step is to move the floor and for doing so we will create a variable called “floor_x” and declare it initially as 0. Now under the game loop we will subtract the 1 from our variable and to move it continuously we will blit the floor image by adding 448 to our x position. All of this will be done under our first user-defined function “draw_floor( )” and the floor may not get disappeared so under the game loop we will check the condition of the floor_x will be less than -448 then again the floor_x will be set as 0. Due to this condition, we can see that the base on our game window will move continuously
The next most important step is to draw a bird on the screen and for showing the movement of the bird we will use three images of a bird at different stages. That is a bird with an up flap, a bid with a mid flap, and a bird with a down flap. We will load these images and blit them with the help of the same functions. Now to show these different images we will
👍2
flappy-bird.zip
96.2 KB
Downloade file for flappy bird game code
Python | ToDo GUI Application using Tkinter 🔥🚀
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method
To create a tkinter :
Importing the module – tkinterCreate the main window (container)
Add any number of widgets to the main window.Apply the event Trigger on the widgets.

Code :-

# import all functions from the tkinter from tkinter import *
# import messagebox class from tkinter
from tkinter import messagebox
# global list is declare for storing all the tasktasks_list = []
# global variable is declare for counting the task
counter = 1
# Function for checking input error when# empty input is given in task field
def inputError() :
# check for enter task field is empty or not if enterTaskField.get() == "" :
# show the error message
messagebox.showerror("Input Error")
return 0
return 1
# Function for clearing the contents
# of task number text fielddef clear_taskNumberField() :
# clear the content of task number text field
taskNumberField.delete(0.0, END)
# Function for clearing the contents# of task entry field
def clear_taskField() :
# clear the content of task field entry box enterTaskField.delete(0, END)
# Function for inserting the contents
# from the task entry field to the text area def insertTask():
global counter
# check for error
value = inputError()
# if error occur then return if value == 0 :
return
# get the task string concatenating # with new line character
content = enterTaskField.get() + "\n"
# store task in the list tasks_list.append(content)
# insert content of task entry field to the text area
# add task one by one in below one by one TextArea.insert('end -1 chars', "[ " + str(counter) + " ] " + content)
# incremented
counter += 1
# function calling for deleting the content of task field clear_taskField()
# function for deleting the specified task
def delete() :
global counter
# handling the empty task error if len(tasks_list) == 0 :
messagebox.showerror("No task") return
# get the task number, which is required to delete
number = taskNumberField.get(1.0, END)
# checking for input error when # empty input in task number field
if number == "\n" : messagebox.showerror("input error")
return
else : task_no = int(number)
# function calling for deleting the
# content of task number field clear_taskNumberField()
# deleted specified task from the list
tasks_list.pop(task_no - 1)
# decremented counter -= 1
# whole content of text area widget is deleted
TextArea.delete(1.0, END)
# rewriting the task after deleting one task at a time for i in range(len(tasks_list)) :
TextArea.insert('end -1 chars', "[ " + str(i + 1) + " ] " + tasks_list[i])
# Driver code
if name == "main" :
# create a GUI window gui = Tk()
# set the background colour of GUI window
gui.configure(background = "light green")
# set the title of GUI window gui.title("ToDo App")
# set the configuration of GUI window
gui.geometry("250x300")
# create a label : Enter Your Task enterTask = Label(gui, text = "Enter Your Task", bg = "light green")
# create a text entry box
# for typing the task enterTaskField = Entry(gui)

# create a Submit Button and place into the root window # when user press the button, the command or
# function affiliated to that button is executed Submit = Button(gui, text = "Submit", fg = "Black", bg = "Red", command = insertTask)
# create a text area for the root
# with lunida 13 font # text area is for writing the content
TextArea = Text(gui, height = 5, width = 25, font = "lucida 13")
# create a label : Delete Task Number taskNumber = Label(gui, text = "Delete Task Number", bg = "blue")
taskNumberField = Text(gui, height = 1, width = 2, font = "lucida 13")
# create a Delete Button and place into the root window
# when user press the button, the command or # function affiliated to that button is executed .
delete = Button(gui, text = "Delete", fg = "Black", bg = "Red", command = delete)
# create a Exit Button and place into the root
👍9
Tic Tac Toe GUI In Python using PyGame

This Post will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Let’s break the task in five parts:
1.Importing the required libraries and setting up the required global variables.2.Designing the game display function, that will set a platform for other components to be displayed on the screen.
3.Main algorithm of win and draw4.Getting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse.
5.Running an infinite loop, and including the defined methods in it.
Importing the required libraries and setting up the required global variables
We are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below.

Importing the required libraries and setting up the required global variablesWe are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below.

# importing the required librariesimport pygame as pg
import sysimport time
from pygame.locals import *
# declaring the global variables
# for storing the 'x' or 'o'# value as character
XO = 'x'
# storing the winner's value at# any instant of code
winner = None
# to check if the game is a drawdraw = None
# to set width of the game window
width = 400
# to set height of the game windowheight = 400
# to set background color of the
# game windowwhite = (255, 255, 255)
# color of the straightlines on that
# white game board, dividing board# into 9 parts
line_color = (0, 0, 0)
# setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3]
Designing the game display
This is the trickier part, that makes the utmost importance in game development. We can use the display.set_mode() method to set up our display window. This takes three arguments, first one being a tuple having (width, height) of the display that we want it to be, the other two arguments are depth and fps respectively.display.set_caption(), sets a caption on the name tag of our display. pg.image.load() is an useful method to load the background images to customize the display. This method takes the file name as an argument along with the extension. There is a small problem with image.load(), it loads the image as a Python object in its native size, which may not be optimized along with the display. So we use another method in pygame known as pg.transform.scale(). This method takes two arguments, one being the name of the image object and the other is a tuple having (width, height), that we want our image to scale to. Finally we head to the first function, game_initiating_window(). On the very first line there is a screen.blit() function. The screen is the Python function and blit is the method that enables pygame to display something over another thing. Here out image object has been displayed over the screen, which was set white initially. pg.display.update() is another important function in game development. It updates the display of our window when called. Pygame also enables us to draw geometric objects like line, circle, etc. In this project we have used pg.draw.line() method that takes five arguments, namely – (display, line color, starting point, ending point, width). This involves a little bit of coordinate geometry to draw the lines properly. This is not sufficient. At each update of the display we need to know the game status, Whether it is win or lose.draw_status() helps us in displaying another 100pc window at the bottom of the main window, that updates the status at each click of the user.
# initializing the pygame window
pg.init()
# setting fps manuallyfps = 30
# this is used to track
👍42👏1
Full Code :-

# importing the required librariesimport pygame as pg
import sysimport time
from pygame.locals import *
# declaring the global variables
# for storing the 'x' or 'o'# value as character
XO = 'x'
# storing the winner's value at# any instant of code
winner = None
# to check if the game is a drawdraw = None
# to set width of the game window
width = 400
# to set height of the game windowheight = 400
# to set background color of the
# game windowwhite = (255, 255, 255)
# color of the straightlines on that
# white game board, dividing board# into 9 parts
line_color = (0, 0, 0)
# setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3]

# initializing the pygame windowpg.init()
# setting fps manually
fps = 30
# this is used to track timeCLOCK = pg.time.Clock()
# this method is used to build the
# infrastructure of the displayscreen = pg.display.set_mode((width, height + 100), 0, 32)
# setting up a nametag for the
# game windowpg.display.set_caption("My Tic Tac Toe")
# loading the images as python object
initiating_window = pg.image.load("modified_cover.png")x_img = pg.image.load("X_modified.png")
y_img = pg.image.load("o_modified.png")
# resizing imagesinitiating_window = pg.transform.scale(
initiating_window, (width, height + 100))x_img = pg.transform.scale(x_img, (80, 80))
o_img = pg.transform.scale(y_img, (80, 80))
def game_initiating_window():
# displaying over the screen
screen.blit(initiating_window, (0, 0))
# updating the display pg.display.update()
time.sleep(3) screen.fill(white)
# drawing vertical lines
pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) pg.draw.line(screen, line_color, (width / 3 * 2, 0),
(width / 3 * 2, height), 7)
# drawing horizontal lines pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7)
pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7)
draw_status()
def draw_status():
# getting the global variable draw
# into action global draw
if winner is None:
message = XO.upper() + "'s Turn" else:
message = winner.upper() + " won !" if draw:
message = "Game Draw !"
# setting a font object font = pg.font.Font(None, 30)
# setting the font properties like
# color and width of the text text = font.render(message, 1, (255, 255, 255))
# copy the rendered message onto the board
# creating a small block at the bottom of the main display screen.fill((0, 0, 0), (0, 400, 500, 100))
text_rect = text.get_rect(center=(width / 2, 500-50)) screen.blit(text, text_rect)
pg.display.update()
def check_win():
global board, winner, draw
# checking for winning rows for row in range(0, 3):
if((board[row][0] == board[row][1] == board[row][2]) and (board[row][0] is not None)): winner = board[row][0]
pg.draw.line(screen, (250, 0, 0), (0, (row + 1)*height / 3 - height / 6),
(width, (row + 1)*height / 3 - height / 6), 4)
break
# checking for winning columns for col in range(0, 3):
if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): winner = board[0][col]
pg.draw.line(screen, (250, 0, 0), ((col + 1) * width / 3 - width / 6, 0), ((col + 1) * width / 3 - width / 6, height), 4)
break
# check for diagonal winners if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None):
# game won diagonally left to right
winner = board[0][0] pg.draw.line(screen, (250, 70, 70), (50, 50), (350, 350), 4)
if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None):
# game won diagonally right to left
winner = board[0][2] pg.draw.line(screen, (250, 70, 70), (350, 50), (50, 350), 4)
if(all([all(row) for row in board]) and winner is None):
draw = True draw_status()

def drawXO(row, col): global board, XO
# for the first row, the image
# should be pasted at a x coordinate # of 30 from the left margin
if row == 1: posx = 30
# for the second row, the image
# should be pasted at a x coordinate
# of 30 from the game line if row == 2:

# margin or width / 3 + 30 from # the left margin of the
👍32