cannot convert without pygame.display initialized error in pygame - python

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

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

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?

Related

How to overwrite the y position of the bird in the game? [duplicate]

im trying to get my image (bird) to move up and down on the screen but i cant figure out how to do it here is what i tried im sure its way off but im trying to figure it out if anyone can help that would be great!
import pygame
import os
screen = pygame.display.set_mode((640, 400))
running = 1
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill([255, 255, 255])
clock = pygame.time.Clock()
clock.tick(0.5)
pygame.display.flip()
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
screen.blit( bird, ( 0, 0 ) )
pygame.display.update()
class game(object):
def move(self, x, y):
self.player.center[0] += x
self.player.center[1] += y
if event.key == K_UP:
player.move(0,5)
if event.key == K_DOWN:
player.move(0,-5)
game()
im trying to get it to move down on the down button press and up on the UP key press
As stated by ecline6, bird is the least of your worries at this point.
Consider reading this book..
For now, First let's clean up your code...
import pygame
import os
# let's address the class a little later..
pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # fill the screen
screen.blit(bird, (0, 0)) # then blit the bird
pygame.display.update() # Just do one thing, update/flip.
clock.tick(40) # This call will regulate your FPS (to be 40 or less)
Now the reason that your "bird" is not moving is:
When you blit the image, ie: screen.blit(bird, (0, 0)),
The (0,0) is constant, so it won't move.
Here's the final code, with the output you want (try it) and read the comments:
import pygame
import os
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')
class Bird(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load(img_path)
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((640, 400))
bird = Bird() # create an instance
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
bird.handle_keys() # handle the keys
screen.fill((255,255,255)) # fill the screen with white
bird.draw(screen) # draw the bird to the screen
pygame.display.update() # update the screen
clock.tick(40)
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
If you want to achieve a continuously movement, you have to use pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
See also Key and Keyboard event and How can I make a sprite move when key is held down.
Minimal example:
import pygame
import os
class Bird(object):
def __init__(self):
self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
self.center = [100, 200]
def move(self, x, y):
self.center[0] += x
self.center[1] += y
def draw(self, surf):
surf.blit(self.image, self.center)
class game(object):
def __init__(self):
self.screen = pygame.display.set_mode((640, 400))
self.clock = pygame.time.Clock()
self.player = Bird()
def run(self):
running = 1
while running:
self.clock.tick(60)
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
keys = pygame.key.get_pressed()
move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
self.player.move(move_x * 5, move_y * 5)
self.screen.fill([255, 255, 255])
self.player.draw(self.screen)
pygame.display.update()
g = game()
g.run()

How do i get my game to resize with the window

Im wokring on my own version of Pacman and am currently trying to get the window to resize. i read an answer here :https://reformatcode.com/code/python/pygame-how-do-i-resize-a-surface-and-keep-all-objects-within-proportionate-to-the-new-window-size. but it didnt help me in my case. at the i have 2 screen, screen and fake screen. if i set everything to blit on fake screen they appear but dont update themselces (pacman wont move). if i set them to screen they appear and update but dont resize. any help or suggestions would be greatly appreciated. btw its still a work on progress
import pygame
from Variables import pelletspawns #imports pellet spwans list from different script
from pygame.locals import *
#Initialisation
pygame.init()
pygame.display.set_caption("Pacman")
myfont = pygame.font.SysFont("monospace", 15)
screen = pygame.display.set_mode((448, 576)) #Creates screen object
fake_screen = screen.copy()
pic = pygame.surface.Surface((50,50))
pic.fill((255,100,100))
clock = pygame.time.Clock() #Creates clock object
Fin = False
#Declaring Variables
FPS = 60
MoveLeft = pygame.K_LEFT
MoveRight = pygame.K_RIGHT
MoveUp = pygame.K_UP
MoveDown = pygame.K_DOWN
#Load images
PACMAN_MAP = pygame.image.load("images/pacman_map.png").convert_alpha()
PACMANSPRITE = pygame.image.load("images/pacman.png").convert_alpha()
#pacmans class
class SpriteClass(pygame.sprite.Sprite):
def __init__(self, image, x, y):
self.image = image
self.y=y
self.x=x
self.rect = self.image.get_rect()
self.rect.left = self.x
self.rect.top = self.y
self.rect.width=16
self.rect.height=16
#draws Pacman
def draw(self, surface):
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
# move pacman
def movement(self):
pressed= pygame.key.get_pressed()
if pressed[MoveUp]:
self.y -= 2
print('key pressed')
if pressed[MoveDown]:
self.y += 2
print('key pressed')
if pressed[MoveLeft]:
self.x -= 2
print('key pressed')
if pressed[MoveRight]:
self.x += 2
print('key pressed')
self.rect.left = self.x
self.rect.top = self.y
print(self.x,self.y)
#instances Pacman
Pacman = SpriteClass(PACMANSPRITE, 216 ,416)
#Function to spawn pellets
def SpawnPellets(pelletspawns):
pelletx=0 #the temp x co-ordinate for the pellet to spawn
pellety= -8 #the temp y co-ordinate for the pellet to spawn (starts at -ve 0.5(gridscpare) for allignment
for row in pelletspawns:
#adds 1 grid space to correctly align spawns
pellety += 16
for pellet in row:
pelletx= 16*pellet
pelletx -=8
pygame.draw.circle(screen,(255, 204, 153), (pelletx, pellety) , 5)
#main game loop
while not Fin:
#For event is used to close the program
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.quit()
if event.type == VIDEORESIZE:
screen = pygame.display.set_mode(event.dict['size'],RESIZABLE)
screen.blit(pygame.transform.scale(fake_screen, event.dict['size']), (0, 0))
pygame.display.flip()
#calls movement function
Pacman.movement()
#blits pacman map as background
screen.blit(PACMAN_MAP, (0, 0))
#draws pacman
Pacman.draw(screen)
#Spawns pellets
SpawnPellets(pelletspawns)
#draws screen
pygame.display.flip()
clock.tick(FPS)
I figured it out, i needed to move
screen.blit(pygame.transform.scale(fake_screen, event.dict['size']), (0, 0))
into the core game loop just above clock.tick. i tried this before but ran into a key error as there was no event for event.dict['size'] to get a size from, so i made a variable in the for event in pygame.event.get(): loop, and then passed that variable where it was asking for event.dict['size']. Here is the section of code i changed:
#main game loop
while not Fin:
#For event is used to close the program
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.quit()
if event.type == VIDEORESIZE:
size = event.dict['size']
screen = pygame.display.set_mode(size,RESIZABLE)
#calls movement function
Pacman.movement()
#blits pacman map as background
fake_screen.blit(PACMAN_MAP, (0, 0))
#draws pacman
Pacman.draw(fake_screen)
#Spawns pellets
SpawnPellets(pelletspawns)
#draws screen
screen.blit(pygame.transform.scale(fake_screen, size), (0, 0))
pygame.display.flip()
clock.tick(FPS)

How do I make the paddle move with the arrow keys?

I'm trying to make it so that you can move the paddle (making a pong game) with the arrow keys. I already have most of the code but I'm confused as to what I would pass to the function that will move the paddle.
Here is my code (this was base code given to us by our instructor, we just modified parts of it):
import math
import random
import sys, pygame
from pygame.locals import *
import ball
import colors
import paddle
# draw the scene
def draw(screen, ball1, paddle1) :
screen.fill((128, 128, 128))
ball1.draw_ball(screen)
paddle1.draw_paddle(screen)
#function to start up the main drawing
def main():
pygame.init()
width = 600
height = 600
screen = pygame.display.set_mode((width, height))
ball1 = ball.Ball(300, 1, 40, colors.RED)
paddle1 = paddle.Paddle(100, 575, colors.BLUE, 100, 20)
while 1:
for event in pygame.event.get():
if event.type == QUIT: sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
paddle1.update_paddle()
if event.key == pygame.K_LEFT:
paddle1.update_paddle()
draw(screen, ball1, paddle1)
pygame.display.flip()
if __name__ == '__main__':
main()
In the while loop, where it says "paddle1.update_paddle()", I need to pass it some arguments to make the paddle move. But this is where I got confused. (I am just starting to learn python!)
Here is what the update_paddle function looks like:
def update_paddle(self, dx):
self.x += dx
So as you can see, update_paddle just increments the paddle's x position by an input value. But what I'm confused about is, what exactly would I put as the input value?
Maybe you can do something like:
def update_paddle(self, dir, dx):
if dir=='left':
self.x -= dx
elif dir=='right':
self.x += dx
Then you can simply do:
paddle1.update_paddle('left',5)
paddle2.update_paddle('right',3)

error with first simple game with Pygame

import os, sys
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.mouse.set_visible(False)
def loadimage(name, colorkey=None):
try:
pygame.image.load(os.path.join(name))
except pygame.error, message:
print "Failed to load image ",name
class Userplane(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = loadimage("userplane.bmp")
def update(self):
pos = pygame.mouse.get_pos()
self.rect.midtop = pos
def main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.mouse.set_visible(False)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))
screen.blit(background, (0,0))
pygame.display.flip()
user = Userplane()
allsprites = pygame.sprite.RenderPlain((user))
clock = pygame.time.Clock()
while 1:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return
allsprites.update()
screen.blit(background(0,0))
pygame.display.flip()
if __name__ == '__main__': main()
hi im very new, ive just finished the codeacademy course and the chimppunch game in the pygame tutorial. Im using almost an exact copy of that game but instead im trying to display a plane at the bottom of the screen instead of a fist. my Userplane class keeps throwing the following error and i dont know why, 'typeerror: 'nonetype' object is not iterable
The reason is in your loadimage function.
It does not return the loaded image, so python is complaining that you are trying to assign self.image, self.rect from a NoneType.
In Python if a function does not return anything, it is assumed to return None.

