1

To preface, I am completely new to programming and am attempting to teach myself. Currently, I have a limited understanding of CS jargon so any explanation in layman terminology would be most appreciated.

I am using programarcadegames.com to learn basic computer science. I've created a a game that collects sprites using the pygame library and would like to break my code up into multiple files. My file, 'Sprite Moving.py' imports block_library.py to obtain the Block class. However, running the program, I receive the error ImportError: No Module named Block. I've read through Stackoverflow and some of the issues people have ran into include library imported is the same name or files not located in path. I believe I've checked these off. Any advice?

Did some google, and I believe this is what you are asking for - pastebin.com/J9qkjQ7F. I originally had all of my files in a separate folder, but one of the issues I saw while researching was the file may not be included in the path? So I dumped all of my relevant files into idlelib.

Thanks in advance!

Sprite Moving.py

"""
Use sprites to collect blocks.
#Tony's lab 13 that will use sprites to collect blocks and print the score.

"""
import pygame
import random
import Block

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


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

    # -- Methods
    def __init__(self, filename):
        """Constructor function"""
        # Call the parent's constructor
        super().__init__()

        # Set height, width
        self.image = pygame.image.load(filename).convert()
        self.image.set_colorkey(WHITE)

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

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

        if self.rect.left <= -15:
            self.rect.x = 715
        elif self.rect.left >= 715:
            self.rect.x = -15
        elif self.rect.y <= -15:
            self.rect.y = 415
        elif self.rect.y >= 415:
            self.rect.y = -15



# 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])
pygame.display.set_caption("Fish World")

# 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_good = pygame.sprite.Group()
block_list_bad = 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 good block
    good_block = block_library.Block("FishBlue.png")

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

    # Add the block to the list of objects
    block_list_good.add(block)
    all_sprites_list.add(block)
for i in range(50):
    #This represents a bad block
    bad_block = block_library.Block("bomb100.png")

    #Sets blocks at random coordinates
    block.rect.x = random.randrange(20, screen_width - 20)
    block.rect.y = random.randrange(20, screen_height - 20)

    #Adds block to bad list and all list
    block_list_bad.add(block)
    all_sprites_list.add(block)



# Create a RED player block
player = Player("shark.png")
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

# Used to blit score onto the screen
font = pygame.font.Font(None, 25)

# Load sound FXs
good_block = pygame.mixer.Sound("good_block.wav")
bad_block = pygame.mixer.Sound("bad_block.wav")


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

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                player.change_y = 0
            elif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                player.change_x = 0

    # Clear the screen
    screen.fill(WHITE)

    #Update sprite positions
    all_sprites_list.update()


    # See if the player block has collided with a good block.
    blocks_good_hit_list = pygame.sprite.spritecollide(player, block_list_good, True)

    # Check the list of collisions.
    for block in blocks_good_hit_list:
        score += 1
        good_block.play()


    # See if the player block has collided with a bad block.
    blocks_bad_hit_list = pygame.sprite.spritecollide(player, block_list_bad, True)

    # Check the list of collisions.
    for block in blocks_bad_hit_list:
        score -= 1
        bad_block.play()




    # Draw all the spites
    all_sprites_list.draw(screen)

    # Blit score onto screen
    score_stamp = font.render("Score " + str(score), True, BLACK)
    screen.blit(score_stamp, [10, 10])

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

block_library.py

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

    def __init__(self, filename):
        """ 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.image.load(filename).convert()
        self.image.set_colorkey(WHITE)

        # 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()
yash
  • 1,357
  • 2
  • 23
  • 34
ToeKnee
  • 35
  • 1
  • 3
  • 2
    Please post the directory structure – yash Nov 07 '17 at 04:47
  • Please add it to your post :) – yash Nov 07 '17 at 05:02
  • 1
    Can you also post the code in `Sprite Moving.py`? – yash Nov 07 '17 at 05:05
  • You need to write `from block_library import Block` – yash Nov 07 '17 at 05:18
  • Also refer https://stackoverflow.com/questions/2349991/python-how-to-import-other-python-files?rq=1 – yash Nov 07 '17 at 05:21
  • Success! Thank you, I tried the import method you outlined before asking the question, but it still gave me the issue. Tried it again and it worked. I know that you can import via 'import xxxx' or 'from xxx import z'. Could you explain why I can't use the first method to import my library same as I import the library random and pygame? Thanks again!!! – ToeKnee Nov 07 '17 at 05:30
  • Usually `import` is followed by a **module name**. So when you are using `import Block` it will search for a module named `Block` in it's `sys.path`. But in your case Block is not a module. It is a part of a module. So either you can just import Block as i mentioned above or you import everything as `from block_library import *` or you could just import the module itself `import block_library`. I suggest you to read the documentation about importing because it's very confusing and highly valuable when dealing with larger codebases – yash Nov 08 '17 at 16:29

0 Answers0