Question

In: Computer Science

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 < xLow:

            dx = -dx

        elif x > xHigh:

            dx = -dx

        if y < yLow:

            dy = -dy

        elif y > yHigh:

            dy = -dy            

        time.sleep(delay)

def getRandomPoint(xLow, xHigh, yLow, yHigh):

    x = random.randrange(xLow, xHigh+1)

    y = random.randrange(yLow, yHigh+1)

    return Point(x, y)   

def makeDisk(center, radius, win):

    disk = Circle(center, radius)

    disk.setOutline("orange")

    disk.setFill("orange")

    disk.draw(win)

    return disk

def createRacket1(win):

    #racket 1

    racket1 = Rectangle(Point(5,1),Point(10,70))

    racket1.setOutline("red")

    racket1.setFill("red")

    racket1.draw(win)

    racket1.move(580,170)

    return racket1

def createRacket2(win):

    racket2 = Rectangle(Point(5,1),Point(10,70))

    racket2.setOutline("blue")

    racket2.setFill("blue")

    racket2.draw(win)

    racket2.move(5,170)

    return racket2

def movePaddles(racket1,racket2,win):

  

    while True:

    #move racket

        key = win.checkKey()

        if key == "q":

            break

        elif key == "Up":

            racket1_up(racket1)

        elif key == "Down":

            racket1_down(racket1)

        elif key == "a":

            racket2_up(racket2)

        elif key == "z":

            racket2_down(racket2)

def bounceBall(dx, dy):

    

    

    winWidth = 600

    winHeight = 400

    win = GraphWin("Ping Pong", winWidth, winHeight)

    win.setBackground("green")

    win.setCoords(0,0,winWidth, winHeight)

    radius = 8

    xLow = radius

    xHigh = winWidth - radius

    yLow = radius

    yHigh = winHeight - radius

    center = getRandomPoint(xLow, xHigh, yLow, yHigh)

    ball = makeDisk(center, radius, win)

    paddle1 = createRacket1(win)

    paddle2 = createRacket2(win)

    bounceInBox(ball, dx, dy, xLow, xHigh, yLow, yHigh)

    movePaddles(paddle1,paddle2,win)

   

     

    

    win.close()

bounceBall(3, 5)


Solutions

Expert Solution

# --- 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

Okay, can someone please tell me what I am doing wrong?? I will show the code...
Okay, can someone please tell me what I am doing wrong?? I will show the code I submitted for the assignment. However, according to my instructor I did it incorrectly but I am not understanding why. I will show the instructor's comment after providing my original code for the assignment. Thank you in advance. * * * * * HourlyTest Class * * * * * import java.util.Scanner; public class HourlyTest {    public static void main(String[] args)     {        ...
can someone tell me if i am wrong on any of these???? THANKS In order to...
can someone tell me if i am wrong on any of these???? THANKS In order to be able to deliver an effective persuasive speech, you need to be able to detect fallacies in your own as well as others’ speeches. The following statements of reasoning are all examples of the following fallacies: Hasty generalization, mistaken cause, invalid analogy, red herring, Ad hominem, false dilemma, bandwagon or slippery slope. 1. __________bandwagon fallacy_______ I don’t see any reason to wear a helmet...
Can you tell me what is wrong with this code ? def update_char_view(phrase: str, current_view: str,...
Can you tell me what is wrong with this code ? def update_char_view(phrase: str, current_view: str, index: int, guess: str)->str: if guess in phrase: current_view = current_view.replace(current_view[index], guess) else: current_view = current_view    return current_view update_char_view("animal", "a^imal" , 1, "n") 'animal' update_char_view("animal", "a^m^l", 3, "a") 'aamal'
Can someone look into my code and tell me what do you think: Thats Palindrome; //class...
Can someone look into my code and tell me what do you think: Thats Palindrome; //class name Palindrome public class Palindrome {    public static void palindromeChecker(String... str) {        // takes string one by one        for (String s : str) {            // creates a stringbuilder for s            StringBuilder sb = new StringBuilder(s);            // reverses the sb            sb.reverse();            // checks if both...
Can someone please explain to me why "return 1" in this Python code returns the factorial...
Can someone please explain to me why "return 1" in this Python code returns the factorial of a given number? I understand recursion, but I do not understand why factorial(5) returns 120 when it clearly says to return 1. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
can someone tell me why I'm getting the error code on Eclipse IDE: Error: Main method...
can someone tell me why I'm getting the error code on Eclipse IDE: Error: Main method is not static in class StaticInitializationBlock, please define the main method as:    public static void main(String[] args) This is what I'm working on class A { static int i; static { System.out.println(1); i = 100; } } public class StaticInitializationBlock { static { System.out.println(2); } public static void main(String[] args) { System.out.println(3); System.out.println(A.i); } }
Can someone tell me the complications and safety for hemorrhagic stroke? this is for a pathophysiology...
Can someone tell me the complications and safety for hemorrhagic stroke? this is for a pathophysiology class
Hi there Can someone tell me. If someone file a case against you and you dont...
Hi there Can someone tell me. If someone file a case against you and you dont have money to fight against it. Then what person should do in that situation.? If someone file a sexual harassment case?
please show me or tell me a trick, on how can i tell right away when...
please show me or tell me a trick, on how can i tell right away when a characteristics equation(system) is 1)overdamped 2)underdamped 3)critically damped 4) nonlinear show each an example write neatly!!!!!
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------...
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------ class Robot{ int serialNumber; boolean flies,autonomous,teleoperated; public void setCapabilities(int serialNumber, boolean flies, boolean autonomous, boolean teleoperated){ this.serialNumber = serialNumber; this.flies = flies; this.autonomous = autonomous; this.teleoperated = teleoperated; } public int getSerialNumber(){ return this.serialNumber; } public boolean canFly(){ return this.flies; } public boolean isAutonomous(){ return this.autonomous; } public boolean isTeleoperated(){ return this.teleoperated; } public String getCapabilities(){ StringBuilder str = new StringBuilder(); if(this.flies){str.append("canFly");str.append(" ");} if(this.autonomous){str.append("autonomous");str.append("...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT