error with first simple game with Pygame - python

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.

Related

Was following a tut on pygame sprites and got some errors, not sure whats wrong with my code it says line 462 has an error, there is no line 462

This is my code. If you respond please include full code, i am bad at replacing things.
import pygame
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0)
pygame.init()
class Will(pygame.sprite.Sprite):
def __init__(self,width,height, pos_y,pos_x,color):
super().__init__()
self.image = pygame.Surface([width,height])
self.image.fill(black)
self.rect = self.image.get_rect()
clock = pygame.time.Clock()
display = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Slap Chris Rock!')
will = Will(50,50,100,100,(black))
will_group = pygame.sprite.Group()
will_group.add(Will)
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
# print(event)
display.fill(white)
pygame.display.update()
pygame.quit()
quit()
will_group.draw(display)
please note these are the actual indentations. my last post had wrong indentations, i have fixed that.
You didn't include the full code so i can't be 100% sure, but from what i tested, the solution is pretty simple, you just have to replace the
will_group.add(Will) by will_group.add(will) with a non caped "will". What your code does is that it tries to add the class Will to a group, and not the instance of Will named will. Try avoiding similar names and you will have less errors like this one.
Edit: in fact the whole code was there, but the indentation is messed up. Here is the working code:
import pygame
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0)
pygame.init()
class Will(pygame.sprite.Sprite):
def __init__(self,width,height, pos_y,pos_x,color):
super().__init__()
self.image = pygame.Surface([width,height])
self.image.fill(black)
self.rect = self.image.get_rect()
clock = pygame.time.Clock()
display = pygame.display.set_mode((500, 500))
pygame.display.set_caption('Slap Chris Rock!')
will = Will(50,50,100,100,(black))
will_group = pygame.sprite.Group()
will_group.add(will)
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
# print(event)
display.fill(white)
pygame.display.update()
pygame.quit()
quit()
will_group.draw(display)

I'm very new to python and one of my images will not draw onto the screen

I was trying to draw an image onto the screen but I keep getting errors. The error keeps saying "video system not initialized". I am new to python, can anyone help?
import pygame
import os
#game window
WIN = pygame.display.set_mode((1000, 800))
NAME = pygame.display.set_caption("Space War!")
#FPS limit
FPS = (60)
#image i am trying to draw onto screen
SPACE_BACKGROUND = pygame.image.load(os.path.join('space_background.png'))
pygame.init()
#allows pygame to quit
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#updates images
pygame.display.update()
#calling def main(): function
if __name__ == "__main__":
main()
do:
def main():
clock = pygame.time.Clock()
run = True
FPS = 60
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#updates images
WIN.blit(SPACE_BACKGROUND, (0, 0)) #you FORGOT this part
pygame.display.update()
BTW the main function cannot access the global 'FPS' variable so declare that within the 'main' function(make it local).

Pygame Side Scroller

I've written my code and whenever I run it, I expect for it to open up the screen with the background but instead nothing happens at all. I don't know where I went wrong or what I did wrong.
My code:
import os.path
import sys
import pygame
from settings import Settings
class Slingshot_Adventures:
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('Slingshot Adventures')
self.bg_color = (0, 0, 0)
bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))
def run_game(self):
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = Slingshot_Adventures()
ai.run_game
You have set the local variable bg in the constructor of the class Slingshot_Adventures, but you did not set the attribute self.bg:
bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))
self.bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))
class Slingshot_Adventures:
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('Slingshot Adventures')
self.bg_color = (0, 0, 0)
#put your path to the image here
self.image = pygame.image.load(r"path/to/your/image.png")
def run_game(self):
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
self.screen.blit(self.image, (0, 0))
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = Slingshot_Adventures()
ai.run_game()

cannot convert without pygame.display initialized error in pygame

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?

PyGame: Nothing Happens

I am making a game in pygame and when I go to run the game nothing is happening. A black box appears but does nothing at all there is no display etc. Also what bugs me is the fact the Python Shell is not displaying any errors at all. Here is the code for the main file:
import pygame
import sys
import random
import pygame.mixer
import math
from constants import *
from player import *
class Game():
def __init__(self):
#States (Not country states)
self.game_state = STATE_INGAME
#State variables
#self.stateMenu =
#Screen
size = SCREEN_WIDTH, SCREEN_HEIGHT
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption('WIP')
self.screen_rect = self.screen.get_rect()
# Player
self.player = Player(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
def run(self):
clock = pygame.time.Clock()
if self.game_state == STATE_INGAME:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.player_move()
self.player.update()
self.player.render(self.screen)
clock.tick(100)
def player_move(self):
# move player and check for collision at the same time
self.player.rect.x += self.player.velX
self.player.rect.y += self.player.velY
Game().run()
I have checked the player file many times and there are NO errors in there at all. Well not from what I can see. Thanks for the help!
You need a while-loop:
def run(self):
clock = pygame.time.Clock()
while True:
if self.game_state == STATE_INGAME:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.player_move()
self.player.update()
self.player.render(self.screen)
clock.tick(100)

Categories