Question

In: Computer Science

I needed the code for pong game (using classes) in pygame.

I needed the code for pong game (using classes) in pygame.

Solutions

Expert Solution

Here is the code for your query :

# --- Import libraries used for this program

import math
import pygame
import random

# Define some colors
BLACK = (0 ,0, 0)
WHITE = (255, 255, 255)


# This class represents the ball
# It derives from the "Sprite" class in Pygame
class Ball(pygame.sprite.Sprite):

# Constructor. Pass in the color of the block, and its x and y position
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()

# Create the image of the ball
self.image = pygame.Surface([10, 10])

# Color the ball
self.image.fill(WHITE)

# Get a rectangle object that shows where our image is
self.rect = self.image.get_rect()

# Get attributes for the height/width of the screen
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

# Speed in pixels per cycle
self.speed = 0

# Floating point representation of where the ball is
self.x = 0
self.y = 0

# Direction of ball in degrees
self.direction = 0

# Height and width of the ball
self.width = 10
self.height = 10

# Set the initial ball speed and position
self.reset()

def reset(self):
self.x = random.randrange(50,750)
self.y = 350.0
self.speed=8.0

# Direction of ball (in degrees)
self.direction = random.randrange(-45,45)

# Flip a 'coin'
if random.randrange(2) == 0 :
# Reverse ball direction, let the other guy get it first
self.direction += 180
self.y = 50

# This function will bounce the ball off a horizontal surface (not a vertical one)
def bounce(self,diff):
self.direction = (180-self.direction)%360
self.direction -= diff

# Speed the ball up
self.speed *= 1.1

# Update the position of the ball
def update(self):
# Sine and Cosine work in degrees, so we have to convert them
direction_radians = math.radians(self.direction)

# Change the position (x and y) according to the speed and direction
self.x += self.speed * math.sin(direction_radians)
self.y -= self.speed * math.cos(direction_radians)

if self.y < 0:
self.reset()

if self.y > 600:
self.reset()

# Move the image to where our x and y are
self.rect.x = self.x
self.rect.y = self.y

# Do we bounce off the left of the screen?
if self.x <= 0:
self.direction = (360-self.direction)%360
print(self.direction)
#self.x=1

# Do we bounce of the right side of the screen?
if self.x > self.screenwidth-self.width:
self.direction = (360-self.direction)%360

# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
# Constructor function
def __init__(self, joystick, y_pos):
# Call the parent's constructor
super().__init__()

self.width=75
self.height=15
self.image = pygame.Surface([self.width, self.height])
self.image.fill(WHITE)
self.joystick = joystick

# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.screenheight = pygame.display.get_surface().get_height()
self.screenwidth = pygame.display.get_surface().get_width()

self.rect.x = 0
self.rect.y = y_pos

# Update the player
def update(self):

# This gets the position of the axis on the game controller
# It returns a number between -1.0 and +1.0
horiz_axis_pos= self.joystick.get_axis(0)

# Move x according to the axis. We multiply by 15 to speed up the movement.
self.rect.x=int(self.rect.x+horiz_axis_pos*15)

# Make sure we don't push the player paddle off the right side of the screen
if self.rect.x > self.screenwidth - self.width:
self.rect.x = self.screenwidth - self.width

score1 = 0
score2 = 0

# Call this function so the Pygame library can initialize itself
pygame.init()

# Create an 800x600 sized screen
screen = pygame.display.set_mode([800, 600])

# Set the title of the window
pygame.display.set_caption('Pong')

# Enable this to make the mouse disappear when over our window
pygame.mouse.set_visible(0)

# This is a font we use to draw text on the screen (size 36)
font = pygame.font.Font(None, 36)

# Create a surface we can draw on
background = pygame.Surface(screen.get_size())

# Create the ball
ball = Ball()
# Create a group of 1 ball (used in checking collisions)
balls = pygame.sprite.Group()
balls.add(ball)

# Count the joysticks the computer has
joystick_count = pygame.joystick.get_count()
if joystick_count < 1:
# No joysticks!
print ("Error, I didn't find enough joysticks.")
pygame.quit()
exit()
else:
# Use joystick #0 and initialize it
joystick1 = pygame.joystick.Joystick(0)
joystick1.init()
joystick2 = pygame.joystick.Joystick(1)
joystick2.init()

# Create the player paddle object
player1 = Player(joystick1,580)
player2 = Player(joystick2,25)

movingsprites = pygame.sprite.Group()
movingsprites.add(player1)
movingsprites.add(player2)
movingsprites.add(ball)

clock = pygame.time.Clock()
done = False
exit_program = False

while not exit_program:

# Clear the screen
screen.fill(BLACK)

for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_program = True

# Stop the game if there is an imbalance of 3 points
if abs(score1 - score2) > 3:
done = True

if not done:
# Update the player and ball positions
player1.update()
player2.update()
ball.update()

# If we are done, print game over
if done:
text = font.render("Game Over", 1, (200, 200, 200))
textpos = text.get_rect(centerx=background.get_width()/2)
textpos.top = 50
screen.blit(text, textpos)

# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player1, balls, False):
# The 'diff' lets you try to bounce the ball left or right depending where on the paddle you hit it
diff = (player1.rect.x + player1.width/2) - (ball.rect.x+ball.width/2)

