I'm working on a game for class and this is what we've learned to do so far. I'm trying to get the sprites to stay onscreen with clamp_ip, but it keeps giving me an error message that "Butterfly instance has no attribute clamp_ip." Is there a different way I should be keeping the butterflies onscreen?
This first bit is just setting up pygame and the butterfly class (where I included a line to define a rectangle for the butterflies), I've highlighted where I'm guessing the potential errors are below.
This should be ok.
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
playground = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Butterflies')
screenRect = playground.get_rect()
steps = 1
class Butterfly:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH)
self.y = random.randint(0, SCREEN_HEIGHT)
self.image_Butterfly = pygame.image.load('butterflya.png')
self.image_ButterflyB = pygame.image.load('butterflyb.png')
self.height = self.image_Butterfly.get_height()
self.width = self.image_Butterfly.get_width()
self.rect = (self.width, self.height)
clock = pygame.time.Clock()
fps = 10
net = []
for i in range (15):
butterflyInstance = Butterfly()
net.append(butterflyInstance)
playground.fill(cyan)
Game_Over = False
while not Game_Over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Game_Over = True
This is where I'm guessing I messed up. I tried to use the clamp_ip function at the end of this loop
for butterflyInstance in net:
butterflyInstance.x += random.randint(-10, 10)
butterflyInstance.y += random.randint(-10,10)
if steps % 2 == 0:
playground.blit(butterflyInstance.image_Butterfly, (butterflyInstance.x, butterflyInstance.y))
steps += 1
else:
playground.blit(butterflyInstance.image_ButterflyB, (butterflyInstance.x, butterflyInstance.y))
steps +=1
butterflyInstance.clamp_ip(screenRect)
Thank you so much!
See PyGame doc pygame.Rect()
clamp_ip is pygame.Rect method so you have to use butterflyInstance.rect.clamp_ip()
But you have to use self.rect.x, self.rect.y, self.rect.width, self.rect.height instead of self.x, self.y, self.width, self.height to keep position and size of object.
And use butterflyInstance.rect.x, butterflyInstance.rect.y, butterflyInstance.rect.width, butterflyInstance.rect.height
instead of butterflyInstance.x, butterflyInstance.y, butterflyInstance.width, butterflyInstance.height
PyGame use pygame.Rect in many places - it is usefull. For example: you can use rect.right instead of rect.x + rect.width, or rect.center = screenRect.center to center object on screen.
Related
Im making a custom tile system for my game. Its my first time and didnt expect to go that far without a tutorial. So i did my best and made something that works when i render in a tile with the blit method but when i use pygame.sprite.Sprite sprites it doesnt work. I need it to be with pygame's sprite system because it makes it easier doing other stuff and im positive its a rookie mistake i just cant find it.
Code:
# Importing libraries
try:
import pygame
from pygame.locals import *
from time import *
from os import *
from random import *
import sys
print("All Libraries imported successfully \n")
except :
print("Error while importing modules and libraries")
sys.exit()
# Creating Screen
screen_width = 640
screen_height = 640
tile_size = int(screen_width / 10)
screen_res = (screen_width, screen_height)
clock = pygame.time.Clock()
running_fps = 144
screen = pygame.display.set_mode(screen_res)
pygame.display.set_caption(f"GTA Circuit Hack FPS:{running_fps}, {screen_width} x {screen_height}, Tile Size: {tile_size}")
# Loading images
# Background image:
backgroundImg = pygame.image.load("Background.png")
backgroundImg = pygame.transform.scale(backgroundImg, screen_res)
# Not walkable tile image:
noWalkTileImg = pygame.image.load("unwalkTile.png")
noWalkTileImg = pygame.transform.scale(noWalkTileImg, (tile_size, tile_size))
# making tiles
tiles = []
tile_y = 0
tile_x = 0
for i in range(10):
if i > 0:
tile_y += tile_size
for i in range(10):
if i > 0:
tile_x += tile_size
tiles.append((tile_x, tile_y))
tile_x = 0
tile_x = 0
tile_y = 0
# creating object classes
class BadTile (pygame.sprite.Sprite):
def __init__(self, tile):
pygame.sprite.Sprite.__init__(self)
self.image = noWalkTileImg
self.tile = tile
self.rect = self.image.get_rect()
self.x = self.tile[0]
self.y = self.tile[1]
def update(self):
self.x = self.tile[0]
self.y = self.tile[1]
# creating objects
tile1 = BadTile(tiles[99])
game_tiles = pygame.sprite.Group()
game_tiles.add(tile1)
run = True
while run:
clock.tick(running_fps)
screen.blit(backgroundImg, (0,0))
# rendering
game_tiles.update()
game_tiles.draw(screen)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
print ("Exited with no errors")
sys.exit()
Images:
pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The latter delegates to the update method 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 former 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. [...]
So you need to set self.rect.x and self.rect.y. Instead of self.x and self.y. You don't need self.x and self.y at all:
class BadTile (pygame.sprite.Sprite):
def __init__(self, tile):
pygame.sprite.Sprite.__init__(self)
self.image = noWalkTileImg
self.tile = tile
self.rect = self.image.get_rect()
self.rect.x = self.tile[0]
self.rect.y = self.tile[1]
def update(self):
self.rect.x = self.tile[0]
self.rect.y = self.tile[1]
I'm trying to use pygame to make a few balls (circles). The code runs but the circles do not show up. I'm wondering if there is an error somewhere in the ball class or it's in the game function class.
This is the code for the balls class:
import pygame
from pygame.sprite import Sprite
import random
class Ball(Sprite):
def __init__(self, bg_settings, screen, user):
super(Ball,self).__init__()
self.screen = screen
self.bg_settings = bg_settings
self.image = pygame.Surface((bg_settings.ball_radius*2,bg_settings.ball_radius*2))
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.velocityx = random.randint(-1 * bg_settings.ball_speed, bg_settings.ball_speed)
self.velocityy= random.randint(-1 * bg_settings.ball_speed, bg_settings.ball_speed)
self.rect.centerx = random.randint(0,bg_settings.screen_width)
self.rect.centery = random.randint(0,bg_settings.screen_height)
while (self.rect.centerx in range(user.rect.left - 30, user.rect.right + 30) and
self.rect.centery in range(0, user.rect.top + 30)):
self.rect.centerx = random.randint(0,bg_settings.screen_width)
self.rect.centery = random.randint(0,bg_settings.screen_height)
self.speed = bg_settings.ball_speed
self.color = bg_settings.ball_color
self.radius = bg_settings.ball_radius
def draw_ball(self):
pygame.draw.circle(self.image, self.color, (self.rect.centerx,self.rect.centery), self.radius)
def update_ball(self):
if not (self.rect.right < self.screen_rect.right or self.rect.left == self.screen_rect.left):
self.rect.centerx += self.velocityx
if not (self.rect.top == self.screen_rect.top or self.rect.bottom == self.screen_rect.bottom):
self.rect.centery += self.velocityy
Here is relevant code for games functions class (I think just the update screen and creating the balls parts ??):
def update_screen(ai_settings, screen, user, balls, gem):
screen.fill(ai_settings.bg_color)
user.blitme()
for ball in balls.sprites():
ball.draw_ball()
gem.blitme()
pygame.display.flip()
def set_balls(balls, bg_settings, screen, user):
for ball_number in range(bg_settings.num_balls):
new_ball = Ball(bg_settings, screen, user)
balls.add(new_ball)
def update_balls(balls, bg_settings):
balls.update()
for ball in balls.copy():
if ball.rect.left == 0 or ball.rect.right == bg_settings.screen_width:
ball.velocityx = ball.velocityx * -1
elif ball.rect.top == 0 or ball.rect.bottom == bg_settings.screen_height:
ball.velocityy = ball.velocityy * -1
Main loop:
while True:
gf.check_events(user)
gf.update_user(user)
gf.update_screen(bg_settings, screen, user, balls, gem)
gf.update_balls(balls, bg_settings)
Any help is appreciated!
You must use pygame.display.update() at the end of your main event loop to update your screen. After doing this, the window would be updated to reflect the latest state and the circles would appear.
If performance is not an issue, you may want to use pygame.display.flip() instead of pygame.display.update() as I heard that it sometimes has problems with edited zone borders.
The main difference between these two functions is that pygame.display.flip() changes the whole screen while pygame.display.update() only changes parts that it detects changed, so that's why it may have problems
I would like individual cars to drive across the screen from left to right with a certain time interval.It should be an endless loop. It is ended by program end
With my code, they all start at the same time. In addition, rect.y changes from the default value 300 to 0.
import pygame
import random
WIDTH = 800
HEIGHT = 600
FPS = 30
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
class Car(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
for i in range(5):
img = pygame.image.load(f"Bilder/Gegenstaende/quer_auto_{i}.png")
self.images.append(img)
self.image = self.images[random.randrange(0, 5)]
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 300
self.last = pygame.time.get_ticks()
self.delay = 5000
def update(self):
self.rect.x += 5
current = pygame.time.get_ticks()
if current - self.last > self.delay:
self.last = current
self.image = self.images[random.randrange(0, 5)]
self.rect = self.image.get_rect()
self.rect.x = 100
background = pygame.image.load("Bilder/starfield.png")
background_rect = background.get_rect()
cars = pygame.sprite.Group()
for i in range(3):
m = Car()
cars.add(m)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
cars.update()
screen.fill((250,250,250))
screen.blit(background,background_rect)
cars.draw(screen)
pygame.display.flip()
pygame.quit()
(Assuming you want these cars to be robots) First create variable and lets name them car_move_right and car_move_left . If you want the car to move towards the right at the beginning of the game, set the car_move_right to True and the other variable to False, and vice versa. Then in the main loop, add an if statement like this:
(Taking carX to be X-coordinate of car)
if car_move_right:
carX += ai_move_speed
if carX == WINDOWWIDTH or carX > WINDOWWIDTH:
car_move_right = False
car_move_left = True
if car_move_left:
carX -= ai_move_speed
if carX == 0 or carX < 0:
car_move_left = False
car_move_right = True
Please note: I had written this code for robot movement which also included going up and down. Not the cleanest and best, but I think it would work for you.
rect.y changes to 0 because you reset the rect, and default rect's x and y values are 0.
if current - self.last > self.delay:
self.last = current
self.image = self.images[random.randrange(0, 5)]
self.rect = self.image.get_rect() ##<--- here
self.rect.x = 100
Also you should consider storing your car's position in a python variable, since self.rect.x can only store integers.
For the timer thing, you should move your update function outside of your car class since it does not have any information about other cars and it needs it.
Here is an example implementation.
import pygame
WIDTH = 800
HEIGHT = 600
FPS = 30
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
class Car(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50)).convert()
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 300
def finished(self):
return self.rect.x >= WIDTH - self.rect.width
class Driver:
def __init__(self, cars):
self.cars = cars
self.currentCar = 0
self.delay = 1000
self.current = pygame.time.get_ticks()
self.last = pygame.time.get_ticks()
self.timePassed = False
def updateCar(self, car):
if self.timePassed:
car.rect.x += 1 #5
def runTimer(self):
self.current = pygame.time.get_ticks()
self.timePassed = False
if self.current - self.last > self.delay:
self.timePassed = True
def Run(self):
self.runTimer()
car = self.cars.sprites()[self.currentCar]
if not car.finished():
self.updateCar(car)
else:
self.current = pygame.time.get_ticks()
self.last = pygame.time.get_ticks()
self.currentCar += 1
def allFinished(self):
return self.currentCar >= len(self.cars)
cars = pygame.sprite.Group()
for i in range(3):
m = Car()
cars.add(m)
driver = Driver(cars)
while True:
if not driver.allFinished():
driver.Run()
#btw, no need to fill if you have background image the size of window
screen.fill((250,250,250))
#screen.blit(background,background_rect)
cars.draw(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
Create 10 car classes. Give them a different name, like car1, car2, etc.
Let's focus on car1 for now. Let car1X represent the x-coordinate of car1.
Now for the speed of movement. If you want each car to have the same speed, just create a variable named ai_move_speed. Now, if you want the speed to differ, then instead of ai_move_speed, make 10 variables and name these variables as ai1_move_speed, ai2_move_speed, etc. For now, set these variables to an integer value of 2.
For the movement of left to right, create a variable called car1_move_right and set it to True.
As each car will go from left to right, then die, We can simply add this code to our main loop :
if car1_move_right:
car1X += ai_move_speed
Now once the game is run, car1 will go from its x-coordinate towards the left side. Repeat this process for the other cars.
But if you want the cars to go back to their original position if they go out of the boundary or die, then just add this line of code at the end of the above code:
if carX == 800:
carX = 100
Now so far we fixed movement. Now if you want the cars to start 1 after the other, delete the entire code from before. Now you can customize when a car starts. For car1 let's simply create a variable and call this variable c1_time. Set it to 5000 for now. Now I want to introduce you to a pygame function called pygame.time.get_ticks(). It gets the number of milliseconds since pygame.init() has been called in milliseconds. Remember the c1_time? We set it to an integer value of 5000 because 1000 milliseconds is 1 second, so car1 will start moving after 5 seconds after the interpreter reads pygame.init().
Now create this variable : time_init and store this code inside it : pygame.time.get_ticks(). After that create an if statement as so :
if car1_move_right:
if time_init >= c1_time:
car1X += ai_move_speed
if car1X == 800:
car1X = 100
Now what this above code does is that 5 seconds after the game starts, it will start moving car1. If car1 goes out of boundary it gets it back again. Repeat these steps for the other cars. This is the simplest and bug-free way I could do it.
PS - Feel free to change any variable name. Just make sure to change it everywhere in the code.
PPS - Please read the entire thing. Also upvote if you found this helpful cuz I spent a lot of time on this.
This question already has answers here:
How do I create animated sprites using Sprite Sheets in Pygame?
(1 answer)
Invalid destination position for blit error, not seeing how
(1 answer)
Closed 2 years ago.
Alright, so I got some extremely simple code going on here, any comments/suggestions are recommended. Keep in mind, SIMPLE, in other words short and concise. thnx.
My problem is loading an image from a png file. So for example i got a couple of images in the file, and i want only one row to be loaded when the user presses for example, the right arrow key. Basically i have 4 rows, 2 or 3 columns 4 rows for each arrow key respectively
#
import pygame, time, random
pygame.init()
HEIGHT = 700
WIDTH = 1350
GRIDSIZE = HEIGHT/28
BLACK = ( 0, 0, 0)
WHITE = (255,255,255)
RED = (255, 0, 0)
screen=pygame.display.set_mode((WIDTH,HEIGHT))
font = pygame.font.SysFont("arial", 36)
shift = 10
#---------------------------------------#
# classes #
#---------------------------------------#
class Sprite(pygame.sprite.Sprite):
""" (fileName)
Visible game object.
Inherits Sprite to use its Rect property.
"""
def __init__(self, picture=None):
pygame.sprite.Sprite.__init__(self)
self.x = 0
self.y = 0
self.visible = False
self.image = self.blend_image(picture)
self.rect = self.image.get_rect()
self.width, self.height = self.rect.width, self.rect.height
self.update()
def spawn(self, x, y):
""" Assign coordinates to the object and make it visible.
"""
self.x, self.y = x,y
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
self.visible = True
def draw(self, surface):
surface.blit(self.image, self.rect)
def update(self):
# after moving a sprite, the rect attribute must be updated
self.rect = self.image.get_rect()
self.rect = pygame.Rect(self.x,self.y,self.rect.width,self.rect.height)
def moveLeft(self):
self.x -= shift
self.update()
def moveRight(self):
self.x += shift
self.update()
def moveUp(self):
self.y -= shift
self.update()
def moveDown(self):
self.y += shift
self.update()
def blend_image(self, file_name):
""" Remove background colour of an image.
Need to use it when a picture is stored in BMP or JPG format, with opaque background.
"""
image_surface = pygame.image.load(file_name)
image_surface = image_surface.convert()
colorkey = image_surface.get_at((0,0))
image_surface.set_colorkey(colorkey)
return image_surface
#---------------------------------------#
# functions #
#---------------------------------------#
def redraw_screen():
screen.fill(BLACK)
world.draw(screen)
if player.visible:
player.draw(screen)
pygame.display.update()
#---------------------------------------#
# main program #
#---------------------------------------#
world = Sprite("town.png")
world.spawn(0,0)
player = Sprite("player.png")
player.spawn(100,400)
LEFT_BORDER = 0
RIGHT_BORDER = WIDTH-1100
TOP_BORDER = 0
BOTTOM_BORDER = HEIGHT-480
#---------------------------------------#
clock = pygame.time.Clock()
FPS = 10
inPlay = True
while inPlay:
clock.tick(FPS)
# keyboard handler
pygame.event.get()
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
inPlay = False
# world moves opposite to the arrow
if keys[pygame.K_LEFT] and world.x < LEFT_BORDER:
world.moveRight()
if keys[pygame.K_RIGHT] and world.x > RIGHT_BORDER:
world.moveLeft()
if keys[pygame.K_UP] and world.y < TOP_BORDER:
world.moveDown()
if keys[pygame.K_DOWN] and world.y > -BOTTOM_BORDER:
world.moveUp()
redraw_screen()
#---------------------------------------#
pygame.quit()
Right, so this is using python 2.7 btw. Any help is appreciated thnx again.
And also, there are some things that are added that have no use, but thats for later code, and vice-versa. Some tweaks i could do, like naming, that will come later.
If the player presses right, i have an image of a guy facing right.
Left, up, and down same concept.
if he holds the button, the guy "runs"
Now i hav normal position, and running position.
4 rows, 2 columns in a png file, how to load 1 row for respective key?
I've been banging my head against this for a while. I am trying to make a game with PyGame and I got up to the collision segment and have been stuck for a while and have checked a few threads.
This is the code I have (removed other methods and conditional statements in between, but left the relevant parts). I am a little confused by the error because I do a self.imageRect = self.image.get_rect() in both classes init, yet I have this error. The error was specifically:
"AttributeError: 'Pebble' object has no attribute 'rect'" when the program attempts to carry out the collision detection part in the dog class. What have I been doing wrong?
import random
import pygame, sys
pygame.init()
clock = pygame.time.Clock() # fps clock
screenSize = WIDTH, HEIGHT = [800, 600]
screen = pygame.display.set_mode(screenSize)
background = pygame.Surface(screen.get_size())
bgColorRGB = [153, 204, 255]
background.fill(bgColorRGB)
pebbleGroup = pygame.sprite.Group()
pebbleSingle = pygame.sprite.GroupSingle()
dogSingle = pygame.sprite.GroupSingle()
#----------------------------------------------------------------------
class Dog(pygame.sprite.Sprite):
def __init__(self, path, speed):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(path) # load sprite from path/file loc.
self.imageRect = self.image.get_rect() # get bounds of image
self.imageWidth = self.image.get_width()
self.imageHeight = self.image.get_height()
self.speed = speed
# sets location of the image, gets the start location of object
# sets the start location as the image's left and top location
def setLocation(self, location):
self.imageRect.left, self.imageRect.top = location
def checkCollision(self, pebble, dogGroup):
if pygame.sprite.spritecollide(pebble, dogGroup, False):
print "collided"
#---------------------------------------------------------------------
class Pebble(pygame.sprite.Sprite):
def __init__(self, path, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(path)
self.imageRect = self.image.get_rect()
self.imageWidth = self.image.get_width()
self.imageHeight = self.image.get_height()
self.imageRect.left, self.imageRect.top = location
self.speed = speed # initialize speed
self.isDragged = False
#----------------------------------------------------------------------
def startGame():
pebblePaths = ['images/pebble/pebble1.jpg', 'images/pebble/pebble2.jpg']
for i in range(3):
pebblePath = pebblePaths[random.randrange(0, len(pebblePaths))]
pebbleSpeed = [random.randrange(1, 7), 0]
pebbleLocation = [0, random.randrange(20, HEIGHT - 75)]
pebble = Pebble(pebblePath, pebbleSpeed, pebbleLocation)
pebbleGroup.add(pebble)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for pebble in pebbleGroup:
dog.checkCollision(pebble, dogSingle)
pygame.display.flip()
clock.tick(30) # wait a little before starting again
startGame()
It's expecting Sprite.rect, so change from
self.imageRect = self.image.get_rect()
#to
self.rect = self.image.get_rect()
Note
self.imageWidth = self.image.get_width()
self.imageHeight = self.image.get_height()
self.imageRect.left, self.imageRect.top = location
These are not necessary, since rect's have many properties, like self.rect.width or self.rect.topleft = location . Another useful one is centerx.
full list at: pygame Rect docs