Pygame: Loading Sprites With Images - python

To improve my skill with objects, I'm trying to make a game in python to learn how to handle objects in which a I have a sprite called Player that displays an image taken from a file called image.gif using this class:
class Player(pygame.sprite.Sprite):
def __init__(self, width, height):
super().__init__()
self.rect = pygame.Rect(width, height)
self.image = pygame.Surface([width, height])
self.image = pygame.image.load("image.gif").convert_alpha()
# More sprites will be added.
I then used that class for the following code:
import Pysprites as pys
pygame.init()
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GRAY = (255,255,255)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
all_sprites_list = pygame.sprite.Group()
player = pys.Player(44,22)
all_sprites_list.add(player)
carryOn = True
clock=pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
all_sprites_list.update()
clock.tick(60)
all_sprites_list.draw(screen)
pygame.display.flip()
pygame.display.update()
pygame.quit()
and got the error:
Traceback (most recent call last):
File "Game1.py", line 14, in <module>
player = pys.Player(44,22)
File "Pysprites.py", line 9, in __init__
self.rect = pygame.Rect(width, height)
TypeError: Argument must be rect style object
What am I doing wrong? How can I make a sprite with an image without encountering this error?

The pygame.Rect() documentation says it only accepts one of 3 different combinations of arguments, none of which involves only providing two values as you're attempting to do.
I think you should have used self.rect = pygame.Rect(0, 0, width, height) in the Player__init__() method to provide the left, top, width, and height argument combination it expects.

Related

Image not showing up on pygame screen

