shhh
🧩 Syntax:
import pygame
import random
# initialize pygame
pygame.init()
# set the screen dimensions
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Shoot the Apple")
# set the game clock
clock = pygame.time.Clock()
# load the apple image
apple_image = pygame.image.load("apple.png").convert_alpha()
# define the apple class
class Apple:
def __init__(self):
self.x = random.randint(0, screen_width - apple_image.get_width())
self.y = -apple_image.get_height()
self.speed = random.randint(1, 5)
def update(self):
self.y += self.speed
def draw(self):
screen.blit(apple_image, (self.x, self.y))
# create a list to hold the apples
apples = []
# define the player class
class Player:
def __init__(self):
self.x = screen_width // 2
self.y = screen_height - 50
self.width = 50
self.height = 50
self.speed = 5
self.score = 0
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.x > 0:
self.x -= self.speed
if keys[pygame.K_RIGHT] and self.x < screen_width - self.width:
self.x += self.speed
def draw(self):
pygame.draw.rect(screen, (255, 0, 0), (self.x, self.y, self.width, self.height))
# create the player object
player = Player()
# define the game loop
running = True
while running:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# check if the player clicked on an apple
for apple in apples:
if apple.x <= event.pos[0] <= apple.x + apple_image.get_width() and apple.y <= event.pos[1] <= apple.y + apple_image.get_height():
apples.remove(apple)
player.score += 1
# update the player and apples
player.update()
for apple in apples:
apple.update()
# check if an apple has gone off the bottom of the screen
if len(apples) > 0 and apples[0].y > screen_height:
apples.pop(0)
# add a new apple every 60 frames
if pygame.time.get_ticks() % 60 == 0:
apples.append(Apple())
# clear the screen
screen.fill((255, 255, 255))
# draw the player and apples
player.draw()
for apple in apples:
apple.draw()
# draw the score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {player.score}", True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(60)
# quit pygame
pygame.quit()