1
votes

I'm working on making a game for a project at my university using pygame. All I'm trying to get done right now is create a ball that can be controlled to go back and forth on the screen when the user presses the left and right arrow keys. Honestly I don't really know what I'm doing, so I'm using the code in the pygame documentation that was used for pong as the base for my game. My code is below, and if someone knows why I'm getting the error that's in the title, please let me know.

try:
        import sys
        import random
        import math
        import os
        import getopt
        import pygame
        from socket import *
        from pygame.locals import *
except ImportError, err:
        print "couldn't load module. %s" % (err)
        sys.exit(2)

def load_png(name):
    """ Load image and return image object"""
    fullname = name
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except pygame.error, message:
            print 'Cannot load image:', fullname
            raise SystemExit, message
    return image, image.get_rect()

class Ball(pygame.sprite.Sprite):
    def __init__(self, (xy)):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_png('ball.png')
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()
        self.hit = 0
        self.speed = 10
        self.state = "still"

    def reinit(self):
        self.state = "still"
        self.movepos = [0,0]
        if self.side == "left":
            self.rect.midleft = self.area.midleft

    def update(self):
        newpos = self.rect.move(self.movepos)
        if self.area.contains(newpos):
            self.rect = newpos
        pygame.event.pump()

    def moveleft(self):
        self.movepos[1] = self.movepos[1] - (self.speed)
        self.state = "moveleft"

    def moveright(self):
        self.movepos[1] = self.movepos[1] + (self.speed)
        self.state = "moveright"

def main():
    running = True
    pygame.init()
    (width, height) = (800, 600)
    screen = pygame.display.set_mode((width, height))

    # Fill background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((0, 0, 0))
    screen.blit(background, (0, 0))
    pygame.display.flip()


    global player
    player = Ball("left")
    playersprite = pygame.sprite.RenderPlain(player)

    playersprite.draw(screen)
    player.update()
    while running:

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_q:
                    running = False
                if event.key == K_LEFT:
                    player.moveleft()
                if event.key == K_RIGHT:
                    player.moveright()
            elif event.type == KEYUP:
                if event.key == K_UP or event.key == K_DOWN:
                    player.movepos = [0,0]
                    player.state = "still"
        #screen.blit(background, ball.rect, ball.rect)
        screen.blit(background, player.rect, player.rect)
        #screen.blit(background, player2.rect, player2.rect)
        #ballsprite.update()
        playersprite.update()
        #ballsprite.draw(screen)
        playersprite.draw(screen)



if __name__ == '__main__': main()
2

2 Answers

1
votes

All I'm trying to get done right now is create a ball that can be controlled to go back and forth on the screen when the user presses the left and right arrow keys.

You are massively over complicating this, you don't need 102 lines to move a ball around. I wrote and commented a simple example that I think could help you a lot. All you really need to do is detect key presses and then update an x and y variable then draw the image using the x and y variables.

import pygame

screen_width = 1280
screen_height = 720

pygame.init()
screen = pygame.display.set_mode((screen_width,screen_height))

BLACK = (0,0,0)

ballImg = pygame.image.load("ball.jpg")
ballPosition = [0,0]
speed = 1


def game_loop():
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        #get all the keys being pressed
        keys = pygame.key.get_pressed()


        #depending on what key the user presses, update ball x and y position accordingly
        if keys[pygame.K_UP]:
            ballPosition[1] -= speed
        if keys[pygame.K_DOWN]:
            ballPosition[1] += speed
        if keys[pygame.K_LEFT]:
            ballPosition[0] -= speed
        if keys[pygame.K_RIGHT]:
            ballPosition[0] += speed


        screen.fill(BLACK) #fill the screen with black
        screen.blit(ballImg, ballPosition) #draw the ball
        pygame.display.update() #update the screen

game_loop()
0
votes

What versions of python/pygame are you running as when I tested your code with python 3.4, I first got syntax errors with your try: except statements, but this may be due to different syntax over different versions. After fixing that I ran into the issue of movepos not being defined when pressing left or right. Adding self.movepos = [0, 0] to the __init__() of the Ball class fixed this.

I never ran into the error you described, however the game did give a constant black screen no matter what I do.

What I'm trying to say is that errors can sometimes be caused by other mistakes earlier on in the code that don't get picked up. One of the answers here sums it up nicely: error: video system not initialized; Is there a solution?

Also, what variables store the balls x and y position? I couldn't seem to make out how you were controlling that?