Drawing App For Kivy

 Below here is the source code for Drawing Application for kivy. Please if you like this content. Don't forget to Subscribe to my YouTube Channel here now on Python Programming now or other programming content now and please support me on PayPal Now for better content! and Join our WhatsApp group here or here also with our Telegram group here to start learning now! Thanks!



from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Line
from kivy.core.window import Window

class DrawingApp(App):
def build(self):
self.drawing_widget = DrawingWidget()
self.erase_button = Button(text="Erase", size_hint=(None,None), size=(100,50), pos=(0,Window.height - 50))
self.erase_button.bind(on_press=self.toggle_color)
self.root = Widget()
self.root.add_widget(self.drawing_widget)
self.root.add_widget(self.erase_button)
return self.root

def toggle_color(self, instance):
self.drawing_widget.toggle_color()
self.update_button_style()

def update_button_style(self):
if self.drawing_widget.color == (1,0,0):
self.erase_button.background_color = (0.6,0.6,0.6,1)
else:
self.erase_button.background_color = (0,0,1,1)




class DrawingWidget(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.color = (1,0,0)
self.line_width = 2


def on_touch_down(self, touch):
with self.canvas:
Color(*self.color)
touch.ud['line'] = Line(points=(touch.x, touch.y), width=self.line_width)


def on_touch_move(self,touch):
touch.ud['line'].points += (touch.x,touch.y)



def toggle_color(self):
if self.color == (1,0,0):
self.color = (0,0,0)
self.line_width = 5

else:
self.color = (1,0,0)
self.line_width = 2



if __name__ == '__main__':
DrawingApp().run()


Source Code For Task Manager Kivy


Below here is the source code for Task Manager for kivy. Please if you like this content. Don't forget to Subscribe to my YouTube Channel here now on Python Programming now or other programming content now and please support me on PayPal Now for better content! and Join our WhatsApp group here or here also with our Telegram group here to start learning now! Thanks!





 from kivy.app import App

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
import pickle

class TaskManager(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.tasks = []


def add_task(self, instance):
if len(self.tasks) < 4:
task_text = self.task_input.text
if task_text:
self.tasks.append(task_text)
self.update_task_list()



def update_task_list(self):
self.task_list.clear_widgets()
for task in self.tasks:
task_label = Label(text=task)
delete_button = Button(text='Delete')
delete_button.bind(on_press=lambda instance, task = task: self.delete_task(task))
self.task_list.add_widget(task_label)
self.task_list.add_widget(delete_button)

def delete_task(self, task_text):
self.tasks.remove(task_text)
self.update_task_list()


def build(self):
layout = BoxLayout(orientation='vertical', padding=10)

self.task_input = TextInput(hint_text = 'Enter your task here')

add_button = Button(text='Add Task')
add_button.bind(on_press = self.add_task)

self.task_list = BoxLayout(orientation='vertical')

layout.add_widget(self.task_input)
layout.add_widget(add_button)
layout.add_widget(Label(text='Tasks:'))
layout.add_widget(self.task_list)
self.load_tasks()
return layout

def on_stop(self):
self.save_tasks()

def save_tasks(self):
with open("tasks.pkl","wb") as f:
pickle.dump(self.tasks, f)

def load_tasks(self):
try:
with open("tasks.pkl","rb") as f:
self.tasks = pickle.load(f)
self.update_task_list()
except FileNotFoundError:
pass




TaskManager().run()

Source Code For Quiz Application Kivy

 

Below here is the source code for Quiz Application for kivy. Please if you like this content. Don't forget to Subscribe to my YouTube Channel here now on Python Programming now or other programming content now and please support me on PayPal Now for better content! and Join our WhatsApp group here or here also with our Telegram group here to start learning now! Thanks!






from kivy.app import App

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.togglebutton import ToggleButton


class ObjectiveQuiz(App):
def __init__(self):
super().__init__()
self.questions = [
{"question": "What is the capital of France?",
"options": ["Paris", "London", "Berlin", "Rome"],
"correct_answer": "Paris"
},

{"question": "What is the capital of United Kingdom?",
"options": ["Paris", "London", "Berlin", "Rome"],
"correct_answer": "London"
},
{"question": "what is 2 + 2",
"options": ["7", "1", "0", "4"],
"correct_answer": "4"
},
{"question": "what continent is Italy on",
"options": ["Africa", "Europe", "North America", "South America"],
"correct_answer": "Europe"
},
{"question": "what is 1 + 1",
"options": ["0", "2", "5", "20"],
"correct_answer": "2"
}

]
self.current_question = 0
self.score = 0

def build(self):
self.queston_label = Label(text=self.questions[self.current_question]["question"])
self.option_buttons = []
for option in self.questions[self.current_question]["options"]:
button = ToggleButton(text=option, group="options", on_press=self.select_option)
self.option_buttons.append(button)

layout = BoxLayout(orientation='vertical')
layout.add_widget(self.queston_label)
for button in self.option_buttons:
layout.add_widget(button)

return layout

def select_option(self, instance):
selected_option = instance.text
correct_answer = self.questions[self.current_question]["correct_answer"]

if selected_option == correct_answer:
self.score += 20

self.current_question +=1
if self.current_question <len(self.questions):
self.update_question()
else:
self.end_quiz()

def update_question(self):
self.queston_label.text = self.questions[self.current_question]["question"]
for button in self.option_buttons:
button.text = self.questions[self.current_question]["options"][self.option_buttons.index(button)]
button.state = "normal"


def end_quiz(self):
self.queston_label.text = "Quiz Finished!"
for button in self.option_buttons:
button.disabled = True
result_label = Label(text=f"Your score is: {self.score}/100")
self.root.add_widget(result_label)


if __name__ == '__main__':
ObjectiveQuiz().run()

Source Code For Tank Simulator (Pygame)

 Here is the link to the sound assets and sprites. Bellow here is the source code. Please if you like this content. Don't forget to Subscribe to my YouTube Channel here now on Python Programming now or other programming content now and please support me on PayPal Now for better content! and Join our WhatsApp group here or here also with our Telegram group here to start learning now! Thanks!


import pygame
import sys
import math

# Initialize Pygame
pygame.init()

# Screen dimensions
WIDTH, HEIGHT = 800, 600

# Create the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tank Movement")
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.display.set_caption("Tank Movement")
shoot_sound = pygame.mixer.Sound("shoot.wav")
move_forward_sound = pygame.mixer.Sound("move_forward.mp3") # Replace with your forward movement sound file path
move_gun = pygame.mixer.Sound("move_gun.mp3")

# Get the screen dimensions
SCREEN_WIDTH, SCREEN_HEIGHT = pygame.display.get_surface().get_size()



# Main game loop



# Tank sprite class
class Tank(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.original_tank_image = pygame.image.load("tank.png").convert_alpha()
self.tank_image = pygame.transform.scale(self.original_tank_image, (50, 30))
self.image = self.tank_image
self.rect = self.tank_image.get_rect(center=(x, y))
self.angle = 0
self.speed = 0
self.rotation_speed = 0


def update(self):
keys = pygame.key.get_pressed()

if keys[pygame.K_UP]:
self.speed = 3
move_forward_sound.play()
elif keys[pygame.K_DOWN]:
self.speed = -2
move_forward_sound.play()
else:
self.speed = 0
move_forward_sound.stop()

if keys[pygame.K_LEFT]:
self.rotation_speed = 2
move_forward_sound.play()
elif keys[pygame.K_RIGHT]:
self.rotation_speed = -2
move_forward_sound.play()

else:
self.rotation_speed = 0

self.angle += self.rotation_speed
self.angle %= 360

self.image = pygame.transform.rotate(self.original_tank_image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)

angle_rad = math.radians(self.angle)
dx = math.cos(angle_rad) * self.speed
dy = math.sin(angle_rad) * self.speed

self.rect.x += dx
self.rect.y -= dy

class Gun(pygame.sprite.Sprite):
def __init__(self, tank):
super().__init__()
self.original_gun_image = pygame.image.load("gun.png").convert_alpha()
self.gun_image = pygame.transform.scale(self.original_gun_image, (20, 40))
self.image = self.gun_image
self.rect = self.gun_image.get_rect(center=tank.rect.center)
self.angle = 0
self.rotation_speed = 0
self.tank = tank
self.gun_length = 40
self.gun_rotation_direction = 0
self.tip_offset = 30

self.original_gun_length = self.gun_length
self.gun_back_start_time = 0
self.gun_back_duration = 200
self.can_shoot = True
self.shoot_cooldown = 0
self.cooldown_duration = 3000
self.last_update_time = pygame.time.get_ticks()


def update(self):
keys = pygame.key.get_pressed()

if keys[pygame.K_z]:
self.rotation_speed = 2
move_forward_sound.stop()
move_gun.play()
elif keys[pygame.K_x]:
self.rotation_speed = -2
move_forward_sound.stop()
move_gun.play()
else:
self.rotation_speed = 0
move_gun.stop()

self.angle += self.rotation_speed
self.angle %= 360

if keys[pygame.K_SPACE] and self.can_shoot:
self.gun_back_start_time = pygame.time.get_ticks() # Start moving the gun back
bullet_angle = self.angle
bullet_x = self.rect.centerx + (self.gun_length + self.tip_offset) * math.cos(math.radians(bullet_angle))
bullet_y = self.rect.centery - (self.gun_length + self.tip_offset) * math.sin(math.radians(bullet_angle))
bullet = Bullet(bullet_x, bullet_y, bullet_angle)
all_sprites.add(bullet)
bullet_sprites.add(bullet)
move_forward_sound.stop()
move_gun.stop()

shoot_sound.play()

self.can_shoot = False
self.shoot_cooldown = self.cooldown_duration

elapsed_time = pygame.time.get_ticks() - self.gun_back_start_time
if elapsed_time <= self.gun_back_duration:
progress = elapsed_time / self.gun_back_duration
self.gun_length = self.original_gun_length - 5 * progress
else:
self.gun_length = self.original_gun_length

angle_rad = math.radians(self.angle)
gun_end_x = self.tank.rect.centerx + (self.gun_length + self.tip_offset) * math.cos(angle_rad)
gun_end_y = self.tank.rect.centery - (self.gun_length + self.tip_offset) * math.sin(angle_rad)

rotated_gun_image = pygame.transform.rotate(self.original_gun_image, self.angle)
self.image = rotated_gun_image
self.rect = self.image.get_rect(center=(gun_end_x, gun_end_y))

if self.shoot_cooldown > 0:
self.shoot_cooldown -= pygame.time.get_ticks() - self.last_update_time
else:
self.can_shoot = True

self.last_update_time = pygame.time.get_ticks()

class Bullet(pygame.sprite.Sprite):
def __init__(self, x , y , angle):
super().__init__()
self.original_bullet_image = pygame.image.load("bullet.png").convert_alpha()
self.bullet_image = pygame.transform.scale(self.original_bullet_image, (20,20))
self.image = self.bullet_image
self.angle = angle
self.speed = 10

angle_rad = math.radians(self.angle)

dx = (gun.gun_length+ gun.tip_offset - 32) * math.cos(angle_rad)
dy = -(gun.gun_length + gun.tip_offset - 32) * math.sin(angle_rad)


self.rect = self.bullet_image.get_rect(center=(x+dx, y+dy))
self.start_x = self.rect.centerx
self.start_y = self.rect.centery

def update(self):
angle_rad = math.radians(self.angle)
dx = self.speed * math.cos(angle_rad)
dy = -self.speed * math.sin(angle_rad)
self.rect.x += dx
self.rect.y += dy


tank = Tank(375,300)
gun = Gun(tank)
all_sprites = pygame.sprite.Group()
all_sprites.add(tank,gun)
bullet_sprites = pygame.sprite.Group()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()

keys = pygame.key.get_pressed()

if gun.can_shoot and keys[pygame.K_SPACE]:
bullet_angle = gun.angle
bullet_x = gun.rect.centerx + (gun.gun_length + gun.tip_offset) * math.cos(math.radians(bullet_angle))
bullet_y = gun.rect.centery - (gun.gun_length + gun.tip_offset) * math.sin(math.radians(bullet_angle))
bullet = Bullet(bullet_x, bullet_y, bullet_angle)
all_sprites.add(bullet)
bullet_sprites.add(bullet)
shoot_sound.play()
gun.can_shoot = False
gun.shoot_cooldown = gun.cooldown_duration
bullet_sprites.update()


screen.fill((255, 255, 255))
all_sprites.draw(screen)
bullet_sprites.draw(screen)
pygame.display.flip()
pygame.time.Clock().tick(60)



Top 5 Games Made With Python



The development of video games is one of the many applications for the flexible programming language Python. Although Python may not be as well-known in the game development community as languages like C++ or engines like Unity, it still has a number of benefits that make it an effective tool in this field.

First of all, Python is renowned for its readability and simplicity. Both novice and seasoned developers will find it to be a great choice because of its simple and easy-to-understand syntax. Python tends to produce short, expressive code that allows programmers to create clear, manageable code.

Despite Python of its short comings for making games, it has helped assist in the development of some of your popular video games, here are the video game that has been supported with python programming language itself:


Battlefield 2


Developed by DICE, Battlefield 2 is a popular first-person shooter game that employs Python for scripting game logic. Python enables developers to define and control various aspects of the game, including player actions, AI behavior, weapon mechanics, and mission objectives. This flexibility provided by Python allows for dynamic and immersive gameplay experiences.


Sid Meier's Civilization IV



Sid Meier's turn-based strategy game Civilization IV heavily utilizes Python for both artificial intelligence and game logic. City administration, diplomacy, trade, and battle are just a few of the game aspects that may be defined and managed by developers using Python. Python gives modders the ability to design unique scenarios, alter gameplay elements, and improve the entire gaming experience.


 Mount & Blade 



Mount & Blade TaleWorlds Entertainment's Mount & Blade video game series uses Python for its scripting and modding features. Python makes it possible for users and modders to alter gameplay mechanics, design new missions, modify AI behaviors, and increase the game's functionality. The community may continuously add to and improve the game's content thanks to its adaptability, which adds to its lifespan.


Frets on Fire


Frets on Fire is an open-source music video game where players simulate playing a guitar by using their keyboard as a guitar fretboard. Developed in Python, the game showcases Python's capability for handling real-time input, graphics rendering, and sound processing. Python's simplicity makes it an accessible language for developers to create rhythm games and other interactive music experiences.


World of Tanks



Python is used for scripting and modification in World of Tanks, an online team-based tank fighting game created by Wargaming. Python makes it possible for gamers to add new features and functionality to the game, improving the gameplay and supporting a thriving modding scene. Python's simplicity and use make it possible for both seasoned developers and beginners to produce original game material.


In conclusion, although Python may not be the language that comes to mind when thinking about game creation, it has demonstrated its adaptability and value in producing quality games. The best Python games show off the language's talents in scripting, modding, prototyping, and server infrastructure, among other areas of game production.


Furthermore, Python's compatibility with other programming languages and game engines, such Unity and Unreal Engine, enables programmers to take advantage of its advantages alongside those of other tools and technologies.


Python is a compelling option for game development due to its readability, simplicity, large library selection, and robust community support. Python shines in areas like quick prototyping, scripting, modding, and smaller to medium-sized game projects, even though it may not be appropriate for all game genres or performance-intensive jobs.


Overall, the best Python games show how good the language is at producing captivating and immersive gaming experiences, as well as how it has the potential to keep having a big impact on the game production industry.


PROJECT IDEA GENERATOR WITH PYTHON TKINTER

 Here is a source codes for random idea generator using Python Tk


import tkinter as tk
import random


class ProjectIdeaGenerator(tk.Tk):
def __init__(self):
super().__init__()

self.title("Project Idea Generator")
self.resizable(False, False)

# create the category label
category_label = tk.Label(self, text="Category:", font=("Helvetica", 12))
category_label.grid(row=0, column=0, padx=10, pady=10)

# create the category option menu
self.category_variable = tk.StringVar(self)
self.category_variable.set("Web Development")
category_option_menu = tk.OptionMenu(self, self.category_variable, *self.get_categories())
category_option_menu.grid(row=0, column=1, padx=10, pady=10)

# create the generate button
generate_button = tk.Button(self, text="Generate", font=("Helvetica", 12), command=self.generate_idea)
generate_button.grid(row=1, column=0, columnspan=2, padx=10, pady=10)

# create the result label
self.result_label = tk.Label(self, text="", font=("Helvetica", 12))
self.result_label.grid(row=2, column=0, columnspan=2, padx=10, pady=10)

def get_categories(self):
return ["Web Development", "Data Science", "Games", "Artificial Intelligence", "Virtual Reality"]

def generate_idea(self):
category = self.category_variable.get()
if category == "Web Development":
ideas = ["Build a weather forecast website", "Create a social media platform",
"Develop an e-commerce website", "Create a job board site", "Build a portfolio website"]
elif category == "Data Science":
ideas = ["Predict housing prices using machine learning", "Classify emails as spam or not spam",
"Analyze survey data", "Build a recommendation system for movies or books",
"Forecast stock prices"]
elif category == "Games":
ideas = ["Create a puzzle game", "Build a platformer game", "Develop a virtual reality game",
"Make a multiplayer game", "Design a role-playing game"]
elif category == "Artificial Intelligence":
ideas = ["Build a chatbot", "Develop a computer vision system", "Create an autonomous car simulation",
"Make a sentiment analysis tool", "Train a machine learning model to generate music"]
elif category == "Virtual Reality":
ideas = ["Build a virtual reality game", "Create a virtual tour of a museum",
"Develop a virtual reality shopping experience", "Make a virtual reality training program",
"Design a virtual reality education tool"]

idea = random.choice(ideas)
self.result_label.config(text=idea)


if __name__ == "__main__":
app = ProjectIdeaGenerator()
app.mainloop()

SOURCE CODE FOR ROCK, PAPER AND SCISSORS GAME WITH TKINTER, PYTHON

 Here is the source code for making a Rock, Paper and Scissors game using Tkinter


import tkinter as tk
import random


def rock_paper_scissors():
player_choice = user_choice.get()
computer_choice = random.choice(['rock', 'paper', 'scissors'])

result = None
if player_choice == computer_choice:
result = "Tie"
elif player_choice == 'rock' and computer_choice == 'scissors':
result = "You Win!"
player_score[0] += 1
elif player_choice == 'paper' and computer_choice == 'rock':
result = "You Win!"
player_score[0] += 1
elif player_choice == 'scissors' and computer_choice == 'paper':
result = "You Win!"
player_score[0] += 1
else:
result = "You Lose!"
computer_score[0] += 1

result_label.config(text=f"Result: {result}")
player_score_label.config(text=f"Your Score: {player_score[0]}")
computer_score_label.config(text=f"Computer Score: {computer_score[0]}")


def reset_scores():
player_score[0] = 0
computer_score[0] = 0
player_score_label.config(text=f"Your Score: {player_score[0]}")
computer_score_label.config(text=f"Computer Score: {computer_score[0]}")
result_label.config(text="Result: ")


root = tk.Tk()
root.resizable(False, False)
root.title("Rock, Paper, Scissors Game")

user_choice = tk.StringVar()

player_score = [0]
computer_score = [0]

result_label = tk.Label(root, text="Result: ", font=("Helvetica", 14))
result_label.pack()

player_score_label = tk.Label(root, text=f"Your Score: {player_score[0]}", font=("Helvetica", 14))
player_score_label.pack()

computer_score_label = tk.Label(root, text=f"Computer Score: {computer_score[0]}", font=("Helvetica", 14))
computer_score_label.pack()

rock_radio = tk.Radiobutton(root, text="Rock", variable=user_choice, value="rock", font=("Helvetica", 14))
rock_radio.pack()

paper_radio = tk.Radiobutton(root, text="Paper", variable=user_choice, value="paper", font=("Helvetica", 14))
paper_radio.pack()

scissors_radio = tk.Radiobutton(root, text="Scissors", variable=user_choice, value="scissors", font=("Helvetica", 14))
scissors_radio.pack()

play_button = tk.Button(root, text="Play", command=rock_paper_scissors, font=("Helvetica", 14))
play_button.pack()

reset_button = tk.Button(root, text="Reset Scores", command=reset_scores, font=("Helvetica", 14))
reset_button.pack()

root.mainloop()

Drawing App For Kivy

  Below here is the source code for Drawing Application for kivy. Please if you like this content.  Don't forget to Subscribe to my YouT...