Pygame_Animation: Moving shapes and Sprites - python

[In pygame, I set the little spare shape to move from right to left and stop at a current point in scene 1 and it works. Then I try to set the sprites to move frame by frame so when the program run, it looks like the object is moving (just like animation) and it works too. But when I combine them together, something crashed and the sprites doesn't work. And I don't know where the problem is. Anyone can please tell me where I did wrong?
Here is the link for my program:]
https://drive.google.com/file/d/1IAr7PGt6bbU5g0EdVCufZtrcpFsH2tES/view?usp=sharing
import pygame, time, math
from pygame.locals import *
# Step 1: Setup animation - Initialize variables.
pygame.init()
clock = pygame.time.Clock()
surface = pygame.display.set_mode((1025, 575), RESIZABLE)
pygame.display.set_caption("Boat Moving")
#FontSetting
FstSceneFont = pygame.font.SysFont("Courier New", 80)
#ColorSetting
black = (0, 0 ,0)
teal = (15, 89, 114)
white = (255, 255, 255)
golden = (228, 155, 84)
maroon = (147, 62, 84)
orchid = (181, 218, 225)
chgX = 350
scene = 0
class Player(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.sprites = []
self.sprites.append(pygame.image.load('Attack_1.png'))
self.sprites.append(pygame.image.load('Attack_2.png'))
self.sprites.append(pygame.image.load('Attack_3.png'))
self.sprites.append(pygame.image.load('Attack_4.png'))
self.sprites.append(pygame.image.load('Attack_5.png'))
self.sprites.append(pygame.image.load('Attack_6.png'))
self.sprites.append(pygame.image.load('Attack_8.png'))
self.sprites.append(pygame.image.load('Attack_9.png'))
self.sprites.append(pygame.image.load('Attack_10.png'))
self.sprites.append(pygame.image.load('1stScene_P11.png'))
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.rect = self.image.get_rect()
self.rect.topleft = [pos_x, pos_y]
def update(self):
self.current_sprite += 1
self.image = self.sprites[self.current_sprite]
moving_sprites = pygame.sprite.Group()
player = Player(0,0)
moving_sprites.add(player)
# Step 2: Set up game loop and poll for events.
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
elif (event.type == pygame.KEYDOWN) and (event.key == pygame.K_ESCAPE):
break
if scene == 0:
pauseTime = 0
scene = 1
elif chgX > 10:
chgX = chgX - 1.7
pauseTime = 0.015
scene == 2
print("S1")
elif scene == 2:
BGColor = maroon
print("S2")
# Step 3: Update game and objects
if scene == 1:
BGColor = orchid
shipment1a = (chgX+718.75, 325, 28.125, 21.875)
Scene1Word1 = FstSceneFont.render("Scene1", 1, white)
scence = 2
elif scene == 2:
BGColor = orchid
Scene1Word2 = FstSceneFont.render("Scene2", 2, white)
# Step 4: Draw on each surface
if scene == 1:
surface.fill(BGColor)
pygame.draw.rect(surface, golden, shipment1a, 0)
surface.blit(Scene1Word1, ([212.5, 137.5]))
elif scene == 2:
surface.fill(BGColor)
surface.blit(Scene1Word2, ([212.5, 137.5]))
# Step 5: Show/display surface
pygame.display.flip()
time.sleep(pauseTime)
moving_sprites.draw(surface)
moving_sprites.update()
pygame.display.flip()
clock.tick(60)
pygame.display.quit()
quit()

You need to reset self.current_sprite when it exceeds the number of items in the list:
class Player(pygame.sprite.Sprite):
# [...]
def update(self):
self.current_sprite += 1
if self.current_sprite >= len(self.sprites):
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
Alter natively you can use the % (modulo) operator. The % operator computes a remainder of an integral division:
class Player(pygame.sprite.Sprite):
# [...]
def update(self):
self.current_sprite = (self.current_sprite + 1) % len(self.sprites)
self.image = self.sprites[self.current_sprite]

Related

I am trying to make a platform around the bottom of the screen but it keeps giving me an error

I have a problem when I made my code and This is the error it shows
platforms_list.append[pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White)]
TypeError: 'builtin_function_or_method' object is not subscriptable
I don't get what it means by subscriptable. I have a circle player that can jump move and can go around but falls off his platform because there is no bottom platform and I don't no how to make it
import math
import os
import sys
# It is importing everything
import pygame
from pygame.locals import *
class Platform:
def __init__(self, size, x, y, color):
#size is a list, this means it has width and height
self.size = size
self.x = x
self.y = y
self.color = color
# This is what the platform class has and what it does
def draw(self):
display = pygame.display.get_surface()
pygame.draw.rect(display, self.color, (int(self.x), int(self.y), self.size[0], self.size[1]))
# This is def draw function is showing that how I want my Platform to look like
def do(self):
self.draw()
# The def do function is running def draw function
class Player:
def __init__(self, velocity, maxJumpRange, x, y, size):
self.falling = True
self.jumpCounter = 0
self.xVelocity = 0
self.y = y
self.x = x
self.jumping = False
self.velocity = velocity
self.maxJumpRange = maxJumpRange
self.jump_offset = 0
self.size = size
self.TouchedGround = False
# The player class is making how the Player is going to look and what are his limits
def keys(self):
k = pygame.key.get_pressed()
# The def keys(self): is creating a variable for pygame.key.get_pressed() and underneath is a function to make the player move around
if k[K_LEFT]:
self.xVelocity = -self.velocity
elif k[K_RIGHT]:
self.xVelocity = self.velocity
else:
self.xVelocity = 0
if (k[K_SPACE] or k[K_UP]) and not self.jumping and self.TouchedGround:
self.jumping = True
self.jumpCounter = 0
self.TouchedGround = False
# The if k[K_Space] or k[K_UP] is making sure the player has a jump limit and can't continue jumping forever.
def move(self):
self.x += self.xVelocity
# if the player is jumping, change y value
if self.jumping:
self.y -= self.velocity
self.jumpCounter += 1
if self.jumpCounter == self.maxJumpRange:
self.jumping = False
self.falling = True
elif self.falling:
self.y += self.velocity
self.jumpCounter -= 1
def draw(self):
display = pygame.display.get_surface()
pygame.draw.circle(display, White, (int(self.x), int(self.y)), self.size)
def do(self):
self.keys()
self.move()
self.draw()
# This Function is doing all of the Functions self.keys(), self.move(), self.draw()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
#window size
w = 576
h = 516
# The above is showing the width the height and Area
os.environ['SDL_VIDEO_WINDOW_POS'] = "50,50"
# the above is showing what the graphics are
#player
p = Player(1, 100, 290, 250, 30)
#start pygame
pygame.init()
Clock = pygame.time.Clock()
DS = pygame.display.set_mode((w, h)) # This is what the display size is
pygame.display.set_caption("Try to get point B")
#variables
FPS = 120
Black = (0, 0, 0, 255)
White = (255, 255, 255, 255)
Red = (255, 0, 0)
# Bkgd stands for background
bkgd = pygame.Surface((w,h)) # didnt have the image so i made it blue
bkgd.fill((0,0,255))
#platforms
pl = Platform([290,20], 250, 350, White)
#this is a list that holds all the platforms
platforms_list = [pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White)]
platforms_list.append[pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White)]
#this is how much to scroll the background by
background_scroll = 0
# What the while true loop is doing is to make sure that the background moves while the player moves
while True:
events()
#blit the background, since the image is same size as window blit twice so when scrolls, you dont have blackness
DS.blit(bkgd, (-background_scroll, 0))
DS.blit(bkgd, (w-background_scroll, 0))
#check for x button clicked
events()
#update the player
p.do()
#update platforms and check for collision with player
platform_color = Red
for platform in platforms_list:
platform.color = platform_color
if p.jumping == 0:
platform.color = White
platform.do()
#if bottom of player is in the platform, move the player on top of the platform
if p.y + p.size > platform.y and p.y + p.size < platform.y + platform.size[1]:
if p.x > platform.x and p.x < platform.x + platform.size[0]:
p.y = platform.y - p.size
p.TouchedGround = True
#if the player reaches the side of the screen, move the background and platforms to make it look like it is moving
if p.x + p.size >= w:
p.x = w - p.size
background_scroll += 1
for platform in platforms_list:
platform.x -= 1
if background_scroll == w:
background_scroll = 0
#same but for the left
if p.x - p.size <= 0:
p.x = 0 + p.size
background_scroll -= 1
for platform in platforms_list:
platform.x += 1
if background_scroll == 0:
background_scroll = w
#update screen
pygame.display.update()
Clock.tick(FPS)
DS.fill(Black)
platforms_list.append[pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White)] this is the code that I added but it keeps giving me the code
I think append needs to be .append() not [].
Try this:
platforms_list.append(pl,Platform([200,20], 100, 450, White), Platform([200,20], 400, 250, White))