I am making my own game with pygame for the first time, and I'm using sprites. I'm trying to blit an image onto the screen but it doesn't work. All it shows is a blank white screen.
Here is the code:
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class SpriteSheet(object):
def __init__(self, file_name):
self.sprite_sheet = pygame.image.load(file_name).convert()
def get_image(self, x, y, width, height):
image = pygame.Surface([width, height]).convert()
image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
image.set_colorkey(BLACK)
return image
class Bomb(pygame.sprite.Sprite):
change_x =0
change_y = 0
def __init__(self):
image = pygame.Surface([256, 256]).convert()
sprite_sheet = SpriteSheet("Bomb_anim0001.png")
image = sprite_sheet.get_image(0, 0, 256, 256)
pygame.init()
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
bomb = Bomb()
clock.tick(60)
pygame.display.flip()
pygame.quit()
This is the image:
Click on this link.
Any help will be highly appreciated. Thanks!
You must blit the image on the screen Surface.
But there is more to be done. Add a rect attribute to the Bomb class:
class Bomb(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
sprite_sheet = SpriteSheet("Bomb_anim0001.png")
self.image = sprite_sheet.get_image(0, 0, 256, 256)
self.rect = self.image.get_rect(topleft = (x, y)
self.change_x = 0
self.change_y = 0
Create a pygame.sprite.Group and add the bomb to the Group. draw all the sprites in the Group on the screen:_
bomb = Bomb(100, 100)
all_sprites = pygame.sprite.Group()
all_sprites.add(bomb)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The former delegates the to the update mehtod of the contained pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update():
Calls the update() method on all Sprites in the Group [...]
The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

TypeError: invalid rect assignment, what's wrong?

I try to build a game with sprite of spaceship but when i run the code, i get a error - TypeError: invalid rect assignment. I don't understard what i do wrong. help me please.
import pygame
pygame.init()
size = (600, 600)
Spaceship_position = [260, 510]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Spaceships")
icon = pygame.image.load("D:\\Yahav\\Cyber\\Cyber_Images\\icon.png")
pygame.display.set_icon(icon)
screen.fill((0, 0, 0))
pygame.display.flip()
class Spaceship(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("D:\\Yahav\\Cyber\\Cyber_Images\\spaceship.png")
self.rect = self.image.get_rect()
self.rect.bottom = (100, 100)
all_sprites = pygame.sprite.Group()
spaceship = Spaceship()
all_sprites.add(spaceship)
def main():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
all_sprites.update()
all_sprites.draw(screen)
main()
what i need to do?
The issue is caused by the line
self.rect.bottom = (100, 100)
rect.bottom is the bottom of the rectangle. Hence you have assign a single value to the virtual attribute rect.bottom:
self.rect.bottom = 100
If you want to set the bottom left corner, then you have to assign a tuple:
self.rect.bottomleft = (100, 100)
See pygame.Rect:
The Rect object has several virtual attributes which can be used to move and align the Rect:
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
All of these attributes can be assigned to:
rect1.right = 10
rect2.center = (20,30)

pygame NameError: name 'self' is not defined but can't see indentation issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have seen This question on this but I can not see any indentation issues in my code. How do I fix the error:
NameError: name 'self' is not defined
My code:
import PySimpleGUI as sg
hp = 0
import pygame, random
#Let's import the Car Class
from player import Car
pygame.init()
def play():
font = pygame.font.Font(None, 100)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
BLUE = (100, 100, 255)
speed = 1
colorList = (RED, GREEN, PURPLE, YELLOW, CYAN, BLUE)
SCREENWIDTH=800
SCREENHEIGHT=600
lack_bar = pygame.Surface((SCREENWIDTH, 35))
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()
playerCar = Car(RED, 60, 80, 70)
playerCar.rect.x = 160
playerCar.rect.y = SCREENHEIGHT - 100
car1 = Car(PURPLE, 60, 80, random.randint(50,100))
car1.rect.x = 60
car1.rect.y = -100
car2 = Car(YELLOW, 60, 80, random.randint(50,100))
car2.rect.x = 160
car2.rect.y = -600
car3 = Car(CYAN, 60, 80, random.randint(50,100))
car3.rect.x = 260
car3.rect.y = -300
car4 = Car(BLUE, 60, 80, random.randint(50,100))
car4.rect.x = 360
car4.rect.y = -900
# Add the car to the list of objects
all_sprites_list.add(playerCar)
all_sprites_list.add(car1)
all_sprites_list.add(car2)
all_sprites_list.add(car3)
all_sprites_list.add(car4)
all_coming_cars = pygame.sprite.Group()
all_coming_cars.add(car1)
all_coming_cars.add(car2)
all_coming_cars.add(car3)
all_coming_cars.add(car4)
#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
end()
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_x:
playerCar.moveRight(10)
#Check if there is a car collision
car_collision_list = pygame.sprite.spritecollide(playerCar,all_coming_cars,False)
for car in car_collision_list:
carryOn=False
end()
self.text = font.render("text that should appear", True, (238, 58, 140))
self.screen.blit(self.text, [400,300])
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerCar.moveLeft(5)
if keys[pygame.K_RIGHT]:
playerCar.moveRight(5)
if keys[pygame.K_UP]:
speed += 0.05
if keys[pygame.K_DOWN]:
speed -= 0.05
#Game Logic
for car in all_coming_cars:
car.moveForward(speed)
if car.rect.y > SCREENHEIGHT:
car.changeSpeed(random.randint(50,100))
car.repaint(random.choice(colorList))
car.rect.y = -200
all_sprites_list.update()
#Drawing on Screen
screen.fill(GREEN)
#Draw The Road
pygame.draw.rect(screen, GREY, [40,0, 400,SCREENHEIGHT])
#Draw Line painting on the road
pygame.draw.line(screen, WHITE, [140,0],[140,SCREENHEIGHT],5)
#Draw Line painting on the road
pygame.draw.line(screen, WHITE, [240,0],[240,SCREENHEIGHT],5)
#Draw Line painting on the road
pygame.draw.line(screen, WHITE, [340,0],[340,SCREENHEIGHT],5)
#Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
all_sprites_list.draw(screen)
#Refresh Screen
pygame.display.flip()
#Number of frames per secong e.g. 60
clock.tick(60)
def end():
layout = [[sg.Text("Car Crash"), sg.Button("Try Again"), sg.Button("End")]]
window = sg.Window("Car Crash!!!", layout)
while True:
event, values = window.read()
if event == "End":
window.close()
pygame.quit()
if event == "Try Again":
window.close()
play()
play()
My sprite class:
import pygame
WHITE = (255, 255, 255)
class Car(pygame.sprite.Sprite):
#This class represents a car. It derives from the "Sprite" class in Pygame.
def __init__(self, color, width, height, speed):
# Call the parent class (Sprite) constructor
super().__init__()
# Pass in the color of the car, and its x and y position, width and height.
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
#Initialise attributes of the car.
self.width=width
self.height=height
self.color = color
self.speed = speed
# Draw the car (a rectangle!)
pygame.draw.rect(self.image, self.color, [0, 0, self.width, self.height])
# Instead we could load a proper picture of a car...
# self.image = pygame.image.load("car.png").convert_alpha()
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
def moveRight(self, pixels):
self.rect.x += pixels
def moveLeft(self, pixels):
self.rect.x -= pixels
def moveForward(self, speed):
self.rect.y += self.speed * speed / 20
def moveBackward(self, speed):
self.rect.y -= self.speed * speed / 20
def changeSpeed(self, speed):
self.speed = speed
def repaint(self, color):
self.color = color
pygame.draw.rect(self.image, self.color, [0, 0, self.width, self.height])
what is going on? I am following The answer to this question for how to show text on the screen (picking things up) - what have I missed? My code (except from own contributions) comes from HERE
Whole traceback:
Traceback (most recent call last):
File "C:\Users\tom\Documents\python\In development\Doge those cars\Doge those cars.py", line 154, in <module>
play()
File "C:\Users\tom\Documents\python\In development\Doge those cars\Doge those cars.py", line 90, in play
self.text = font.render("text that should appear", True, (238, 58, 140))
NameError: name 'self' is not defined
The answer was said in the comments. self isn't defined in your code, either as an argument for your function or as a global variable. In fact, your play function isn't even defined in a class, so I'm not too sure as to why you're using the self keyword at all.
Follow the traceback:
in your file Doge those cars.py line 90, that is in the func play()
there is a line that states self.text = font.render("text that should appear", True, (238, 58, 140))
but it isn't in your class, and there is no 'self' defined.

Name Error when trying to build a sprite using pygame

I am starting to use pygame. My first task is to make a sprite and to make it move. So far I am doing fine until I get the error:
Traceback (most recent call last):
File "C:\Users\tom\Documents\python\agame.py", line 33, in <module>
YOU = Player(RED ,20, 30)
NameError: name 'RED' is not defined
My main code so far:
import pygame
import sys
from player import Player
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
init_result = pygame.init()
# Create a game window
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Set title
pygame.display.set_caption("agame")
#game_running keeps loopgoing
game_running = True
while game_running:
# Game content
# Loop through all active events
YOU = Player(RED ,20, 30)
for event in pygame.event.get():
#exit through the X button
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#change background colour to white
game_window.fill((255,255,255))
#update display
pygame.display.update()
As you can see this is the very start of making a sprite.
My sprite class:
import pygame
#creating sprite class
class Player(pygame.sprite.Sprite):
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
super().__init__()
# Pass in the color of the Player, and its x and y position, width and height.
# Set the background color
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw player (a rectangle!)
pygame.draw.rect(self.image, color, [0, 0, width, height])
This has been made in the .py file called player. I am following the tutorials HERE and making my own changes as I go along. I do not understand this error. I am very new to pygame so forgive me if this is obvious.
You have to define the colors RED and WHITE. For instance:
RED = (255, 0, 0)
WHITE = (255, 255, 255)
Or create pygame.Color objects:
RED = pygame.Color("red")
WHITE = pygame.Color("white")
Furthermore you have to use the color argument in the constructor of Player:
class Player(pygame.sprite.Sprite):
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
super().__init__()
# Pass in the color of the Player, and its x and y position, width and height.
# Set the background color
self.image = pygame.Surface([width, height])
self.image.fill(color)

Got an error with pygame and the method update

I'm starting to code and have been following a series of videos to create a game with pygame. However, even when I've followed everything the guy in the video said, and after checking many times mine and his code, I got this error:
File "C:/Users/sdf/PycharmProjects/pygame1/pygametutorial 2/tutorail 1 template.py", line 43, in
all_sprites.update()
TypeError: update() missing 1 required positional argument: 'self'
this is the code I've programmed so far:
import pygame
import random
import sprites as sprites
height = 360
width = 480
FPS = 30
White = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tutorial")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.center = (height / 2, width / 2)
all_sprites = pygame.sprite.Group
player = Player()
all_sprites.add(player)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
all_sprites.update()
screen.fill(black)
sprites.draw(screen)
# after every drawing flip the display
pygame.display.flip()
Im not sure what import sprites as sprites is, is it another file you made? Is it meant to be import pygame.sprite.Sprite as sprite?
all_sprites = pygame.sprite.Group
Group is a class so you need the brackets
all_sprites = pygame.sprite.Group()
now you are calling it and all_sprites is a group object, not referencing the class
now i changed sprites.draw(screen) to all_sprites.draw(screen) as not don't have sprites, and not sure what is is.

Categories