Untitled
unknown
plain_text
7 months ago
2.9 kB
4
Indexable
import pygame
import random
import math
# Initialize pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
BALL_RADIUS = 20
HOOP_RADIUS = 30
FPS = 60
GRAVITY = 0.5
JUMP_STRENGTH = 15
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Setup the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Basketball Game")
# Clock to control frame rate
clock = pygame.time.Clock()
# Ball class
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((BALL_RADIUS * 2, BALL_RADIUS * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, RED, (BALL_RADIUS, BALL_RADIUS), BALL_RADIUS)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH // 4, HEIGHT - 50)
self.velocity = [0, 0]
def update(self):
self.rect.x += self.velocity[0]
self.rect.y += self.velocity[1]
# Gravity effect
if self.rect.y + BALL_RADIUS < HEIGHT:
self.velocity[1] += GRAVITY
else:
self.velocity[1] = 0
self.rect.y = HEIGHT - BALL_RADIUS
def throw(self, angle, speed):
angle_rad = math.radians(angle)
self.velocity = [speed * math.cos(angle_rad), -speed * math.sin(angle_rad)]
# Hoop class
class Hoop(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((HOOP_RADIUS * 2, HOOP_RADIUS * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, GREEN, (HOOP_RADIUS, HOOP_RADIUS), HOOP_RADIUS, 5)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH - 100, HEIGHT // 4)
# Main game loop
def game_loop():
ball = Ball()
hoop = Hoop()
all_sprites = pygame.sprite.Group()
all_sprites.add(ball, hoop)
running = True
score = 0
while running:
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Throw ball when the space bar is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball.throw(random.randint(30, 50), random.randint(15, 20))
# Update all sprites
all_sprites.update()
# Check if ball is in the hoop
if ball.rect.colliderect(hoop.rect):
score += 1
ball.rect.center = (WIDTH // 4, HEIGHT - 50)
ball.velocity = [0, 0]
# Draw everything
all_sprites.draw(screen)
# Display score
font = pygame.font.SysFont("Arial", 30)
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# Update the screen
pygame.display.flip()
# Set FPS
clock.tick(FPS)
pygame.quit()
# Run the game
if __name__ == "__main__":
game_loop()
Editor is loading...
Leave a Comment