Cannot move player right on pygame

I am trying to write a Space Invaders game in pygame, but I cannot get the player to move right. Moving left works fine however.
My code for the Sprite and Player classes are:
class Sprite(pygame.sprite.Sprite):
def __init__(self, x, y, image = None):
pygame.sprite.Sprite.__init__(self)
if image is None:
self.image = pygame.Surface((25, 25))
self.image.fill((0, 255, 0))
else:
self.image = image
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
self.speed = 0.5
def moveLeft(self):
self.rect.x -= self.speed
def moveRight(self):
self.rect.x += self.speed
def draw(self):
screen.blit(self.image, (self.rect.x, self.rect.y))
class Player(Sprite):
def __init__(self, startpos):
try:
image = pygame.image.load(PLAYER_SPRITE_LOCATION)
except: image = None
Sprite.__init__(self, startpos[0], startpos[1], image)
print("Player class initialized at %a with sprite %s" % (self.rect, self.image))
self.score = 0
And the rest of the code is:
RESOLUTION = (224, 256)
PLAYERPOS = [112, 220]
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
player = Player(PLAYERPOS)
end = False
fps = 60
clock = pygame.time.Clock()
printString = ""
PRINTFPS, time = pygame.USEREVENT+1, 1000
pygame.time.set_timer(PRINTFPS, time)
curr_fps = 0
invaders = pygame.sprite.Group()
bullets = pygame.sprite.Group()
fullscreen = False
while not end:
for event in pygame.event.get():
if event.type == pygame.QUIT:
end = True
if event.type == PRINTFPS:
curr_fps = clock.get_fps()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT] or pressed[pygame.K_a]:
player.moveLeft()
if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:
player.moveRight()
if pressed[pygame.K_SPACE] or pressed[pygame.K_s] or pressed[pygame.K_UP]:
player.score += 1
if pressed[pygame.K_F11]:
if not fullscreen:
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
fullscreen = True
else:
screen = pygame.display.set_mode(RESOLUTION)
fullscreen = False
# Print game data
prevPrintString = printString
printString = "\rPlayer: (%s, %s)" % (str("%.3f" % player.rect.x).zfill(7),
str("%.3f" % player.rect.y).zfill(7))
printString += "; Score: %i" % player.score
printString += "; FPS: %s" % (str("%.2f" % curr_fps).zfill(5))
if printString != prevPrintString:
print(printString, end = "")
# Background (not really needed)
screen.fill((0, 0, 255)) # Blue screen!
# Update sprites, e.g. invaders moving and bullets flying
invaders.update()
bullets.update()
# Drawing sprites
invaders.draw(screen)
bullets.draw(screen)
player.draw()
# Update screen and maintain constant FPS
clock.tick(fps)
pygame.display.flip()
The problem is not that the input isn't working: I can tell that it does. I think the problem is with the moveRight function itself, and that somehow it maybe doesn't work with addition? But I don't know.
Thank you in advanced!
All of the fields stored in a pygame Rect are integers, but you are adding or substracting a fraction (0.5). My best guess is that when you subtract 0.5 from the x coordinate, it goes from (say) 112 to 111.5 and gets truncated to 111, so you move left one pixel. But if you add 0.5, it goes from 112 to 112.5 and gets truncated back to 112, so you don't move at all. I would suggest using whole numbers only.

