Mute and unmute function - python

I have mute and unmute button on my main screen and the problem I'm having with is that when I press my mute button and it turns to a unmute button then when I play my game and die and I go back to the main screen, it turns it back to a mute button. I want to make it so that if I mute my game and I start it and die, it still a mute button, it does not revert to a unmute button. I have tried using a True and False statement also I have tried. https://gyazo.com/6b3d63d7615b07f2b4984d01ae239db5
My full code
import pygame,random
pygame.init()
width = 500
height = 600
# Screen width and height
window = pygame.display.set_mode((width,height))
# Name of the Screen
pygame.display.set_caption("Game")
# For off and on music
music_on = pygame.image.load("img/music_on.png")
music_on = pygame.transform.scale(music_on,(music_on.get_width()//2, music_on.get_height()//2))
music_off = pygame.image.load("img/music_off.png")
music_off = pygame.transform.scale(music_off,(music_off.get_width()//2, music_off.get_height()//2))
# Start screen
def text_objects(font,text):
textSurface = font.render(text,True,(0,0,0))
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ac,ic,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(window,ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window,ic,(x,y,w,h))
def quitgame():
pygame.quit()
def game2():
# part of making background shift
# player class
class Player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect(x,y,width,height)
def get_rect(self):
self.rect.topleft = (self.x,self.y)
return self.rect
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Button class
class button11:
def __init__(self,color,x,y,width,height,text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.over = False
def draw(self,window, outline=None):
# Call this method to draw button on screen
if outline:
pygame.draw.rect(window,outline(self.x-2,self.y-2,self.width+4,self.height+4),0)
pygame.draw.rect(window,self.color,(self.x,self.y,self.width,self.height),0)
if self.text != '':
font = pygame.font.SysFont("comicsans",60)
text = font.render(self.text,1,(0,0,0))
window.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y+ (self.height/2 - text.get_height()/2)))
def isOver(self,pos):
# Pos is mouse position or tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
def playSoundIfMouseIsOver(self,pos,sound):
if self.isOver(pos):
if not self.over:
Hover.play()
self.over = True
else:
self.over = False
class Sweep:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 2
self.rect = pygame.Rect(x,y,width,height)
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Color
white = (255,255,255)
Black = (0,0,0)
# Calss's cords,size, and color
playerman = Player(230,150,40,40,white)
right = Sweep(-600,0,600,800,Black)
right2 = Sweep(530,0,600,800,Black)
left1 = Sweep(-550,0,800,800,Black)
left2 = Sweep(250,0,800,800,Black)
sweeps = [right,right2,left1,left2]
font = pygame.font.Font("img/Bubble.ttf",60)
text = font.render("SPACE TO START!",True,(0,0,0))
textRect = text.get_rect()
textRect.center = ((250,400))
Sbutton = button11((0,255,0),431,16,40,50, '')
# Displaying class's in main loop
def redrawwindow():
window.fill((255,0,0))
# Drawing my classes and other things
playerman.draw()
window.blit(text,textRect)
if on:
window.blit(music_on,(420,10))
if off:
window.blit(music_off,(420,10))
for Sweep in sweeps:
Sweep.draw()
sound = True
mouseisover = True
switch = 1
Stimer = 0
off = False
on = True
timer = 0
fps = 35
clock = pygame.time.Clock()
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if switch == 1 and Sbutton.isOver(pos):
switch = 2
on = False
off = True
else:
if switch == 2 and Sbutton.isOver(pos):
switch = 1
on = True
off = False
timer += 1
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and timer >= 20:
Stimer += 1
if Stimer > 0 :
Stimer += 1
right.x += 20
right2.x -= 20
if Stimer >= 32:
main_loop()
Stimer = 0
left1.x -= 20
left2.x += 20
redrawwindow()
pygame.display.update()
pygame.quit()
def main_loop():
global lose
# Making both peipes separate
Pipe_distance = 830
# part of making background shift
bg_shift = 0
# player class
# player class
class Player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 5
self.JumpCount = False
self.isJump = 10
self.fall = 0
self.rect = pygame.Rect(x,y,width,height)
def get_rect(self):
self.rect.topleft = (self.x,self.y)
return self.rect
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Pipe class
class Pipe:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 3
self.rect = pygame.Rect(x,y,width,height)
def get_rect(self):
self.rect.topleft = (self.x,self.y)
return self.rect
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Pipe2 class
class Pipe2:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 3
self.rect = pygame.Rect(x,y,width,height)
def get_rect(self):
self.rect.topleft = (self.x,self.y)
return self.rect
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
class Sweep:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 2
self.rect = pygame.Rect(x,y,width,height)
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Color
white = (255,255,255)
green = (0,255,0)
blue = (0,0,255)
Black = (0,0,0)
# Calss's cords,size, and color
playerman = Player(200,200,40,40,white)
pipe1 = Pipe(350,900,60,700,green)
pipe2 = Pipe2(350,-900,60,700,green)
pipe3 = Pipe(720,9900,60,700,white)
pipe4 = Pipe2(720,-9900,60,700,blue)
left1 = Sweep(-550,0,800,800,Black)
left2 = Sweep(250,0,800,800,Black)
# All my list
pipes = [pipe1,pipe3]
pipes2 = [pipe2,pipe4]
sweeps = [left1,left2]
# Point system
font = pygame.font.Font("img/CAT.ttf",60)
score = 0
text = font.render(""+str(score), True,(255,255,255))
textRect = text.get_rect()
textRect.center = ((250,60))
lose = False
def quitgame():
pygame.quit()
def unlose():
global lose
lose = False
def lost():
lfont = pygame.font.Font("img/CAT.ttf",60)
ltext = lfont.render("You Died",True,(255,255,255))
ltextRect = ltext.get_rect()
ltextRect.center = ((250,90))
lfont2 = pygame.font.Font("img/CAT.ttf",60)
ltext2 = lfont2.render("Score",True,(255,255,255))
ltextRect2 = ltext2.get_rect()
ltextRect2.center = ((250,510))
lfont3 = pygame.font.Font("img/CAT.ttf",50)
ltext3 = lfont3.render("Space To Return",True,(255,0,255))
ltextRect3 = ltext3.get_rect()
ltextRect3.center = ((250,270))
timer = 0
while lose:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
timer += 1
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and timer >= 20:
game2()
window.fill((0,0,0))
text = font.render(""+str(score), True,(255,255,255))
textRect.center = ((250,450))
window.blit(ltext,ltextRect)
window.blit(ltext2,ltextRect2)
window.blit(ltext3,ltextRect3)
window.blit(text,textRect)
pygame.display.update()
clock.tick(15)
# Displaying class's in main loop
def redrawwindow():
window.fill((0,0,0))
# Drawing my classes and other things
playerman.draw()
for Pipe in pipes:
Pipe.draw()
for Pipe2 in pipes2:
Pipe2.draw()
for Sweep in sweeps:
Sweep.draw()
window.blit(text,textRect)
# To make the game more difuclt
ptimer = 0
# for playing sprite when player jumps
# Making it so the rectangle dose not come for a whilw
Ptimer = 0
Ptimer2 = 0
spcdown = False
sound = True
# for making firse play once
fps = 35
clock = pygame.time.Clock()
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Making most of my classes move
for Pipe in pipes:
Pipe.x -= Pipe.speed
for Pipe2 in pipes2:
Pipe2.x -= Pipe2.speed
for Pipe2 in pipes2:
if Pipe2.x <= -200:
Pipe2.x = 550
left1.x -= 20
left2.x += 20
# Randomizing pipe
for Pipe in pipes:
if Pipe.x <= -200:
Pipe.x = 550
Pipe.y = random.randint(150,500)
pipe2.y = pipe1.y - Pipe_distance
pipe4.y = pipe3.y - Pipe_distance
# Making the game faster
ptimer += 1
if ptimer == 10000:
for Pipe in pipes:
for Pipe2 in pipes2:
Pipe.speed += 1
Pipe2.speed += 1
bg_shift += 3
for Pipe in pipes:
if playerman.rect.colliderect(Pipe.rect):
lose = True
lost()
for Pipe2 in pipes2:
if playerman.rect.colliderect(Pipe2.rect):
lose = True
lost()
keys = pygame.key.get_pressed()
if not keys[pygame.K_SPACE]:
spcdown = False # space released
if keys[pygame.K_SPACE]:
Jumping = 1
if not spcdown:
spcdown = True
collide = False
playerman.y += playerman.speed
# bird moving
if not playerman.isJump:
# [...]
# the bird is allowed to jump even if it is not colliding:
if keys[pygame.K_SPACE]:
playerman.isJump = True
if collide:
playerman.fall = 0
else:
if playerman.JumpCount > 0:
playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.3
playerman.JumpCount -= 1
else:
playerman.JumpCount = 10
# if K_SPACE is pressed, then the bird keeps jumping
if not keys[pygame.K_SPACE]:
playerman.isJump = False
redrawwindow()
pygame.display.update()
pygame.quit()
unlose()
game2()
main_loop()

The problem is probably caused by using two separate variables to control the state of the sound:
if on:
window.blit(music_on,(420,10))
if off:
window.blit(music_off,(420,10))
I suggest using only a single, descriptive, variable name:
if ( sound_muted ):
window.blit( music_on, (420,10) ) # show "un-mute" button
else:
window.blit( music_off, (420,10) ) # show "mute" button
And change that when the image is clicked:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if Sbutton.isOver(pos):
sound_muted = not sound_muted # mute or un-mute the sound.

Related

Colliderect firing even when 2 items aren't touching

I am making a system where the items fall from the sky and you collect them however the collision is being registered even when the character doesn't touch the items. The collision happens when the character collides with the item on the x axis but it can collide at any point on the y axis.
Here is an example from the image below:
Example Image
I have tried printing the positions of both the character and item to see if for some reason the position wasn't up to date with where it was on screen but for both the character and item the positions were fine.
Here is my code:
import pygame
import sys
import os
import time
from pygame.locals import *
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
SCREENWIDTH = 580
SCREENHEIGHT = 375
SCREENSIZE = [SCREENWIDTH, SCREENHEIGHT]
SCREEN = pygame.display.set_mode(SCREENSIZE)
CLOCK = pygame.time.Clock()
FPS = 60
jumping = False
backgroundImage = pygame.image.load('Images/backgroundImage.jpg')
backgroundScaled = pygame.transform.scale(backgroundImage,(580,375))
pygame.display.set_caption("Christmas Game")
santaWidth, santaHeight = 93,64
santaImage = pygame.image.load("Images/santa.png")
santaScaled = pygame.transform.scale(santaImage,(santaWidth,santaHeight))
santa = pygame.Rect(100,100,santaWidth,santaHeight)
font = pygame.font.SysFont("myriadProFont",50)
timeText = font.render("", 1,(255,255,255))
startTime = time.time()
itemsGroup = pygame.sprite.Group()
#IDs 0 = coin,
class Item(pygame.sprite.Sprite):
def __init__(self,x,y,ID,imageName):
super().__init__()
self.ID = ID
self.image = pygame.image.load(imageName)
self.scaledImage = pygame.transform.scale(self.image,(50,50))
self.x = x
self.y = y
self.rect = self.image.get_rect()
self.rect.topleft = (self.x,self.y)
def render(self, screen):
screen.blit(self.scaledImage,(self.x,self.y))
def collect(self, santa):
hit = self.rect.colliderect(santa)
if hit:
if self.ID == 0:
print("Coin")
self.kill()
def itemGravity(self):
if self.y < 370:
self.y += 1
self.rect = self.image.get_rect()
self.rect.topleft = (self.x,self.y)
else:
self.kill()
print("killed")
coin = Item(200,0,0,"Images/coin.png")
itemsGroup.add(coin)
coin2 = Item(500,0,0,"Images/coin.png")
itemsGroup.add(coin2)
class Floor(pygame.sprite.Sprite):
def __init__(self, width, height, x, y, name):
super().__init__()
self.image = pygame.image.load(name)
self.image = pygame.transform.scale(self.image, (width, height))
self.rect = self.image.get_rect()
self.size = width, height
self.pos = (x, y)
self.rect.topleft = self.pos
self.isTouching = False
def render(self, display):
display.blit(self.image, self.pos)
def collision(self,santa):
global jumping
hit = self.rect.colliderect(santa)
if hit and self.isTouching == False:
self.isTouching = True
elif not hit:
self.isTouching = False
floorGroup = pygame.sprite.Group()
floor = Floor(291,70,-50,305,"Images/floor.webp")
floorGroup.add(floor)
floor2 = Floor(291,70,330,305,"Images/floor.webp")
floorGroup.add(floor2)
def adjustTime():
global timeText
global jumping
newTime = time.time()
difference = newTime - startTime
if difference > 1:
timeText = font.render(time.strftime('%M:%S', time.gmtime(difference)), 1,(255,255,255))
def playerMovement(keyPressed,santa):
global jumping
if (keyPressed[pygame.K_UP] or keyPressed[pygame.K_w] or keyPressed[pygame.K_SPACE]) and santa.y > 0 and jumping == False:
jumping = True
santa.y = santa.y - 50
elif(keyPressed[pygame.K_LEFT] or keyPressed[pygame.K_a]) and santa.x > -20:
santa.x = santa.x - 5
elif(keyPressed[pygame.K_RIGHT] or keyPressed[pygame.K_d]) and santa.x < 525:
santa.x = santa.x + 5
def updateScreen(santa):
SCREEN.blit(backgroundScaled, (0, 0))
for floor in floorGroup:
floor.render(SCREEN)
for item in itemsGroup:
item.render(SCREEN)
SCREEN.blit(santaScaled,(santa.x,santa.y))
SCREEN.blit(timeText,(250,0))
pygame.display.update()
def gravity(santa):
global jumping
if santa.y < 320:
santa.y += 3
elif santa.y == 320:
jumping = False
else:
santa.y = 320
while True:
timeDelta = CLOCK.tick(FPS)/1000.0
adjustTime()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
user_input = pygame.key.get_pressed()
playerMovement(user_input,santa)
gravity(santa)
for item in itemsGroup:
item.collect(santa)
item.itemGravity()
for floor in floorGroup:
floor.collision(santa)
updateScreen(santa)
CLOCK.tick(FPS)
`
You have to get the bounding rectangle of the scaled image instead of the original image:
self.rect = self.image.get_rect()
self.rect = self.scaledImage.get_rect()
Note that the pygame.sprite.Sprite object does not need a render or draw method if you use pygame.sprite.Group. See How can I add objects to a "pygame.sprite.Group()"? and What does pygame.sprite.Group() do

Why are my enemy bullets not deleting when they touch my player [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
So I been trying make it so when my enemy bullet's touch my player, it will disappear. My problem is that the bullets will randomly work for a couple of times then the next time it hits the player I get this error.
eguns.pop(eguns.index(egun))
ValueError: <__main__.main_loop.<locals>.enemybullets object at 0x06F69E50> is not in list
also here is a short clip showing what is happening.
https://gyazo.com/f7718fd6b1200af3cf2f77d1a559fa46
When I got hit by the bullet, my game just froze.
here is the part that is not working
for egun in eguns:
for one in range(len(eguns)-1-1-1):
if egun.rect.colliderect(playerman.rect):
eguns.pop(eguns.index(egun)) # this is the code that was spouse to make the bullet dissaper
Lives -= 1
text2 = font.render("Lives = "+str(Lives),True,(0,0,0))
textRect2.center = ((600,65))
My full code
import pygame
pygame.init()
# Build The Screen
window = pygame.display.set_mode((700,500))
fps = (10)
clock = pygame.time.Clock()
# COLORS
white = (255,255,255)
darkred = (200,0,0)
darkgreen = (0,200,0)
green = (0,255,0)
red = (255,0,0)
black = (0,0,0)
#######
# Start Screen
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(window, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window, ic,(x,y,w,h))
smallText = pygame.font.SysFont("comicsansms",40)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
window.blit(textSurf, textRect)
def quitgame():
pygame.quit()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
largeText = pygame.font.Font('freesansbold.ttf',95)
TextSurf, TextRect = text_objects("AIR FLIGHT", largeText)
TextRect.center = ((700/2),(500/2))
window.blit(TextSurf, TextRect)
button("Fly!",50,350,200,100,green,darkgreen,main_loop)
button("Land!",450,350,200,100,red,darkred,quitgame)
pygame.display.update()
clock.tick(fps)
# Start Screen
###
def main_loop():
global Dead
# Name Screen
pygame.display.set_caption("Noobs first Game")
bg = pygame.image.load("skybg1.png")
bg_shift = 0
# Class Player
class player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 6
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("heroplane1.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
def draw(self):
self.rect.topleft=(self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
player_rect = self.ss1.get_rect(center = self.rect.center)
player_rect.centerx += -7
player_rect.centery += -6
window.blit(self.ss1,player_rect)
# Class Enemy
class Enemy:
def __init__(self,x,y,width,height,color,imagefile):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 4
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load(imagefile)
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
self.etimer = 0 # <---
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy_rect = self.ss1.get_rect(center = self.rect.center)
enemy_rect.centerx += -2
enemy_rect.centery += -6
window.blit(self.ss1,enemy_rect)
# Class Enemy2
class Enemy2:
def __init__(self,x,y,width,height,color,imagefile):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 4
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load(imagefile)
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
self.etimer = 0 # <---
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy_rect = self.ss1.get_rect(center = self.rect.center)
enemy_rect.centerx += -4
enemy_rect.centery += -6
window.blit(self.ss1,enemy_rect)
class enemy3:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("enemyplane3.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy3_rect = self.ss1.get_rect(center = self.rect.center)
enemy3_rect.centerx += -4
enemy3_rect.centery += -6
window.blit(self.ss1,enemy3_rect)
# Class Enemy3
class Star:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("skycoin.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//12,self.ss1.get_height()//12))
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy3_rect = self.ss1.get_rect(center = self.rect.center)
enemy3_rect.centerx += -4
enemy3_rect.centery += -4
window.blit(self.ss1,enemy3_rect)
class projectile(object):
def __init__(self, x, y,color):
self.x = x
self.y = y
self.slash = pygame.image.load("herogun1.png")
self.slash = pygame.transform.scale(self.slash,(self.slash.get_width()//11,self.slash.get_height()//11))
self.rect = self.slash.get_rect()
self.rect.topleft = ( self.x, self.y )
self.speed = 10
self.color = color
def draw(self, window):
self.rect.topleft = ( self.x,self.y )
window.blit(self.slash, self.rect)
class enemybullets(object):
def __init__(self, x, y,color):
self.x = x
self.y = y
self.slash = pygame.image.load("enemygun1.png")
self.slash = pygame.transform.scale(self.slash,(self.slash.get_width()//11,self.slash.get_height()//11))
self.rect = self.slash.get_rect()
self.rect.topleft = ( self.x, self.y )
self.speed = 10
self.color = color
def draw(self, window):
self.rect.topleft = ( self.x,self.y )
window.blit(self.slash, self.rect)
class Power:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 4
self.rect = pygame.Rect(x,y,width,height)
def draw(self):
self.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
import pygame
pygame.init()
# Build The Screen
window = pygame.display.set_mode((700,500))
# Name Screen
pygame.display.set_caption("Noobs first Game")
bg = pygame.image.load("skybg1.png")
bg_shift = 0
# Class Player
class player:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 6
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("heroplane1.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
def draw(self):
self.rect.topleft=(self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
player_rect = self.ss1.get_rect(center = self.rect.center)
player_rect.centerx += -7
player_rect.centery += -6
window.blit(self.ss1,player_rect)
# Class Enemy
class Enemy:
def __init__(self,x,y,width,height,color,imagefile):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 4
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load(imagefile)
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
self.etimer = 0 # <---
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy_rect = self.ss1.get_rect(center = self.rect.center)
enemy_rect.centerx += -2
enemy_rect.centery += -6
window.blit(self.ss1,enemy_rect)
# Class Enemy2
class Enemy2:
def __init__(self,x,y,width,height,color,imagefile):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = 4
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load(imagefile)
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
self.etimer = 0 # <---
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy_rect = self.ss1.get_rect(center = self.rect.center)
enemy_rect.centerx += -4
enemy_rect.centery += -6
window.blit(self.ss1,enemy_rect)
class enemy3:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("enemyplane3.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//9,self.ss1.get_height()//9))
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy3_rect = self.ss1.get_rect(center = self.rect.center)
enemy3_rect.centerx += -4
enemy3_rect.centery += -6
window.blit(self.ss1,enemy3_rect)
# Class Enemy3
class Star:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = pygame.Rect(x,y,width,height)
self.ss1 = pygame.image.load("skycoin.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//12,self.ss1.get_height()//12))
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
enemy3_rect = self.ss1.get_rect(center = self.rect.center)
enemy3_rect.centerx += -4
enemy3_rect.centery += -4
window.blit(self.ss1,enemy3_rect)
class projectile(object):
def __init__(self, x, y,color):
self.x = x
self.y = y
self.slash = pygame.image.load("herogun1.png")
self.slash = pygame.transform.scale(self.slash,(self.slash.get_width()//11,self.slash.get_height()//11))
self.rect = self.slash.get_rect()
self.rect.topleft = ( self.x, self.y )
self.speed = 10
self.color = color
def draw(self, window):
self.rect.topleft = ( self.x,self.y )
window.blit(self.slash, self.rect)
class enemybullets(object):
def __init__(self, x, y,color):
self.x = x
self.y = y
self.slash = pygame.image.load("enemygun1.png")
self.slash = pygame.transform.scale(self.slash,(self.slash.get_width()//11,self.slash.get_height()//11))
self.rect = self.slash.get_rect()
self.rect.topleft = ( self.x, self.y )
self.speed = 10
self.color = color
def draw(self, window):
self.rect.topleft = ( self.x,self.y )
window.blit(self.slash, self.rect)
class Power:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 4
self.rect = pygame.Rect(x,y,width,height)
def draw(self):
self.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
# Color
white = (255,255,255)
black = (0,0,0)
# Draw Player
playerman = player(5,250,90,40,white)
# For Enemy
enemy1 = Enemy(400, 100, 90, 40, white, "enemyplane1.png")
enemy4 = Enemy(400, 400, 90, 40, white, "enemyplane1.png")
# For Enemy2
enemy21 = Enemy2(400,300,90,40,white,"enemyplane2.png")
enemy22 = Enemy2(400,100,90,40,white,"enemyplane2.png")
# For Coins
star1 = Star(300,250,45,45,white)
star2 = Star(300,350,45,45,white)
# For Enemy3
ememy31 = enemy3(400,400,90,40,white)
# For Enemy
enemys = [enemy1,enemy4]
#For Coin
stars = [star1,star2]
# enemys
enemyGroup = pygame.sprite.Group()
level1 = [
" 1 c 1 c 1 c c c ",
" c 1 1 1 c 1 c 1 1 1 1 1 1 1 c c c c c ",
" c 1 c 1 1 1 c 1 c 1 c c c ",
" c 1 c 1 c 1 1 1 c1 c 1 1 1 c 1 c 1 1 c c ",
" c c c c 1 1 c 1 c1 1 1 1 1 c1 1 c 1 1 c c c c ",
" c 1 c 1 c c 1 c 1 c c c ",
" 1 1 c 1 1 c 1 c1 1 c 1 1 cc 1 c 1 1 c 1 c c c c c",]
for iy, row in enumerate(level1):
for ix, col in enumerate(row):
if col == "1":
new_enemy = Enemy(ix*70,iy*70,90,40,(255,255,255),"enemyplane1.png")
enemys.append(new_enemy)
for iy, row in enumerate(level1):
for ix, col in enumerate(row):
if col == "c":
new_stars = Star(ix*70,iy*70,45,45,(255,255,255))
stars.append(new_stars)
enemy2Group = pygame.sprite.Group()
level2 = [
" ",
" ",
" ",
" ",
" ",
" ",
" ",]
for iy, row in enumerate(level2):
for ix, col in enumerate(row):
if col == "2":
new_enemy2 = Enemy2(ix*70,iy*70,90,40,(255,255,255),"enemyplane2.png")
Enemy2.append(new_enemy2)
Dead = False
def quitgame():
pygame.quit()
def unpause():
global Dead
Dead = False
def Die():
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("You Died!", largeText)
TextRect.center = ((700/2),(500/2))
window.blit(TextSurf, TextRect)
while Dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Fly!",50,350,200,100,green,darkgreen,main_loop)
button("Land!",450,350,200,100,red,darkred,quitgame)
pygame.display.update()
clock.tick(fps)
# Redrawwinodw
def redrawwindow():
window.fill((0,0,0))
bg_width = bg.get_width()
bg_offset = bg_shift % bg_width
window.blit(bg, (-bg_offset, 0))
window.blit(bg, (bg_width - bg_offset, 0))
# Draw playerman
playerman.draw()
# Draw enemy
for enemy in enemys:
enemy.draw()
# Draw enemy2
enemy21.draw()
# Draw enemy3
ememy31.draw()
#Draw Coin
for Star in stars:
Star.draw()
# Draw Enemy gun and playergun
for bullet in bullets:
bullet.draw(window)
for egun in eguns:
egun.draw(window)
window.blit(text,textRect)
window.blit(text2,textRect2)
window.blit(text3,textRect3)
# FPS Cnd Clock
fps = (30)
clock = pygame.time.Clock()
font = pygame.font.Font("freesansbold.ttf",30)
score = 0
text = font.render("Coins = "+str(score),True,(0,0,0))
textRect = text.get_rect()
textRect.center = ((600,40))
font = pygame.font.Font("freesansbold.ttf",30)
Lives = 10
text2 = font.render("Lives = "+str(Lives),True,(0,0,0))
textRect2 = text.get_rect()
textRect2.center = ((600,65))
font = pygame.font.Font("freesansbold.ttf",30)
enemyd = 0
text3 = font.render("Enemys Died = 10/ "+str(enemyd),True,(0,0,0))
textRect3 = text.get_rect()
textRect3.center = ((450,95))
# For Bullets List And Timer
bullets = []
btimer = 0
# For Enemy Bullets And Timer
eguns = []
etimer = 0
# Main Loop
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for Star in stars:
for one in range(len(stars)-1,-1,-1):
if playerman.rect.colliderect(stars[one].rect):
del stars[one]
score += 1
text = font.render("Coins = "+str(score),True,(0,0,0))
textRect.center = ((600,40))
for enemy in enemys:
for one in range(len(enemys)-1-1-1):
if enemys[one].rect.colliderect(playerman.rect):
del enemys[one]
enemyd += 1
text3 = font.render("Enemys Died = 10/ "+str(enemyd),True,(0,0,0))
textRect3.center = ((450,95))
Lives -= 1
text2 = font.render("Lives = "+str(Lives),True,(0,0,0))
textRect2.center = ((600,65))
for Enemys in enemys:
if enemy.x < 0:
enemy.x * playerman.x
for Star in stars:
Star.x -= playerman.speed
ememy31.x -= playerman.speed
# Timer for Bullets
if btimer > 0:
btimer += 1
if btimer > 10:
btimer = 0
# Timer for Enemy Bullets
if etimer > 0:
etimer += 1
if etimer > 13:
etimer = 0
# This Is Keys for bullet
keys = pygame.key.get_pressed()
# This is bullets and when player press Spacebar they come
for bullet in bullets:
if bullet.x < 700 and bullet.x > 0:
bullet.x += bullet.speed
else:
bullets.pop(bullets.index(bullet))
if keys[pygame.K_SPACE] and btimer == 0:
if len(bullets) < 5:
bullets.append(projectile(round(playerman.x+playerman.width//2),round(playerman.y + playerman.height-24),(0,0,0)))
btimer = 1
# Allow's enemy to disapper when it touches the player bullets
for Enemy in enemys:
for bullet in bullets:
for one in range(len(enemys)-1,-1,-1):
if bullet.rect.colliderect(enemys[one].rect):
del enemys[one]
bullets.pop(bullets.index(bullet))
enemyd += 1
text3 = font.render("Enemys Died = 10/ "+str(enemyd),True,(0,0,0))
textRect3.center = ((450,95))
#A PART OF THE Died FUNCTION
if Lives < 1:
Dead = True
Die()
# Timer for Enemy Bullets
for enemy in enemys:
if enemy.etimer > 0:
enemy.etimer += 1
if enemy.etimer > 40:
enemy.etimer = 0
# Allows enemy to shoot
for egun in eguns:
if egun.x < 700 and egun.x > 0:
egun.x -= egun.speed
else:
eguns.pop(eguns.index(egun))
for Enemy in enemys:
if Enemy.x < 700 and Enemy.etimer == 0:
if len(eguns) < 15:
eguns.append(enemybullets(round(Enemy.x+Enemy.width//2),round(Enemy.y + Enemy.height-24),(0,0,0)))
Enemy.etimer = 1
# What make's the player lose live's when it touch the bullets for enenmy
for egun in eguns:
for one in range(len(eguns)-1-1-1):
if egun.rect.colliderect(playerman.rect):
eguns.pop(eguns.index(egun))
Lives -= 1
text2 = font.render("Lives = "+str(Lives),True,(0,0,0))
textRect2.center = ((600,65))
# Makes enemy move
for Enemy in enemys:
Enemy.x -= Enemy.speed
# For The Background Shifting
bg_shift += round(3/2)
# Keys For Playerman
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and playerman.x > playerman.speed:
playerman.x -= playerman.speed
if keys[pygame.K_d] and playerman.x < 260 - playerman.width - playerman.speed:
playerman.x += playerman.speed
if keys[pygame.K_w] and playerman.y > playerman.speed:
playerman.y -= playerman.speed
if keys[pygame.K_s] and playerman.y < 500 - playerman.height - playerman.speed:
playerman.y += playerman.speed
# Update And Other Sutff
redrawwindow()
pygame.display.update()
pygame.quit()
unpause()
game_intro()
main_loop()
The nested loop is useless. Since one is never used you don't need the inner loop anyway.
When you want to remove an element from a list, while you iterate it, you have to take a copy of the list (eguns[:]). See How to remove items from a list while iterating?
. Iterate through the copy, but remove elements from the original list:
for egun in eguns[:]:
if egun.rect.colliderect(playerman.rect):
eguns.remove(egun)
# [...]
Anyway, it would be a lot easier and you wouldn't be in trouble using pygame.sprite.Sprite, pygame.sprite.Group and pygame.sprite.spritecollide() respectively pygame.sprite.Sprite.kill(), as intended in pygame.

How Do I Scroll My BackGround Image In Pygame? [duplicate]

This question already has answers here:
Making the background move sideways in pygame
(2 answers)
Closed 2 years ago.
I was Wonder How I Could Scroll mY background image in pygame
I have a moving object I want it to scroll when that object is moving
here is a video of the background image right now video
right now I am just blitting the background image
def redrawwindow():
window.blit(bg,(0,0))
here is my full code
import pygame
import random
pygame.init()
#this is screem height
window = pygame.display.set_mode((500,500))
#know we put screem name
pygame.display.set_caption("Noobs Flappy Bird Game")
#player class
class bird:
def __init__(self,x,y,height,width,color):
self.x = x
self.y =y
self.bright = [
pygame.image.load("killers50.png"),
pygame.image.load("killers51.png"),
pygame.image.load("killers52.png"),
pygame.image.load("killers53.png"),
]
self.bleft = [
pygame.image.load("ms1.png"),
pygame.image.load("ms2.png"),
pygame.image.load("ms3.png"),
pygame.image.load("ms4.png"),
]
self.bright = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bright]
self.bleft = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bleft]
self.height = height
self.width = width
self.isJump = False
self.JumpCount = 10
self.fall = 0
self.speed = 5
self.Walking = 0
self.vel = 5
self.color = color
self.rect = pygame.Rect(x,y,height,width)
self.direction = "down"
# this makes the enemy move right and left
def draw(self):
self.rect.topleft = (self.x,self.y)
if self.Walking + 1 >= 33:
self.Walking = 0
if self.vel > 0: # left
window.blit(self.bright[self.Walking % 3], (self.x,self.y))
self.Walking += 1
else: # right
window.blit(self.bleft[self.Walking % 3], (self.x,self.y))
self.Walking += 1
class platform:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.pipis = pygame.image.load("pip.png")
self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft=(self.x,self.y)
window.blit(self.pipis,self.rect)
class pip:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.pipis = pygame.image.load("pipo.png")
self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft=(self.x,self.y)
window.blit(self.pipis,self.rect)
#player and enemy
white = (255,255,255)
bird1 = bird(0,400,50,50,white)
red = (255,48,48)
platform1 = platform(600,300,150,50,white)
platform2 = platform(800,200,150,50,white)
platform3 = platform(1100,300,150,50,white)
platform4 = platform(1300,400,150,50,white)
platform5 = platform(1500,300,150,50,white)
platform6 = platform(1800,200,150,50,white)
# ROUND 2
platform7 = platform(2200,300,150,50,white)
platform8 = platform(2400,200,150,50,white)
platform9 = platform(2600,300,150,50,white)
platform10 = platform(2700,400,150,50,white)
platform11 = platform(2900,300,150,50,white)
platform12 = platform(3200,200,150,50,white)
# rOUND 3
platform13 = platform(3400,300,150,50,white)
platform14 = platform(3600,200,150,50,white)
platform15 = platform(3800,300,150,50,white)
platform16 = platform(4000,400,150,50,white)
platform17 = platform(4200,300,150,50,white)
platform18 = platform(4400,200,150,50,white)
# ROUND 4
platform19 = platform(600,300,150,50,white)
platform20 = platform(800,200,150,50,white)
platform21 = platform(1100,300,150,50,white)
platform22 = platform(1300,400,150,50,white)
platform23 = platform(1500,300,150,50,white)
platform24 = platform(1800,200,150,50,white)
platforms = [platform1,platform2,platform3,platform4,platform5,platform6,platform7,platform8,platform9,platform10,platform11,platform12,platform13,platform14,platform15,platform16,platform17,platform18,platform19,platform20,platform21,platform22,platform23,platform24]
# sceond pip
pip1 = pip(600,-160,150,50,white)
pip2 = pip(800,-270,150,50,white)
pip3 = pip(1100,-170,150,50,white)
pip4 = pip(1300,-170,150,50,white)
pip5 = pip(1500,-170,150,50,white)
pip6 = pip(1800,-270,150,50,white)
# ROUND 2
pip7 = pip(2200,-160,150,50,white)
pip8 = pip(2400,-270,150,50,white)
pip9 = pip(2600,-170,150,50,white)
pip10 = pip(2700,-170,150,50,white)
pip11 = pip(2900,-170,150,50,white)
pip12 = pip(3200,-270,150,50,white)
# ROUND 3
# rOUND 3
pip13 = pip(3400,-160,150,50,white)
pip14 = pip(3600,-270,150,50,white)
pip15 = pip(3800,-170,150,50,white)
pip16 = pip(4000,-170,150,50,white)
pip17 = pip(4200,-170,150,50,white)
pip18 = pip(4400,-270,150,50,white)
# ROUND 4
pip19 = pip(600,-160,150,50,white)
pip20 = pip(800,-270,150,50,white)
pip21 = pip(1100,-170,150,50,white)
pip22 = pip(1300,-170,150,50,white)
pip23 = pip(1500,-170,150,50,white)
pip24 = pip(1800,-270,150,50,white)
pips = [pip1,pip2,pip3,pip4,pip5,pip6,pip7,pip8,pip9,pip10,pip11,pip12,pip13,pip14,pip15,pip16,pip17,pip18,pip19,pip20,pip21,pip22,pip23,pip24]#window
class orb:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
class particleAndPoint:
def __init__(self,x,y,height,width,color):
self.x = x
self.y =y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
particleAndPoints = []
# this is the orbs
orb1 = orb(1500,100,50,550,white)
orb2 = orb(2600,100,50,550,white)
orbes = [orb1,orb2]
platformGroup = pygame.sprite.Group
platformList = []
level = [" ",
" ",
" ",
" ",
" p p p p p p p p p p p p p p p p p p",
" ",
" ",
" ",
" ",
" ",
" ",]
for iy, row in enumerate(level):
for ix, col in enumerate(row):
if col == "p":
new_platforms = particleAndPoint(ix*10, iy*0, 10,1010,(255,255,255))
particleAndPoints.append(new_platforms)
# the score text
font = pygame.font.Font('Candarai.ttf',60)
score = 0
loltext = font.render("" + str(score), True, (255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((130,60))
# wow sound anime
wowsound = pygame.mixer.Sound("wows.wav")
explodesound = pygame.mixer.Sound("partexplode.wav")
class particle:
def __init__(self,x,y):
self.x = x
self.y = y
self.x_vel = random.randrange(-10,13)*1
self.y_vel = random.randrange(-10,-1)*1
self.lifetime = 0
def draw(self,window):
self.lifetime += 1
if self.lifetime <30:
self.x -= self.x_vel
self.y -= self.y_vel
pygame.draw.rect(window,(232,255,24),(self.x,self.y, 16,16))
# draw the screen things
def redrawwindow():
bg = pygame.image.load("bgs.png")
window.blit(bg,(0,0))
#player draw
bird1.draw()
for platform in platforms:
platform.draw()
for pip in pips:
pip.draw()
for particleAndPoint in particleAndPoints:
particleAndPoint.draw()
window.blit(loltext,lolrect)
for orb in orbes:
orb.draw()
for particle in particles:
particle.draw(window)
fps = (30)
clock = pygame.time.Clock()
particles = []
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# if player collides with the obsticles add 1 to the player and delete the obstacle
for one in range(len(particleAndPoints)-1,-1,-1):
if bird1.rect.colliderect(particleAndPoints[one].rect):
score += 1
bird1.speed += 0.2
del particleAndPoints[one]
explodesound.play()
loltext = font.render("" + str(score), True, (255,255,255))
lolrect.center = ((130,60))
for x in range(60):
x, y = bird1.rect.center
particles.append( particle( x, y ) )
# if ball collides with player1 show the particles
# if ball collides with player1 show the particles
if bird1.rect.colliderect( orb1.rect ):
for x in range(60):
wowsound.play()
explodesound.play()
x, y = bird1.rect.center
particles.append( particle( x, y ) )
if bird1.rect.colliderect( orb2.rect ):
for x in range(60):
wowsound.play()
explodesound.play()
x, y = bird1.rect.center
particles.append( particle( x, y ) )
keys = pygame.key.get_pressed()
# bird moving
bird1.x += bird1.speed
if not bird1.isJump:
bird1.y += bird1.speed
bird1.isJump = False
if keys[pygame.K_SPACE]:
bird1.isJump = True
# this part lets you jump on platform
collide = False
for platform in platforms:
if bird1.rect.colliderect(platform.rect):
collide = False
# this makes the player fall down up to
if bird1.rect.bottom >= 500:
collide = True
bird1.isJump = False
bird1.JumpCount = 10
bird1.y = 500 - bird1.height
if collide:
if keys[pygame.K_SPACE]:
bird1.isJump = True
bird1.fall = 0
else:
if bird1.JumpCount > 0:
bird1.y -= (bird1.JumpCount*abs(bird1.JumpCount)) * 0.2
bird1.JumpCount -= 1
else:
bird1.JumpCount = 10
bird1.isJump = False
# this scrolls my screen right
if bird1.x > 300:
bird1.x -= bird1.speed
for platform in platforms:
platform.x -= bird1.speed
for pip in pips:
pip.x -=bird1.speed
for particleAndPoint in particleAndPoints:
particleAndPoint.x -= bird1.speed
for orb in orbes:
orb.x -= bird1.speed
redrawwindow()
pygame.display.update()
pygame.quit()
I want the background to keep scrolling right because my player is always moving right Thank YOu!
You have to draw the background twice in a tiled mode. Add a variable which defines the offset of the background bg_shift. Compute the offset in relation to the width of the background by the % (modulo) operator (See Binary arithmetic operations). Finally blit the background twice:
bg_shift = 0
def redrawwindow():
bg_width = gb.get_widht()
bg_offset = bg_shift % bg_width
window.blit(bg, (-bg_offset, 0))
window.blit(bg, (bg_width - bg_offset, 0))
You have to change the variabel bg_shift in the main application loop dependent on the movement of the bird.
bg_shift += bird1.speed
You can even try to move the background with a different speed, which gives a nice perspective effect. For instance:
bg_shift += round(bird1.speed / 2)

How Do I Make A Play Again Button That Restarts My Pygame From The Beginning Pygame? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
so I am remaking flappy bird and I wondering how I could make a remake button that restarts my game all over again video right now I have it as crashing the game when it collides with the pip
right now I have it has quiting my game when I collid with the pips
# colisions between the up platforms
for pip in pips:
if bird1.rect.colliderect(pip.hitbox):
print("collided")
pygame.quit()
keys = pygame.key.get_pressed()
heres my full code
import pygame
import random
pygame.init()
#this is screem height
window = pygame.display.set_mode((500,500))
#know we put screem name
pygame.display.set_caption("Noobs Flappy Bird Game")
#---------------------------------------------------
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(window, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window, ic,(x,y,w,h))
smallText = pygame.font.SysFont("Candarai.ttf",40)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
window.blit(textSurf, textRect)
#------------------------------------------------------
def text_objects(text, font):
black = (0,0,0)
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
# this makes it
snow_list=[]
no_of_circles=100;
clock = pygame.time.Clock()
FPS = 60
clock.tick(FPS)
for i in range(no_of_circles):
x = random.randrange(0, 600)
y = random.randrange(0, 500)
snow_list.append([x,y])
red = (200,0,0)
green = (255,250,250)
bright_red = (255,250,0)
bright_green = (0,255,0)
clock = pygame.time.Clock()
intro = True
while intro:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
window.fill((0,0,0))
for point in snow_list:
point[1]+=1
pygame.draw.circle(window, (255,255,255), point, 2)
if(point[1] >= 600):
point[0] = random.randrange(0, 600)
point[1] = random.randrange(-10, -5)
clock.tick(FPS)
font = pygame.font.Font("Candarai.ttf", 50)
loltext = font.render("Blaste OF Immunity", True,(255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((250,100))
window.blit(loltext,lolrect)
font = pygame.font.Font("Candarai.ttf", 50)
loltext = font.render("Classic Flappy Bird Game", True,(255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((250,160))
window.blit(loltext,lolrect)
font = pygame.font.Font("Candarai.ttf", 50)
loltext = font.render("By:Habib I.", True,(255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((280,460))
window.blit(loltext,lolrect)
button("Click To Play!",180,250,190,40,green,bright_green,main_game)
# ---------------------------------------------------------------------
pygame.display.update()
def main_game():
#player class
class bird:
def __init__(self,x,y,height,width,color):
self.x = x
self.y =y
self.bright = [
pygame.image.load("killers50.png"),
pygame.image.load("killers51.png"),
pygame.image.load("killers52.png"),
pygame.image.load("killers53.png"),
]
self.bleft = [
pygame.image.load("ms1.png"),
pygame.image.load("ms2.png"),
pygame.image.load("ms3.png"),
pygame.image.load("ms4.png"),
]
self.bright = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bright]
self.bleft = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bleft]
self.height = height
self.width = width
self.isJump = False
self.JumpCount = 10
self.fall = 0
self.speed = 5
self.Walking = 0
self.vel = 5
self.color = color
self.rect = pygame.Rect(x,y,height,width)
self.direction = "down"
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
# this makes the enemy move right and left
def draw(self):
self.rect.topleft = (self.x,self.y)
self.hitbox = (self.x + 17, self.y + 11, 29, 22)
pygame.draw.rect(window, (255,0,0), self.hitbox,2)
if self.Walking + 1 >= 33:
self.Walking = 0
if self.vel > 0: # left
window.blit(self.bright[self.Walking % 3], (self.x,self.y))
self.Walking += 1
else: # right
window.blit(self.bleft[self.Walking % 3], (self.x,self.y))
self.Walking += 1
class platform:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.pipis = pygame.image.load("pip.png")
self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
self.rect = pygame.Rect(x,y,height,width)
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
def draw(self):
self.rect.topleft=(self.x,self.y )
window.blit(self.pipis,self.rect)
self.rect.topleft = (self.x,self.y)
self.hitbox = (self.x + 5, self.y + 4, 79, 552)
pygame.draw.rect(window, (255,0,0), self.hitbox,2)
class pip:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.pipis = pygame.image.load("pipo.png")
self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
self.rect = pygame.Rect(x,y,height,width)
self.hitbox = (self.x + 17, self.y + -11, 29, 100)
def draw(self):
self.rect.topleft=(self.x,self.y)
window.blit(self.pipis,self.rect)
self.hitbox = (self.x + 5, self.y + -200, 79, 552)
pygame.draw.rect(window, (255,0,0), self.hitbox,2)
#player and enemy
white = (255,255,255)
bird1 = bird(0,400,40,20,white)
red = (255,48,48)
platform1 = platform(600,300,50,550,white)
platform2 = platform(800,200,90,550,white)
platform3 = platform(1100,300,90,550,white)
platform4 = platform(1300,400,90,550,white)
platform5 = platform(1500,300,90,550,white)
platform6 = platform(1800,200,90,550,white)
# ROUND 2
platform7 = platform(2200,300,90,550,white)
platform8 = platform(2400,200,90,550,white)
platform9 = platform(2600,300,90,550,white)
platform10 = platform(2700,400,90,550,white)
platform11 = platform(2900,300,90,550,white)
platform12 = platform(3200,200,90,550,white)
# rOUND 3
platform13 = platform(3400,300,90,550,white)
platform14 = platform(3600,200,90,550,white)
platform15 = platform(3800,300,90,550,white)
platform16 = platform(4000,400,90,550,white)
platform17 = platform(4200,300,90,550,white)
platform18 = platform(4400,200,90,550,white)
# ROUND 4
platform19 = platform(600,300,90,550,white)
platform20 = platform(800,200,90,550,white)
platform21 = platform(1100,300,90,550,white)
platform22 = platform(1300,400,90,550,white)
platform23 = platform(1500,300,90,550,white)
platform24 = platform(1800,200,90,550,white)
platforms = [platform1,platform2,platform3,platform4,platform5,platform6,platform7,platform8,platform9,platform10,platform11,platform12,platform13,platform14,platform15,platform16,platform17,platform18,platform19,platform20,platform21,platform22,platform23,platform24]
# sceond pip
pip1 = pip(600,-160,100,50,white)
pip2 = pip(800,-270,150,50,white)
pip3 = pip(1100,-170,150,50,white)
pip4 = pip(1300,-170,150,50,white)
pip5 = pip(1500,-170,150,50,white)
pip6 = pip(1800,-270,150,50,white)
# ROUND 2
pip7 = pip(2200,-160,150,50,white)
pip8 = pip(2400,-270,150,50,white)
pip9 = pip(2600,-170,150,50,white)
pip10 = pip(2700,-170,150,50,white)
pip11 = pip(2900,-170,150,50,white)
pip12 = pip(3200,-270,150,50,white)
# ROUND 3
# rOUND 3
pip13 = pip(3400,-160,150,50,white)
pip14 = pip(3600,-270,150,50,white)
pip15 = pip(3800,-170,150,50,white)
pip16 = pip(4000,-170,150,50,white)
pip17 = pip(4200,-170,150,50,white)
pip18 = pip(4400,-270,150,50,white)
# ROUND 4
pip19 = pip(600,-160,150,50,white)
pip20 = pip(800,-270,150,50,white)
pip21 = pip(1100,-170,150,50,white)
pip22 = pip(1300,-170,150,50,white)
pip23 = pip(1500,-170,150,50,white)
pip24 = pip(1800,-270,150,50,white)
pips = [pip1,pip2,pip3,pip4,pip5,pip6,pip7,pip8,pip9,pip10,pip11,pip12,pip13,pip14,pip15,pip16,pip17,pip18,pip19,pip20,pip21,pip22,pip23,pip24]#window
class orb:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
class particleAndPoint:
def __init__(self,x,y,height,width,color):
self.x = x
self.y =y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
particleAndPoints = []
# this is the orbs
orb1 = orb(1500,100,50,550,white)
orb2 = orb(2600,100,50,550,white)
orbes = [orb1,orb2]
platformGroup = pygame.sprite.Group
platformList = []
level = [" ",
" ",
" ",
" ",
" p p p p p p p p p p p p p p p p p p",
" ",
" ",
" ",
" ",
" ",
" ",]
for iy, row in enumerate(level):
for ix, col in enumerate(row):
if col == "p":
new_platforms = particleAndPoint(ix*10, iy*0, 10,1010,(255,255,255))
particleAndPoints.append(new_platforms)
# the score text
font = pygame.font.Font('Candarai.ttf',60)
score = 0
loltext = font.render("" + str(score), True, (255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((130,60))
# wow sound anime
wowsound = pygame.mixer.Sound("wows.wav")
explodesound = pygame.mixer.Sound("partexplode.wav")
class particle:
def __init__(self,x,y):
self.x = x
self.y = y
self.x_vel = random.randrange(-10,13)*1
self.y_vel = random.randrange(-10,-1)*1
self.lifetime = 0
def draw(self,window):
self.lifetime += 1
if self.lifetime <30:
self.x -= self.x_vel
self.y -= self.y_vel
pygame.draw.rect(window,(232,255,24),(self.x,self.y, 16,16))
# draw the screen things
# scrolling screen
bg_shift = 0
def redrawwindow():
bg = pygame.image.load("bgs.png")
bg_width = bg.get_width()
bg_offset = bg_shift % bg_width
window.blit(bg, (-bg_offset, 0))
window.blit(bg, (bg_width - bg_offset, 0))
#player draw
bird1.draw()
for platform in platforms:
platform.draw()
for pip in pips:
pip.draw()
for particleAndPoint in particleAndPoints:
particleAndPoint.draw()
window.blit(loltext,lolrect)
for orb in orbes:
orb.draw()
for particle in particles:
particle.draw(window)
fps = (30)
clock = pygame.time.Clock()
particles = []
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# if player collides with the obsticles add 1 to the player and delete the obstacle
for one in range(len(particleAndPoints)-1,-1,-1):
if bird1.rect.colliderect(particleAndPoints[one].rect):
score += 1
bird1.speed += 0.2
del particleAndPoints[one]
explodesound.play()
loltext = font.render("" + str(score), True, (255,255,255))
lolrect.center = ((130,60))
for x in range(60):
x, y = bird1.rect.center
particles.append( particle( x, y ) )
# if ball collides with player1 show the particles
# if ball collides with player1 show the particles
if bird1.rect.colliderect( orb1.rect ):
for x in range(60):
wowsound.play()
explodesound.play()
x, y = bird1.rect.center
particles.append( particle( x, y ) )
if bird1.rect.colliderect( orb2.rect ):
for x in range(60):
wowsound.play()
explodesound.play()
x, y = bird1.rect.center
particles.append( particle( x, y ) )
# collisions between the platforms
for platform in platforms:
if bird1.rect.colliderect(platform.hitbox):
print("collided")
pygame.quit()
# colisions between the up platforms
for pip in pips:
if bird1.rect.colliderect(pip.hitbox):
print("collided")
pygame.quit()
keys = pygame.key.get_pressed()
# bird moving
bird1.x += bird1.speed
if not bird1.isJump:
bird1.y += bird1.speed
bird1.isJump = False
if keys[pygame.K_SPACE]:
bird1.isJump = True
# this part lets you jump on platform
collide = False
for platform in platforms:
if bird1.rect.colliderect(platform.rect):
collide = False
# this makes the player fall down up to
if bird1.rect.bottom >= 500:
collide = True
bird1.isJump = False
bird1.JumpCount = 10
bird1.y = 500 - bird1.height
if collide:
if keys[pygame.K_SPACE]:
bird1.isJump = True
bird1.fall = 0
else:
if bird1.JumpCount > 0:
bird1.y -= (bird1.JumpCount*abs(bird1.JumpCount)) * 0.2
bird1.JumpCount -= 1
else:
bird1.JumpCount = 10
bird1.isJump = False
# this scrolls my screen right
if bird1.x > 300:
bird1.x -= bird1.speed
for platform in platforms:
platform.x -= bird1.speed
for pip in pips:
pip.x -=bird1.speed
for particleAndPoint in particleAndPoints:
particleAndPoint.x -= bird1.speed
for orb in orbes:
orb.x -= bird1.speed
# scrolling window
bg_shift += round(bird1.speed / 2)
redrawwindow()
pygame.display.update()
pygame.quit()
game_intro()
main_game()
I just want a basic functional button that allows my game to restart and works when my bird collides with the pips
black = (0,0,0)
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',25)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((500/2),(500/2))
window.blit(TextSurf, TextRect)
pygame.display.update()
main_game()
time.sleep(2)
def crash():
message_display('You Crashed')

TypeError: argument 1 must be pygame.Surface, not list [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 6 years ago.
Improve this question
I was working on a movement animations since I saw a youtuber explaining how to do it, but I'm getting this error:
TypeError: argument 1 must be pygame.Surface, not list
My code is about 500 lines.
# Pygame Template - skeleton for a new pygame project
import pygame
import random
import os
from os import path
vec = pygame.math.Vector2
width = 800
height = 600
FPS = 60
POWERUP_TIME = 5000
title = 'Parkourse'
# Player properties
player_acceleration = 0.5
player_friction = -0.12
player_gravity = 0.8
player_jump = 10
# Starting platforms
platforms_list = [(0,height-40,width,50), # Ground
(0,0,800,10), # Top
(0,0,10,600), # Left Border
(790,height-400,10,600),# Right Border
(250,height - 160,width-200,10), # Floor 1
(0,height - 280,width-200,10), # Floor 2
(250,height - 400,width-100,10)] # Floor 3
# Define Colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
# set up assets folders
game_folder = os.path.dirname(__file__)
image_folder = os.path.join(game_folder, "Image")
sound_folder = os.path.join(game_folder, "Sound")
# Initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption(title)
clock = pygame.time.Clock()
# Load all game graphics
background = pygame.image.load(path.join(image_folder, "background.png")).convert()
background_rect = background.get_rect()
no_mvmt_0 = pygame.image.load(path.join(image_folder,"no_mvmt_0.png")).convert()
no_mvmt_1 = pygame.image.load(path.join(image_folder,"no_mvmt_1.png")).convert()
running_0 = pygame.image.load(path.join(image_folder,"running_0.png")).convert()
running_1 = pygame.image.load(path.join(image_folder,"running_1.png")).convert()
jumping_0 = pygame.image.load(path.join(image_folder,"jumping_0.png")).convert()
mini_no_mvmt = pygame.transform.scale(no_mvmt_0, (25,48))
mini_no_mvmt.set_colorkey(white)
scissors = pygame.image.load(path.join(image_folder,"scissors.png")).convert()
mob_left = pygame.image.load(path.join(image_folder,"mob_left.png")).convert()
power_upper_image = {}
power_upper_image['shield_0'] = pygame.image.load(path.join(image_folder,"shield_upper_0.png")).convert()
power_upper_image['shield_1'] = pygame.image.load(path.join(image_folder,"shield_upper_1.png")).convert()
power_upper_image['shield_2'] = pygame.image.load(path.join(image_folder,"shield_upper_2.png")).convert()
power_upper_image['life'] = pygame.image.load(path.join(image_folder,"life_upper.png")).convert()
power_upper_image['power'] = pygame.image.load(path.join(image_folder,"power.png")).convert()
explosion_animation = {}
explosion_animation['normal']=[]
explosion_animation['small']=[]
explosion_animation['player']=[]
for explosion in range(5):
explose = 'explosion_{}.png'.format(explosion)
image = pygame.image.load(path.join(image_folder, explose)).convert()
image.set_colorkey(white)
image.set_colorkey(black)
image_normal = pygame.transform.scale(image, (80,80))
explosion_animation['normal'].append(image_normal)
image_small = pygame.transform.scale(image, (30, 30))
explosion_animation['small'].append(image_small)
death = 'dying_{}.png'.format(explosion)
image = pygame.image.load(path.join(image_folder, death)).convert()
image.set_colorkey(white)
explosion_animation['player'].append(image)
#Load all game sounds
scream_sound = []
for scream in ["slightscream_0.wav", "slightscream_1.wav", "slightscream_2.wav",
"slightscream_3.wav", "slightscream_4.wav", "slightscream_5.wav",
"slightscream_6.wav", "slightscream_7.wav", "slightscream_8.wav",
"slightscream_9.wav", "slightscream_10.wav", "slightscream_11.wav",
"slightscream_12.wav", "slightscream_13.wav", "slightscream_14.wav"]:
scream_sound.append(pygame.mixer.Sound(path.join(sound_folder,scream)))
shoot_sound = pygame.mixer.Sound(path.join(sound_folder,"shoot.wav"))
shield = pygame.mixer.Sound(path.join(sound_folder,"shield.wav"))
life = pygame.mixer.Sound(path.join(sound_folder,"life.wav"))
special_power = pygame.mixer.Sound(path.join(sound_folder,"special_power.wav"))
death_sound = pygame.mixer.Sound(path.join(sound_folder,"death.ogg"))
explosion_sound = []
for sound in ["explosion.wav", "explosion_2.wav"]:
explosion_sound.append(pygame.mixer.Sound(path.join(sound_folder, sound)))
pygame.mixer.music.load(path.join(sound_folder,"gameplay.ogg"))
pygame.mixer.music.set_volume(0.6)
font_name = pygame.font.match_font('arial')
def draw_text (surf, text,color,size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def newmob():
m = Mobs()
all_sprites.add(m)
mobs.add(m)
def draw_shield_bar(screen, x,y,percentage):
if percentage < 0:
percentage = 0
bar_lenght = 100
bar_height = 10
fill = (percentage / 100) * bar_lenght
outline_rect = pygame.Rect(x,y,bar_lenght,bar_height)
fill_rect = pygame.Rect(x,y,fill, bar_height)
pygame.draw.rect(screen, green, fill_rect)
pygame.draw.rect(screen, black, outline_rect, 2) # 2 is the the number of pixels
# of how wide you want the outline
# of the rectangle to be
def draw_lives (surface, x, y, lives, image):
for i in range(lives):
image_rect = image.get_rect()
image_rect.x = x + 30 * i
image_rect.y = y
surface.blit(image, image_rect)
score = 0
def show_game_over_screen():
screen.blit(background, background_rect)
draw_text(screen, "Dang..!",red,100, width/2, 200)
draw_text(screen, "Score: " + str(score),blue,30, width/2, 330)
draw_text(screen, "Press any key to retry",blue,30, width/2, 390)
pygame.display.flip()
waiting = True
while waiting:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
waiting = False
def show_start_screen():
screen.blit(background, background_rect)
draw_text(screen,"Parkourse!", green, 100, width/2, 200)
draw_text(screen, "Use the arrow keys to move, S to fire, and space to Jump",blue,30, width/2, 330)
draw_text(screen, "Press any key to begin",blue,30, width/2, 390)
pygame.display.flip()
waiting = True
while waiting:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
waiting = False
class Player (pygame.sprite.Sprite):
# Sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.load_movement_images()
self.image = self.standing_frame[0]
self.rect = self.image.get_rect()
self.pos = vec(50,500)
self.vel = vec(0,0)
self.acc = vec(0,0)
self.shield = 100
self.lives = 3
self.hidden = False
self.hide_timer = pygame.time.get_ticks()
self.power = 1
self.power_timer = pygame.time.get_ticks()
self.running = False
self.jumping = False
self.current_frame = 0
self.last_update = 0
def load_movement_images(self):
self.standing_frame = [no_mvmt_0, no_mvmt_1]
self.running_frame_right = [running_0,running_1]
self.running_frame_left = []
for frame in self.standing_frame:
frame.set_colorkey(white)
for frame in self.running_frame_right:
self.running_frame_left.append(pygame.transform.flip(frame,True,False)) # True is horizontaly, False is vertically
frame.set_colorkey(white)
self.jumping_frame = jumping_0
self.jumping_frame.set_colorkey(white)
def animate(self):
now = pygame.time.get_ticks()
if not self.jumping and not self.running:
if now - self.last_update > 350:
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.standing_frame)
self.image = self.standing_frame
def jump(self):
# Jump only if standing on a Platform
self.rect.x +=1
hits = pygame.sprite.spritecollide(player,platforms, False)
self.rect.x -= 1
if hits:
self.vel.y = - player_jump
def update(self):
self.animate()
# timeout for powerups
if self.power >=2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME:
self.power -= 1
self.power_time = pygame.time.get_ticks()
# unhide if hidden
if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:
self.hidden = False
self.pos = vec(30, 400)
self.acc = vec(0,player_gravity)
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT] or keystate[pygame.K_a]:
self.acc.x = -player_acceleration
if keystate[pygame.K_RIGHT] or keystate[pygame.K_d]:
self.acc.x = player_acceleration
if keystate[pygame.K_SPACE]:
player.jump()
# apply friction
self.acc.x += self.vel.x * player_friction
# equations of motions
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
# wrap around the sides of the screen
if self.pos.x > 750:
self.pos.x = 750
if self.pos.x <= 0:
self.pos.x = 25
self.rect.midbottom = self.pos
def powerup(self):
self.power += 1
self.power_time = pygame.time.get_ticks()
def shoot(self):
if self.power == 1:
bullet = Bullet(self.pos.x + 5, self.pos.y - 20)
all_sprites.add(bullet)
bullets.add(bullet)
shoot_sound.play()
if self.power >= 2:
bullet1 = Bullet(self.pos.x + 5, self.pos.y - 20)
bullet2 = Bullet(self.pos.x + 35, self.pos.y -20)
all_sprites.add(bullet1)
all_sprites.add(bullet2)
bullets.add(bullet1)
bullets.add(bullet2)
shoot_sound.play()
def hide(self):
# hide the player temporarily
self.hidden = True
self.hide_timer = pygame.time.get_ticks()
self.pos = vec(0, 6000)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = scissors
self.rect = self.image.get_rect()
self.image.set_colorkey(white)
self.image = pygame.transform.scale(scissors, (30,15))
self.rect.bottom = y
self.rect.centerx = x
self.speedx = 10
def update(self):
self.rect.x += self.speedx
# kill if it moves off the top of the screen
if self.rect.bottom < 0:
self.kill()
class Mobs(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = mob_left
self.rect = self.image.get_rect()
self.image.set_colorkey(white)
self.rect.x = random.randrange(0,800)
self.rect.y = 530
self.speedx = 2
def update(self):
self.rect.x -= self.speedx
if self.rect.right < 0:
self.rect.x = 800
class Explosion(pygame.sprite.Sprite):
def __init__(self, center, size, frame):
pygame.sprite.Sprite.__init__(self)
self.size = size
self.image = explosion_animation[self.size][0]
self.rect = self.image.get_rect()
self.rect.center = center
self.frame = 0
self.last_update = pygame.time.get_ticks()
self.frame_rate = frame
def update(self):
now = pygame.time.get_ticks()
if now - self.last_update > self.frame_rate:
self.last_update = now
self.frame += 1
if self.frame == len(explosion_animation[self.size]):
self.kill()
else:
center = self.rect.center
self.image = explosion_animation[self.size][self.frame]
self.rect = self.image.get_rect()
self.rect.center = center
class Normal_Power(pygame.sprite.Sprite):
def __init__(self, center):
pygame.sprite.Sprite.__init__(self)
self.type = random.choice(['shield_0','shield_1','shield_2'])
self.image = power_upper_image[self.type]
self.rect = self.image.get_rect()
self.image.set_colorkey(white)
self.rect.center = center
class Special_Power(pygame.sprite.Sprite):
def __init__(self, center):
pygame.sprite.Sprite.__init__(self)
self.type = random.choice(['life','power'])
self.image = power_upper_image[self.type]
self.rect = self.image.get_rect()
self.image.set_colorkey(white)
self.rect.center = center
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((w, h))
self.image.fill(black)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
pygame.mixer.music.play(loops=-1) # loops = -1 means that pygame will restart the song when it's finished
# Game loop
running = True
new_game = True
game_over = False
while running:
if new_game:
show_start_screen()
new_game = False
all_sprites = pygame.sprite.Group()
platforms = pygame.sprite.Group()
for plat in platforms_list:
p = Platform (*plat)
all_sprites.add(p)
platforms.add(p)
mobs = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
bullets = pygame.sprite.Group()
powerups = pygame.sprite.Group()
for i in range(1):
newmob()
score = 0
if game_over:
show_game_over_screen()
game_over = False
all_sprites = pygame.sprite.Group()
platforms = pygame.sprite.Group()
for plat in platforms_list:
p = Platform (*plat)
all_sprites.add(p)
platforms.add(p)
mobs = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
bullets = pygame.sprite.Group()
powerups = pygame.sprite.Group()
for i in range(1):
newmob()
score = 0
# Keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
player.shoot()
# Updates
all_sprites.update()
# check if player hits a platform - only if falling
if player.vel.y > 0:
hits = pygame.sprite.spritecollide(player,platforms,False)
if hits:
player.pos.y = hits[0].rect.top
player.vel.y = 0
# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs,bullets,True,True)
for hit in hits:
score += 1
random.choice(explosion_sound).play()
expl = Explosion(hit.rect.center, 'normal', 50)
all_sprites.add(expl)
if random.random() > 0.75:
power = Normal_Power(hit.rect.center)
all_sprites.add(power)
powerups.add(power)
if random.random() > 0.90:
lives = Special_Power(hit.rect.center)
all_sprites.add(lives)
powerups.add(lives)
newmob()
# check to see if the mob hit the player
hits = pygame.sprite.spritecollide(player, mobs,True)
for hit in hits:
random.choice(explosion_sound).play()
player.shield -= 25
newmob()
expl = Explosion(hit.rect.center, 'small', 50)
all_sprites.add(expl)
if player.shield <= 0:
death_sound.play()
death_animation = Explosion(player.rect.center, 'player', 100)
all_sprites.add(death_animation)
player.hide()
player.lives -= 1
player.shield = 100
else:
random.choice(scream_sound).play()
# check if the player hit a powerup
hits = pygame.sprite.spritecollide(player, powerups, True)
for hit in hits:
if hit.type == 'shield_0':
player.shield += 5
if player.shield >= 100:
player.shield = 100
shield.play()
if hit.type == 'shield_1':
player.shield += 20
if player.shield >= 100:
player.shield = 100
shield.play()
if hit.type == 'shield_2':
player.shield += 20
if player.shield >= 100:
player.shield = 100
shield.play()
if hit.type == 'life':
player.lives += 1
if player.lives >= 3:
player.lives = 3
life.play()
if hit.type == 'power':
special_power.play()
player.powerup()
# if the player died and the explosion finished playing
if player.lives == 0 and not death_animation.alive():
game_over = True
# Draw / Render
screen.fill(white)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen,str(score),red,30, width/ 2, 30)
draw_text(screen,"Score:",red,30, width / 2, 3)
draw_shield_bar(screen,90,20, player.shield)
draw_lives(screen,95,40,player.lives, mini_no_mvmt)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
quit()
The error is caused by a sprite in your all_sprites group that has a list as its self.image attribute. I've just printed the sprites before the all_sprites.draw(screen) line
for sprite in all_sprites:
print(sprite, sprite.image)
and it was the player sprite which had a list as its image.
<Player sprite(in 1 groups)> [<Surface(40x25x32 SW)>, <Surface(40x25x32 SW)>]
In the load_movement_images method you define self.standing_frame as a list of two images/pygame.Surfaces and in __init__ you set self.image to the first item of that list. But in the animate method you set self.image to the whole list instead of the active image self.image = self.standing_frame and that leads to the error.
class Player (pygame.sprite.Sprite):
# Sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.load_movement_images()
# self.image is the first image in the
# self.standing_frame list.
self.image = self.standing_frame[0]
# ...
def load_movement_images(self):
self.standing_frame = [no_mvmt_0, no_mvmt_1]
# ...
def animate(self):
now = pygame.time.get_ticks()
if not self.jumping and not self.running:
if now - self.last_update > 350:
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.standing_frame)
# Here you set the self.image to the self.standing_fram list instead one image.
self.image = self.standing_frame
# It should be:
# self.image = self.standing_frame[self.current_frame]

Categories

Resources