# Set the ball's y position in case we hit the ball on the edge of the paddle
ball.y = 570
ball.bounce(diff)
score1 += 1

# See if the ball hits the player paddle
if pygame.sprite.spritecollide(player2, balls, False):
# The 'diff' lets you try to bounce the ball left or right depending where on the paddle you hit it
diff = (player2.rect.x + player2.width/2) - (ball.rect.x+ball.width/2)

# Set the ball's y position in case we hit the ball on the edge of the paddle
ball.y = 40
ball.bounce(diff)
score2 += 1

# Print the score
scoreprint = "Player 1: "+str(score1)
text = font.render(scoreprint, 1, WHITE)
textpos = (0, 0)
screen.blit(text, textpos)

scoreprint = "Player 2: "+str(score2)
text = font.render(scoreprint, 1, WHITE)
textpos = (300, 0)
screen.blit(text, textpos)

# Draw Everything
movingsprites.draw(screen)

# Update the screen
pygame.display.flip()

clock.tick(30)

pygame.quit()


Related Solutions

Create a C++ code for the mastermind game using classes(private classes and public classes). Using this...
Create a C++ code for the mastermind game using classes(private classes and public classes). Using this uml as a reference.
Can someone tell me what is wrong with this code? Python pong game using graphics.py When...
Can someone tell me what is wrong with this code? Python pong game using graphics.py When the ball moves the paddles don't move and when the paddles move the ball doesn't move. from graphics import * import time, random def racket1_up(racket1):    racket1.move(0,20)        def racket1_down(racket1):    racket1.move(0,-20)   def racket2_up(racket2):    racket2.move(0,20)   def racket2_down(racket2):    racket2.move(0,-20)   def bounceInBox(shape, dx, dy, xLow, xHigh, yLow, yHigh):     delay = .005     for i in range(600):         shape.move(dx, dy)         center = shape.getCenter()         x = center.getX()         y = center.getY()         if x...
I need to deep clone these 4 classes, using the cloneable interface. This is my code...
I need to deep clone these 4 classes, using the cloneable interface. This is my code so far. Is it correct or do I need to make any changes? class Record implements Cloneable { private String CNAME; private ArrayList<Subject> eCores; private Major eMajor; private ArrayList<Subject> eElectives; private int totalCredit; private Status status; private ArrayList<Student> students; @Override protected Record clone() throws CloneNotSupportedException { Record record = (Record) super.clone(); record.eMajor = (Major) eMajor.clone(); eCores = new ArrayList<>(); for (Subject s : eCores)...
Can you program Exploding kittens card game in c++ using linked lists and classes! The game...
Can you program Exploding kittens card game in c++ using linked lists and classes! The game is played with between 2 and 4 players. You'll have a deck of cards containing some Exploding Kittens. You play the game by putting the deck face down and taking turns drawing cards until someone draws an Exploding Kitten. When that happens, that person explodes. They are now dead and out of the game. This process continues until there's only one player left, who...
Fill in needed code to finish Mastermind program in Python 3.7 syntax Plays the game of...
Fill in needed code to finish Mastermind program in Python 3.7 syntax Plays the game of Mastermind. The computer chooses 4 colored pegs (the code) from the colors Red, Green, Blue, Yellow, Turquoise, Magenta. There can be more than one of each color, and order is important. The player guesses a series of 4 colors (the guess). The computer compares the guess to the code, and tells the player how many colors in the guess are correct, and how many...
6. A and B are playing a short game of ping pong where A serves 3...
6. A and B are playing a short game of ping pong where A serves 3 times and B also serves 3 times. If after these six points one of them is ahead the game ends, otherwise they go into a second phase. Suppose that A wins 70% of the points when they serve and 40% of the points when B serves. Let’s look at the first phase. a) (3 pts) Find the probability that A or B wins 0,...
Assignment6A: This used to be entertainment. If you haven’t played the classic game Pong, then you...
Assignment6A: This used to be entertainment. If you haven’t played the classic game Pong, then you are now required to do so. Though it doesn’t capture the poor quality of the original, you can find an emulator at Pong-2.com. Play it (using the keyboard).   Do you see how the ball bounces off of the walls and the paddles? You’re going to learn how to do this by creating class Ball. A Ball has an X and Y position. Equally important,...
I am writing this machine learning code (classification) to clssify between two classes. I started by...
I am writing this machine learning code (classification) to clssify between two classes. I started by having one feature to capture for all my images. for example: class A=[(4295046.0, 1), (4998220.0, 1), (4565017.0, 1), (4078291.0, 1), (4350411.0, 1), (4434050.0, 1), (4201831.0, 1), (4203570.0, 1), (4197025.0, 1), (4110781.0, 1), (4080568.0, 1), (4276499.0, 1), (4363551.0, 1), (4241573.0, 1), (4455070.0, 1), (5682823.0, 1), (5572122.0, 1), (5382890.0, 1), (5217487.0, 1), (4714908.0, 1), (4697137.0, 1), (4737784.0, 1), (4648881.0, 1), (4591211.0, 1), (4750706.0, 1), (5067788.0, 1),...
Write a code for simple racing game (using dots) on c coding.
Write a code for simple racing game (using dots) on c coding.
Write a code for simple racing game (using dots) on c program.
Write a code for simple racing game (using dots) on c program.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT