0

I am working through the programarcadegames labs using python and pygame and I am stuck. When I am running this code, I am doing something wrong when I am initializing the block and player classes. The player class is supposed to be its own class and not an instance of Block class.

When I run this program, I am getting this error: 'Block' object has no attribute 'changespeed'

import pygame
import random

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

class Block(pygame.sprite.Sprite):

    def __init__(self, color, width, height):
        """ Constructor. Pass in the color of the block,
        and its x and y position. """

        # Call the parent class (Sprite) constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.Surface([width, height])
        self.image.fill(color)

        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()

class Player (pygame.sprite.Sprite):
    """ The class is the player-controlled sprite. """

    def __init__(self,x,y):
        """Constructor function"""
        # Call the parent's constructor
        super().__init__()

        # -- methods
        # Set height, width
        self.image = pygame.Surface([15, 15])
        self.image.fill(BLACK)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

        # -- Attributes
        # Set speed vector
        self.change_x = 0
        self.change_y = 0

    def changespeed(self, x, y):
        """ Change the speed of the player"""
        self.change_x += x
        self.change_y += y

    def update(self):
        """ Find a new position for the player"""
        self.rect.x += self.change_x
        self.rect.y += self.change_y

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])

# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
block_list = pygame.sprite.Group()

# This is a list of every sprite. 
# All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

for i in range(50):
    # This represents a block
    block = Block(BLACK, 20, 15)

    # Set a random location for the block
    block.rect.x = random.randrange(screen_width)
    block.rect.y = random.randrange(screen_height)

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

# Create a RED player block
player = Block(BLUE, 20, 15)
all_sprites_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True
        # Set the speed based on the key pressed
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_UP:
                player.changespeed(0, -3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, 3)

        # Reset speed when key goes up
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.changespeed(3, 0)
            elif event.key == pygame.K_RIGHT:
                player.changespeed(-3, 0)
            elif event.key == pygame.K_UP:
                player.changespeed(0, 3)
            elif event.key == pygame.K_DOWN:
                player.changespeed(0, -3)

    # Clear the screen
    screen.fill(WHITE)

    # Get the current mouse position. This returns the position
    # as a list of two numbers.
    #pos = pygame.mouse.get_pos()

    # Fetch the x and y out of the list,
       # just like we'd fetch letters out of a string.
    # Set the player object to the mouse location
    #player.rect.x = pos[0]
    #player.rect.y = pos[1]

    # See if the player block has collided with anything.
    blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)

    # Check the list of collisions.
    for block in blocks_hit_list:
        score += 1
        print(score)

    # This calls update on all the sprites
    all_sprites_list.update()

    # Draw all the spites
    all_sprites_list.draw(screen)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Limit to 60 frames per second
    clock.tick(60)

pygame.quit()
3
  • 1
    The error seems to suggest that you're creating a block and trying to use the method changespeed. The classes are not related at all so the error is not that "they're not their own classes". What I think is happening is that you're overwriting the player variable with an instance of block, or putting both the player and block into a list which you iterate through and trying to call 'changespeed' on every object. However, it's not possible to help you any further than that without an minimal reproducible example. Commented Apr 8, 2017 at 19:28
  • 1
    I posted the code in its entirety. When I try to move the player object, that's when it throws an error. Commented Apr 8, 2017 at 21:57
  • 1
    Creating a minimal reproducible example will help you to resolve the problem yourself without any help and is done very quickly (5-10 mins max). If you don't find the error then you'll at least made the question useful for other people looking for answers in Stackoverflow. When people search on Stackoverflow they'll easier find a solution if the problem is contained in a minimal example with complete explanation of the problem and which is easily testable and verifiable. But to give you 2 leading hints: 1. In which line in the code do you initialize (create) the player? 2. When do you call/use the player class? Commented Apr 9, 2017 at 0:35

1 Answer 1

1

Here's the problem: player = Block(BLUE, 20, 15). The player is a Block instance not a Player instance and blocks have got no changespeed method.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the big help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.