0% found this document useful (0 votes)
2 views

the code

Uploaded by

rathormansi1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

the code

Uploaded by

rathormansi1234
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

import pygame

# Define some colors


BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

# Define screen size

width = 800

height = 600

# Initialize Pygame

pygame.init()

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('Bat and Ball Game')

clock = pygame.time.Clock()

# Define bat and ball properties

bat_x = width // 2 - 30 # Center the bat horizontally

bat_y = height - 30 # Place the bat at the bottom

bat_width = 60

bat_height = 20

ball_x = width // 2 # Center the ball horizontally

ball_y = height // 2 # Center the ball vertically

ball_radius = 10

ball_speed_x = 3 # Ball movement speed on X-axis

ball_speed_y = 3 # Ball movement speed on Y-axis

# Game loop flag


running = True

# Main game loop

while running:

# Check for events (like closing the window)

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

# Handle user input (move the bat)

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT] and bat_x > 0:

bat_x -= 5 # Move left

if keys[pygame.K_RIGHT] and bat_x < width - bat_width:

bat_x += 5 # Move right

# Update ball position

ball_x += ball_speed_x

ball_y += ball_speed_y

# Wall collision detection (bounce the ball)

if ball_y > height - ball_radius or ball_y < ball_radius:

ball_speed_y *= -1 # Reverse Y-axis speed on wall collision

if ball_x > width - ball_radius or ball_x < ball_radius:

ball_speed_x *= -1 # Reverse X-axis speed on wall collision


# Bat collision detection (bounce the ball)

if ball_y + ball_radius > bat_y and ball_y < bat_y + bat_height and ball_x + ball_radius > bat_x and
ball_x < bat_x + bat_width:

ball_speed_y *= -1 # Reverse Y-axis speed on bat collision

# Fill the screen with black

screen.fill(BLACK)

# Draw the bat and ball

pygame.draw.rect(screen, WHITE, (bat_x, bat_y, bat_width, bat_height))

pygame.draw.circle(screen, WHITE, (ball_x, ball_y), ball_radius)

# Update the display

pygame.display.flip()

# Set frame rate

clock.tick(60) # 60 frames per second

# Quit Pygame

pygame.quit()
<iframe width="1263" height="480" src="https://www.youtube.com/embed/OVn1L6gXXtk"
title="Class 8 English New Pathways | Unit 4 Unlikely Destinations - Emperors on Ice Explanation
(Part 2)" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media;
gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen></iframe>

You might also like