How to move Sprite in Pygame

im trying to get my image (bird) to move up and down on the screen but i cant figure out how to do it here is what i tried im sure its way off but im trying to figure it out if anyone can help that would be great!
import pygame
import os
screen = pygame.display.set_mode((640, 400))
running = 1
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill([255, 255, 255])
clock = pygame.time.Clock()
clock.tick(0.5)
pygame.display.flip()
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
screen.blit( bird, ( 0, 0 ) )
pygame.display.update()
class game(object):
def move(self, x, y):
self.player.center[0] += x
self.player.center[1] += y
if event.key == K_UP:
player.move(0,5)
if event.key == K_DOWN:
player.move(0,-5)
game()
im trying to get it to move down on the down button press and up on the UP key press
As stated by ecline6, bird is the least of your worries at this point.
Consider reading this book..
For now, First let's clean up your code...
import pygame
import os
# let's address the class a little later..
pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # fill the screen
screen.blit(bird, (0, 0)) # then blit the bird
pygame.display.update() # Just do one thing, update/flip.
clock.tick(40) # This call will regulate your FPS (to be 40 or less)
Now the reason that your "bird" is not moving is:
When you blit the image, ie: screen.blit(bird, (0, 0)),
The (0,0) is constant, so it won't move.
Here's the final code, with the output you want (try it) and read the comments:
import pygame
import os
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')
class Bird(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load(img_path)
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((640, 400))
bird = Bird() # create an instance
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
bird.handle_keys() # handle the keys
screen.fill((255,255,255)) # fill the screen with white
bird.draw(screen) # draw the bird to the screen
pygame.display.update() # update the screen
clock.tick(40)
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
If you want to achieve a continuously movement, you have to use pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
See also Key and Keyboard event and How can I make a sprite move when key is held down.
Minimal example:
import pygame
import os
class Bird(object):
def __init__(self):
self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
self.center = [100, 200]
def move(self, x, y):
self.center[0] += x
self.center[1] += y
def draw(self, surf):
surf.blit(self.image, self.center)
class game(object):
def __init__(self):
self.screen = pygame.display.set_mode((640, 400))
self.clock = pygame.time.Clock()
self.player = Bird()
def run(self):
running = 1
while running:
self.clock.tick(60)
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
keys = pygame.key.get_pressed()
move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
self.player.move(move_x * 5, move_y * 5)
self.screen.fill([255, 255, 255])
self.player.draw(self.screen)
pygame.display.update()
g = game()
g.run()

Categories