Pygame sprite group using random.rand

I am working with a sprite group which contains 60 sprite objects.
each object represents a asteroid image and all images displayed after each other in the right order creates an animation of a rotating asteroid, in other words i am iterating through the sprite group as seen in code below.
Evcerything works fine until the objects passes the screen height and resets at the top again and the objects then starts appearing at random locations in the x direction. The screen now seem to blit each sprite at random locations and the asteroid now just flickers back and forth horizontally.
Is there a way to get the same new random x location for all the sprites after asteroid obj passes the screen instead of giving each sprite in the group a new x value?
Any suggestions?
import pygame
import sys
import os
import random
import time
import math
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 40, 60)
green = (50, 180, 50)
blue = (50, 30, 200)
skyblue = (135, 206, 250)
silver = (192, 192, 192)
darkgray = (47, 79, 79)
vegasgold = (197, 179, 88)
nightblue = (25, 25, 112)
steelblue = (70, 130, 180)
deepblue = (0, 26, 51)
screen_width = 1920
screen_height = 1080
half_width = screen_width/2
half_height = screen_height/2
screen = pygame.display.set_mode([screen_width, screen_height])
Title = pygame.display.set_caption('Space Mash')
clock = pygame.time.Clock()
class Spaceship(pygame.sprite.Sprite):
def __init__(self, width=30, height=30, color=white):
super(Spaceship, self).__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
def center_set_position(self, x, y):
self.rect.x = x - self.rect.center[0]
self.rect.y = y - self.rect.width
def rotate_ship(self, dg):
self.image = pygame.transform.rotate(self.image, dg)
def set_image(self, filename):
self.image = pygame.image.load(filename)
self.rect = self.image.get_rect()
def draw_ship(self):
screen.blit(self.image, [self.rect.x, self.rect.y])
player_spaceship = Spaceship()
player_spaceship.set_image("main_ship.png")
player_spaceship.center_set_position(half_width, screen_height)
all_sprites_list = pygame.sprite.Group()
all_sprites_list.add(player_spaceship)
class Asteroids(pygame.sprite.Sprite):
def __init__(self, nr):
super(Asteroids, self).__init__()
self.image = pygame.image.load('Asteroid_{0}.png'.format(nr))
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
def update(self):
self.rect.y += 5
if self.rect.y > screen_height + 50:
self.rect.y = -50
self.rect.x = random.randrange(0, (screen_width - (self.rect.width))
asteroids_list = pygame.sprite.LayeredUpdates()
for i in range(1, 61):
asteroid = Asteroids(nr=i)
asteroids_list.add(asteroid)
all_sprites_list.add(asteroid)
class Stars(pygame.sprite.Sprite):
def __init__(self):
super(Stars, self).__init__()
self.image = pygame.Surface([1, 1])
self.image.fill(white)
self.rect = self.image.get_rect()
stars_group = pygame.sprite.Group()
def making_star_objects():
for i in range(100):
x_loc = random.randint(0, screen_width - 1)
y_loc = random.randint(0, screen_height - 1)
star = Stars()
star.rect.x = x_loc
star.rect.y = y_loc
stars_group.add(star)
def gameloop():
ending = False
x_change = 0
y_change = 0
making_star_objects()
frame = 0
while not ending:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_change = 10
elif event.key == pygame.K_LEFT:
x_change = -10
elif event.key == pygame.K_UP:
y_change = -8
elif event.key == pygame.K_DOWN:
y_change = 8
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_LEFT:
x_change = 0
player_spaceship.rect.x += x_change
player_spaceship.rect.y += y_change
if frame > 59:
frame = 0
asteroids_list.update()
asteroids_hit_list = pygame.sprite.spritecollide(player_spaceship, asteroids_list, False)
screen.fill(deepblue)
stars_group.draw(screen)
screen.blit(asteroids_list.get_sprite(frame).image, (asteroids_list.get_sprite(frame).rect.x,
asteroids_list.get_sprite(frame).rect.y))
frame += 1
player_spaceship.draw_ship()
pygame.display.update()
clock.tick(30)
pygame.quit()
quit()
gameloop()
You can add a Class variable property and store the first coordinate X assigned, then reuse the value when you need it. It will be accessible from all the objects, since is a class global variable.
If you assign the value to the variable by this way, it will be the same (if you don't change it) during all the execution of the program, because it's value is assigned when the class is created.
rectXCopy = random.randrange(0, (screen_width - (self.rect.width))
Finaly, your class will become like this:
class Asteroids(pygame.sprite.Sprite):
rectXCopy = random.randrange(0, (screen_width - (self.rect.width))
def __init__(self, nr):
super(Asteroids, self).__init__()
self.image = pygame.image.load('Asteroid_{0}.png'.format(nr))
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.rectYCopy = 0
self.copied = False
def update(self):
self.rect.y += 5
if self.rect.y > screen_height + 50:
self.rect.y = -50
self.rect.x = self.rectXcopy
The problem is that you have all the animation frames as separate sprite objects in your asteroids_list sprite group. They all have their own rects and if you update one of them, the others aren't affected. So when the sprites leave the screen you set them all to different random positions.
I recommend to create only one asteroid object, put the images into a list or dict (whatever you prefer) and then just change the image of this single asteroid sprite in its update method to create the animation.
# Put the images / pygame.Surfaces into a global constant list.
ASTEROID_FRAMES = [surface1, surface2] # etc. (use a list comprehension)
class Asteroids(pygame.sprite.Sprite):
def __init__(self, nr):
super(Asteroids, self).__init__()
self.image = ASTEROID_FRAMES[0]
self.rect = self.image.get_rect(topleft=(0, 0))
self.frame = 0
def update(self):
self.rect.y += 5
if self.rect.y > screen_height + 50:
self.rect.y = -50
self.rect.x = random.randrange(0, (screen_width - (self.rect.width)))
# Update the image (this is frame rate bound, but you can also
# add a timer to change the frame after some time has passed).
self.frame += 1
# Keep the index in the correct range.
self.frame %= len(ASTEROID_FRAMES)
self.image = ASTEROID_FRAMES[self.frame]

pygame - blitting a moving background image causes extreme fps drop?

I'm making a Flappy Bird clone in PyGame and I'm trying to add a moving background image. I'm using a 800x600 image right now, and for some reason, when I blit the image, the performance suffers terribly. Is there something I'm doing wrong that is taking up a lot of resources?
import pygame, sys
import random
from pygame import *
pygame.init()
red = (255, 0, 0)
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("flap it up")
clock = pygame.time.Clock()
MAX_VEL = 5
GAP = 175
WALLSPEED = -2
WALLEVENT = pygame.USEREVENT+1
SCOREEVENT = pygame.USEREVENT+2
pygame.time.set_timer(WALLEVENT, 5000)
pygame.time.set_timer(SCOREEVENT, 2500)
myfont = pygame.font.SysFont("monospace", 18)
class Player(object):
def __init__(self):
self.rect = pygame.Rect(384, 284, 32, 32)
self.xvel = 0
self.yvel = MAX_VEL
self.xcel = 0
self.ycel = 1
def move(self):
self.rect.top += self.yvel
if self.yvel < MAX_VEL:
self.yvel += self.ycel
else:
self.yvel = MAX_VEL
def jump(self):
self.yvel = -15
def draw(self):
pygame.draw.rect(screen, red, self.rect)
class Wall(object):
def __init__(self, y):
self.rect1 = pygame.Rect(800, y, 32, 600-y)
self.rect2 = pygame.Rect(800, 0, 32, y-GAP)
self.xvel = WALLSPEED
def move(self, walls):
self.rect1.x += self.xvel
self.rect2.x += self.xvel
if self.rect1.x < -31:
walls.remove(self)
def draw(self):
pygame.draw.rect(screen, green, self.rect1)
pygame.draw.rect(screen, green, self.rect2)
class BG(object):
def __init__(self, x):
self.x = x
self.xvel = WALLSPEED
self.img = pygame.image.load("bg.jpg")
def move(self, bg):
self.x += self.xvel
if self.x < -799:
bg.remove(self)
bg.append(BG(self.x+1600))
screen.blit(self.img, (self.x, 0))
def lose():
pygame.quit()
quit()
def main(player, walls, bg, score, playing):
while playing:
for event in pygame.event.get():
if event.type == KEYDOWN:
player.jump()
if event.type == WALLEVENT:
numbo = random.randrange(GAP, 600, 25)
walls.append(Wall(numbo))
if event.type == SCOREEVENT:
score += 1
for b in bg:
b.move(bg)
label = myfont.render("Score: " + str(score), 1, (0, 0, 0))
screen.blit(label, (30, 20))
player.move()
player.draw()
for w in walls:
w.move(walls)
w.draw()
if player.rect.colliderect(w.rect1) or player.rect.colliderect(w.rect2):
lose()
playing = False
clock.tick(60)
pygame.display.update()
player = Player()
walls = []
bg = []
score = 0
walls.append(Wall(300))
bg.append(BG(0))
bg.append(BG(800))
playing = True
main(player, walls, bg, score, playing)
Typically, this should not be a problem. You should try to set the FPS manually and see if there is a difference
# Create a clock
clock = pygame.time.Clock()
# Set FPS (frames per second)
clock.tick(50)

Collision in the Class

I am writing a code for a game (school project).
I have a Class with different images for objects.
What I want is to create a condition for collision. For example, if the image if fire collides the image of earth then get a new image.
How can I do it ?
Thank you!
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((900,800))
pygame.display.set_caption("Tiny Alchemist")
clock = pygame.time.Clock()
FPS = 90
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
ALTWHITE = (240, 240, 240)
clear = False # Flag that shows if the user wants to clear the screen
class Element(pygame.Surface):
def __init__(self, image, xpos, ypos):
self.image = image
self.xpos = xpos
self.ypos = ypos
self.width = image.get_width()
self.height = image.get_height()
self.selected = False
self.visible = False
self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())
def move(self, move):
self.xpos += move[0]
self.ypos += move[1]
self.rect = pygame.Rect(self.xpos, self.ypos, self.width, self.height)
class Recycle(pygame.Surface):
def __init__(self, xpos, ypos):
self.image = pygame.image.load("ElementIcon/recycle.png").convert_alpha()
self.image = pygame.transform.scale(self.image, (75, 75))
self.image.set_colorkey(BLACK)
self.xpos = xpos
self.ypos = ypos
self.rect = pygame.Rect(xpos, ypos, self.image.get_width(), self.image.get_height())
class PanelElements(pygame.Surface):
def __init__ (self, image, xpos, ypos):
self.image = image
self.xpos = xpos
self.ypos = ypos
self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())
self.clicked = False
def init():
global ImageList
global Panel
global recycle
fire = pygame.image.load("ElementIcon/fire.png").convert_alpha()
fire = pygame.transform.scale(fire, (50, 69))
fire.set_colorkey(BLACK)
fire_mini = pygame.transform.scale(fire, (40,50))
fire_mini.set_colorkey(ALTWHITE)
earth = pygame.image.load("ElementIcon/earth.png").convert_alpha()
earth = pygame.transform.scale(earth, (50, 69))
earth.set_colorkey(BLACK)
earth_mini = pygame.transform.scale(earth, (40, 50))
earth_mini.set_colorkey(ALTWHITE)
water = pygame.image.load("ElementIcon/water.png").convert_alpha()
water = pygame.transform.scale(water, (50, 69))
water.set_colorkey(BLACK)
water_mini = pygame.transform.scale(water, (40, 50))
water_mini.set_colorkey(ALTWHITE)
wind = pygame.image.load("ElementIcon/wind.png").convert_alpha()
wind = pygame.transform.scale(wind, (50, 69))
wind.set_colorkey(BLACK)
wind_mini = pygame.transform.scale(wind, (40, 50))
wind_mini.set_colorkey(ALTWHITE)
energy = pygame.image.load("ElementIcon/energy.png").convert_alpha()
energy = pygame.transform.scale(energy, (50, 69))
energy.set_colorkey(BLACK)
energy_mini = pygame.transform.scale(energy, (40, 50))
energy_mini.set_colorkey(ALTWHITE)
recycle = Recycle(650, 718)
fire_mini_obj = PanelElements(fire_mini, 750, 10)
earth_mini_obj = PanelElements(earth_mini, 750, 60)
water_mini_obj = PanelElements(water_mini, 750, 110)
wind_mini_obj = PanelElements(wind_mini, 750, 160)
fire_obj = Element(fire, 362, 460)
fire_obj.visible = True
earth_obj = Element(earth, 300, 410)
earth_obj.visible = True
water_obj = Element(water, 365, 350)
water_obj.visible = True
wind_obj = Element(wind, 420, 409)
wind_obj.visible = True
Panel = [] #adding elements to the list
Panel.append(fire_mini_obj)
Panel.append(earth_mini_obj)
Panel.append(water_mini_obj)
Panel.append(wind_mini_obj)
ImageList =[] #adding elements to the list
ImageList.append(fire_obj)
ImageList.append(earth_obj)
ImageList.append(water_obj)
ImageList.append(wind_obj)
def run():
global done
done = False
while done == False:
check_events()
update()
clock.tick(60)
def check_events():
global done
global ImageList
global Panel
global recycle
global clear
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
print("User quits the game :(")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
print("Game stopped early by user :( ")
if event.type == pygame.MOUSEBUTTONDOWN:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and (im.visible == True):
im.selected = True
if recycle.rect.collidepoint(mouse_pos):
clear = True
for mini in Panel:
if mini.rect.collidepoint(mouse_pos):
mini.clicked = True
if event.type == pygame.MOUSEBUTTONUP:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and im.visible == True:
im.selected = False
if event.type == pygame.MOUSEMOTION:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and im.selected and (im.visible == True):
xmv = event.rel[0]
ymv = event.rel[1]
if event.buttons[0]:
if xmv < 0:
if im.xpos > 0:
im.move((xmv,0))
elif event.rel[0] > 0:
if im.xpos < screen.get_width():
im.move((xmv,0))
elif ymv < 0:
if im.ypos > 0:
im.move((0,ymv))
elif event.rel[1] > 0:
if im.ypos < screen.get_height():
im.move((0,ymv))
#pygame.display.update()
def update():
global ImageList
global Panel
global recycle
global clear
screen.fill(WHITE)
#Update the screen with drawings
for im in ImageList:
if im.visible == True:
screen.blit(im.image, (im.xpos, im.ypos))
pygame.draw.rect(screen, ALTWHITE, (740, 0, 160, 800), 0)
for mini in Panel:
screen.blit(mini.image, (mini.xpos, mini.ypos))
screen.blit(recycle.image, (recycle.xpos, recycle.ypos))
if (clear == True):
for im in ImageList:
im.visible = False
clear = False
for i in range(0,len(Panel)):
if Panel[i].clicked == True:
Panel[i].clicked = False
pygame.display.update()
if __name__=="__main__":
init()
run()
pygame.quit()
perhaps something like this:
earth = pygame.image.load("earth.png").convert()
earthRect = earth.get_rect()
fire = pygame.image.load("fire.png").convert()
fireRect = fire.get_rect()
if earth.colliderect(fire):
earth = pygame.image.load("thirdimage.png")
with the first four lines defining our images and the rect objects used to detect collision, the last two line detecting the collision and changing the image file

Categories