How to display text over a background? - python

I am trying to make a little game and I need to put some text over the background to show lives. But the text doesn't show up over the background and I don't know why. Any help is appreciated. All the drawing code is in the redrawgamewindow function. I know its something to do with the background maybe being put over the text but how would I fix this?
import random
import math
pygame.init()
GOLD = (255, 215, 0)
def text_objects(text, font):
textSurface = font.render(text, True, GOLD)
return textSurface, textSurface.get_rect()
screenwidth = 500
screenheight = 500
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('First Game')
bkg = pygame.image.load('2.jpg')
bkg = pygame.transform.scale(bkg, (500,500))
char1 = pygame.image.load('guy.png')
char1 = pygame.transform.scale(char1, (100, 100))
walkRight = []
walkLeft = []
HitAnim = []
Howmany = 4
for i in range(1, 13):
walkRight.append(pygame.transform.scale(pygame.image.load('R' + str(i) + '.png'), (100, 100)))
for i in range(1, 13):
walkLeft.append(pygame.transform.scale(pygame.image.load('L' + str(i) + '.png'), (100, 100)))
rockboom = pygame.image.load('b1.png')
rockboom = pygame.transform.scale(rockboom, (100,100))
GameO = pygame.image.load('GO.jpg')
rock = pygame.image.load('b.png')
rock = pygame.transform.scale(rock, (100, 100))
clock = pygame.time.Clock()
class player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.GameOver = False
self.vel = 10
self.walkCount = 0
self.left = False
self.right = False
self.lives = 3
self.hit = 0
self.hit1 = False
def draw(self, win):
if self.walkCount + 1 >= 27:
self.walkCount = 0
if self.left == True:
win.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
pygame.display.update()
elif self.right == True :
win.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
win.blit(char1, (self.x, self.y))
class rocky():
def __init__(self):
self.x = random.randrange(0, 430)
self.y = -100
def draw(self, win):
win.blit(rock, (self.x, self.y))
if man.hit1 == True:
win.blit (rockboom, (self.x, self.y))
def redrawgamewindow():
win.blit(bkg, (0, 0))
man.draw(win)
rock1.draw(win)
largeText = pygame.font.Font('freesansbold.ttf', 45)
TextSurf, TextRect = text_objects("Lives:" + str(man.lives), largeText)
TextRect.center = ((screenwidth / 2), (100 / 2))
pygame.display.flip()
def collided (rockx, rocky, manx, many):
man.hit = 0
distance = math.sqrt((math.pow(rockx-manx, 2) + (math.pow(rocky-many, 2))))
if distance < 75:
man.hit += 1
print("we be touched")
man.hit1 = True
else:
man.hit1 = False
my_list= []
for number in range(Howmany):
my_object = rocky()
my_list.append(my_object)
rock1 = rocky()
man = player(250, 350, 100, 100)
run = True
while run:
# Setting fps
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
# Getting keys pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and man.x > 0:
man.x -= man.vel
man.left = True
man.right = False
elif keys[pygame.K_RIGHT] and man.x < 500 - man.vel - man.width:
man.x += man.vel
man.left = False
man.right = True
else:
man.left = False
man.right = False
man.walkCount = 0
for rockk in my_list:
rock1.draw(win)
rock1.y += 5
if rock1.y >= 500:
rock1.x = random.randrange(0, 430)
rock1.y = -100
if man.hit1 == True:
rock1.x = random.randrange(0, 430)
rock1.y = -100
if man.hit == 1:
man.lives -=1
if man.hit ==2:
man.lives -=1
if man.lives <= 0:
print("so uh yeah it worked cool ")
exit()
collided(rock1.x, rock1.y, man.x, man.y)
redrawgamewindow()
win.blit(pygame.image.load('R1.png').convert_alpha(), (200, 200))

You're not blitting the text. Try this:
def redrawgamewindow():
win.blit(bkg, (0, 0))
man.draw(win)
rock1.draw(win)
largeText = pygame.font.Font('freesansbold.ttf', 45)
TextSurf, TextRect = text_objects("Lives:" + str(man.lives), largeText)
TextRect.center = ((screenwidth / 2), (100 / 2))
win.blit(TextSurf,TextRect)
pygame.display.flip()

Related

How do I make and end screen when my player class collide with one of my platform class?

So I been trying to make an end screen but I do know how, I have watched some tutorials but none of them really make's sense to me. I have also tried using my start screen but switch it up a little bit and putting it in a different spot but it dose not work. I am trying make it was when my player collides with one of my platforms the end screen shows up but I do not know how to make an end screen.
I do not know what to really put here but this is my start screen code
##############################################
#START MENUE
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",20)
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():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Jump", largeText)
TextRect.center = ((500/2),(500/2))
window.blit(TextSurf, TextRect)
button("GO!",100,350,100,50,green,darkgreen,main_loop)
button("Quit",300,350,100,50,orange,darkred,quitgame)
pygame.display.update()
clock.tick(15)
############################################
my Full code
import pygame
import time
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 first Game")
bg = pygame.image.load("New.png")
gg = pygame.image.load("lol.png")
Rule2 = pygame.image.load("one1.png")
Rule1 = pygame.image.load("two2.png")
Rule3 = pygame.image.load("three3.png")
Rule4 = pygame.image.load("four4.png")
Rule5 = pygame.image.load("five5.png")
Rule6 = pygame.image.load("six6.png")
#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.isJump = False
self.JumpCount = 10
self.fall = 0
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(window,self.color,self.rect)
class platform:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
self.ss1 = pygame.image.load("Rock.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//2,self.ss1.get_height()//2))
self.hitbox = (self.x + 20 , self.y,58,60)
def draw(self):
self.rect.topleft=(self.x,self.y)
player_rect = self.ss1.get_rect(center = self.rect.center)
player_rect.centerx += 70
player_rect.centery += 88
window.blit(self.ss1,player_rect)
self.hitbox = (self.x + 20 , self.y,58,60)
class item:
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
self.ss1 = pygame.image.load("H6.png")
self.ss1 = pygame.transform.scale(self.ss1,(self.ss1.get_width()//2,self.ss1.get_height()//2))
def draw(self):
self.rect.topleft = (self.x,self.y)
window.blit(self.ss1,self.rect)
class wall:
def __init__(self,x,y,width,height,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)
pygame.draw.rect(window,self.color,self.rect)
#draw player
white = (255,255,255)
player1 = player(255,400,30,30,white)
darkred = (200,0,0)
darkgreen = (0,200,0)
black = (0,0,0)
item1 = item(200,-500,50,50,white)
item2 = item(250,250,50,50,white)
item3 = item(330,-1030,50,50,white)
item4 = item(400,-2290,50,50,white)
item5 = item(300,-1600,50,50,white)
item6 = item(200,130,50,50,white)
item7 = item(230,-1830,50,50,white)
item8 = item(300,0,50,50,white)
item9 = item(330,-1440,50,50,white)
item10 = item(20,-160,50,50,white)
items = [item1,item2,item3,item4,item5,item6,item7,item8,item9,item10]
green = (0,255,0)
orange = (255,0,0)
platform1 = platform(100,300,10,60,orange)
platform2 = platform(5,200,10,60,orange)
platform3 = platform(5,400,10,60,orange)
platform4 = platform(100,100,10,60,orange)
platform5 = platform(5,-50,10,60,orange)
platform6 = platform(100,-200,10,60,orange)
platform7 = platform(5,400,60,600,orange)
platform8 = platform(300,-2430,10,60,orange)
platform9 = platform (350,-340,10,60,orange)
platform10 = platform (100,-470,10,60,orange)
platform13 = platform(330,-600,10,60,orange)
platform14 = platform(100,-790,10,60,orange)
platform15 = platform(330,-990,10,60,orange)
platform16 = platform(70,-1130,10,60,orange)
platform17 = platform(200,-1340,10,60,orange)
platform18 = platform(400,-1500,10,60,orange)
platform19 = platform(300,-1700,10,60,orange)
platform20 = platform(100,-1950,10,60,orange)
platform21 = platform (350,-2140,10,60,orange)
platform22 = platform (100,-2270,10,60,orange)
platform23 = platform(0,-2500,60,500,green)
#walls
platform11 = wall (485,-9600,10000,10,orange)
platform12 = wall (0,-9600,10000,10,orange)
wall1 = wall (0,400,60,500,orange)
wall2 = wall (0,-2500,60,500,green)
wall3 = wall (485,-9600,10000,10,orange)
wall4 = wall (0,-9600,10000,10,orange)
walls = [wall1,wall2]
platforms = (platform1,platform2,platform3,platform4,platform5,platform6,platform7,platform8,platform9,platform10,platform13,platform14,platform15,platform16,platform17,platform18,platform19,platform20,platform21,platform22,platform23)
fps = (60)
clock = pygame.time.Clock()
##############################################
#START MENUE
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",20)
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():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Jump", largeText)
TextRect.center = ((500/2),(500/2))
window.blit(TextSurf, TextRect)
button("GO!",100,350,100,50,green,darkgreen,main_loop)
button("Quit",300,350,100,50,orange,darkred,quitgame)
pygame.display.update()
clock.tick(15)
############################################
def main_loop():
#window
def redrawwindow():
window.fill((0,0,0))
window.blit(bg,(0,0))
#draw plyer
player1.draw()
platform11.draw()
platform12.draw()
wall3.draw()
wall4.draw()
for platform in platforms:
platform.draw()
for wall in walls:
wall.draw()
# the score draw it on the screen
window.blit(text,textRect)
for item in items:
item.draw()
font = pygame.font.Font("freesansbold.ttf",30)
score = 0
text = font.render("Coins = "+str(score),True,(255,255,255))
textRect = text.get_rect()
textRect.center = ((100,40))
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#walls
if player1.rect.colliderect(platform11) and player1.rect.colliderect(platform12):
player1.x = 40
# this makes you scroll up
if player1.y < 250:
player1.y += 1
#platforms
for platform in platforms:
platform.y += player1.speed
for item in items:
item.y += player1.speed
for wall in walls:
wall.y += player1.speed
#walls
platform11.y += player1.speed
platform12.y += player1.speed
# this makes you scroll down
if player1.y > 450:
player1.y -= player1.fall
for platform in platforms:
platform.y -= player1.fall
platform11.y -= player1.fall
platform12.y -= player1.fall
for item in items:
item.y -= player1.fall
for wall in walls:
wall.y -= player1.fall
# coin collisions
for item in items:
for one in range(len(items)-1,-1,-1):
if player1.rect.colliderect(items[one].rect):
del items[one]
score += 1
text = font.render("Coins = "+str(score),True,(255,255,255))
textRect.center = ((100,40))
keys = pygame.key.get_pressed()
if keys[pygame.K_a]and player1.x > player1.speed:
player1.x -= player1.speed
if keys[pygame.K_d]and player1.x <500 - player1.height - player1.speed:
player1.x += player1.speed
if keys[pygame.K_w]and player1.y > player1.speed:
player1.y -= player1.speed
if keys[pygame.K_s]and player1.y <500 - player1.width - player1.speed:
player1.y += player1.speed
if not player1.isJump:
player1.y += player1.fall
player1.fall += 1
player1.isJump = False
collide = False
# this part lets you jump on platform
for platform in platforms:
if player1.rect.colliderect(platform.rect):
collide = True
player1.isJump = False
player1.y = platform.rect.top - player1.height + 1
if player1.rect.right > platform.rect.left and player1.rect.left < platform.rect.left - player1.width:
player1.x = platform.rect.left - player1.width
if player1.rect.left < platform.rect.right and player1.rect.right > platform.rect.right + player1.width:
player1.x = platform.rect.right
if player1.rect.bottom >= 500:
collide = True
player1.isJump = False
player1.JumpCount = 10
player1.y = 500 - player1.height
if collide:
if keys[pygame.K_SPACE]:
player1.isJump = True
player1.fall = 0
else:
if player1.JumpCount >= 0:
player1.y -= (player1.JumpCount*abs(player1.JumpCount))*0.3
player1.JumpCount -= 1
else:
player1.JumpCount = 10
player1.isJump = False
redrawwindow()
if player1.rect.colliderect(platform6):
window.blit(Rule3,(-150,-80))
if player1.rect.colliderect(platform2.rect):
window.blit(Rule1,(-30,0))
if player1.rect.colliderect(platform23.rect):
window.blit(gg,(100,100))
if player1.rect.colliderect(platform7.rect):
window.blit(Rule2,(-70,0))
if player1.rect.colliderect(platform1.rect):
window.blit(Rule4,(-40,100))
if player1.rect.colliderect(platform14.rect):
window.blit(Rule5,(-50,0))
if player1.rect.colliderect(platform17.rect):
window.blit(Rule6,(-50,0))
pygame.display.update()
pygame.quit()
game_intro()
main_loop()
Here is a framework that might help you out. Along same lines as comment above. You need a boolean variable to keep track of when to show the end screen (something bad happened) and then use it to decide which screen to draw in your main loop...
def redrawwindow():
# basically what you have now...
def draw_end_screen():
# make this new function such that it shows your end-screen
run=True
end_condition=False # a new boolean variable to keep track if collision (or something else happened)
while run:
# basically what you have now....
# check for collision (in pseudo-code) check for game-ending events
if player1.collides_with_death...:
end_condition=True
if player1.falls_into_pit()...:
end_condition=True
# use the boolean variable to decide what to do next, and in next loop
if end_condition:
draw_end_screen()
else:
redrawwindow()
pygame.display.update()

how to handle time for different components in pygame

I'm making a pygame game where a person can purchase bombs from a shop. The player can also drop as many bombs as he buys. I need a way to make each bomb disappear after 3 seconds of it being dropped. In the following code I am just able to drop the bombs however I have tried various methods and failed.
import pygame
import random
pygame.font.init()
width = 900
height = 600
screen = pygame.display.set_mode([width, height])
walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]
char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
bomb_explosion = pygame.transform.scale(pygame.image.load('explosion1.png'), (40,40))
# char_rect = char.get_rect()
enemy_Left = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png')]
x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0
enemy_vel = 2
enemy_list = []
shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))
clock = pygame.time.Clock()
FPS = 60
font = pygame.font.Font('freesansbold.ttf', 32)
items_font = pygame.font.Font('freesansbold.ttf', 16)
bombs =[]
bag = {'bomb': 0}
print(bag["bomb"])
class Button():
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
def draw(self, win, outline=None):
# Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 20)
text = font.render(self.text, 1, (0, 0, 0))
win.blit(text, (
self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))
def shop_run():
shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_b")
bright_green = (0, 255, 0)
green = (0, 200, 0)
shop_bomb.draw(screen)
def redrawGameWindow():
global walkCount
global font
global bag
global items_font
global enemy_list
screen.fill([166, 166, 166])
for five_enemies in range(6):
random_enemy_location_y = random.randrange(100, 400)
random_enemy_location_x = random.randrange(800, 840)
enemy_list.append([random_enemy_location_x, random_enemy_location_y])
for enemies in range(6):
screen.blit(enemy_Left[enemies], enemy_list[enemies])
enemy_list[enemies][0] -= 0.3
pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
if x + char.get_width() < 60 and y + char.get_height() < 60:
shop_run()
screen.blit(shop, (0, 0))
screen.blit(font.render("Menu", True, (255,255,255)),(805, 10))
screen.blit(items_font.render("Bombs: "+ str(bag["bomb"]), True, (255, 255, 255)), (805, 550))
# screen.blit(bomb_explosion, (450, 300))
if walkCount + 1 >= 27:
walkCount = 0
if left:
screen.blit(walkLeft[walkCount // 3], (x, y))
walkCount += 1
elif right:
screen.blit(walkRight[walkCount // 3], (x, y))
walkCount += 1
elif down:
screen.blit(char, (x, y))
walkcount = 0
elif up:
screen.blit(char, (x, y))
walkcount = 0
else:
screen.blit(char, (x, y))
walkCount = 0
for pos in bombs:
screen.blit(bomb_pic, pos)
pygame.display.update()
def main():
run = True
# shopper()
pygame.display.set_caption("bomb-mania")
global x
global y
global width
global height
global vel
global isJump
global jumpCount
global left
global right
global down
global up
global walkCount
global bomb_pic
global font
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if x + char.get_width() < 60 and y + char.get_height() < 60:
buy = pygame.key.get_pressed()
if buy[pygame.K_b]:
bag["bomb"] += 1
print(bag["bomb"])
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
bombs.append(((x + (char.get_width()/2)),( y + (char.get_height() - 20))))
bag["bomb"] -= 1
redrawGameWindow()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel - 15:
x -= vel
left = True
right = False
down = False
up = False
elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
x += vel
left = False
right = True
down = False
up = False
elif keys[pygame.K_DOWN] and y < 600 - height:
y += vel
left = False
right = False
down = True
up = False
elif keys[pygame.K_UP] and y > vel - 15:
y -= vel
left = False
right = False
down = False
up = True
else:
left = False
right = False
down = False
up = False
walkCount = 0
clock.tick(FPS)
pygame.display.flip()
main()
Use pygame.time.get_ticks() to get the current time in milliseconds. Compute the time when the bomb has to disappear.
Store the time to the list bombs. The list bombs has to contain a tuple of position and time.
If the time is elapsed, then remove the bomb from the list:
def redrawGameWindow():
current_time = pygame.time.get_ticks()
# [...]
for i in reversed(range(len(bombs))):
pos, end_time = bombs[i]
if current_time > end_time
bombs.pop(i)
else:
screen.blit(bomb_pic, pos)
def main():
# [...]
while run:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# [...]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
pos = x + char.get_width()/2, y + char.get_height() - 20
end_time = current_time + 3000 # 3000 milliseconds = 3 seconds
bombs.append((pos, end_time))
bag["bomb"] -= 1
redrawGameWindow()

Is there a way to receive inputs from xbox controller triggers, in pygame? [duplicate]

import pygame
import os
import random
import time
import json
from pygame import joystick
pygame.font.init()
pygame.init()
WIDTH, HEIGHT = 1920, 1000
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("space invaders")
WHITE = (255, 255, 255)
#load images
RED_SPACE_SHIP = pygame.transform.scale(pygame.image.load(os.path.join("Assets", "pixel_ship_red_small.png")), (125, 100))
GREEN_SPACE_SHIP = pygame.transform.scale(pygame.image.load(os.path.join("Assets", "pixel_ship_green_small.png")), (125, 100))
BLUE_SPACE_SHIP = pygame.transform.scale(pygame.image.load(os.path.join("Assets", "pixel_ship_blue_small.png")), (125, 100))
#player
YELLOW_SPACE_SHIP = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join("Assets", "spaceship_yellow.png")), (154, 121)), 180)
#lasers
RED_LASER = pygame.image.load(os.path.join("Assets", "pixel_laser_red.png"))
BLUE_LASER = pygame.image.load(os.path.join("Assets", "pixel_laser_blue.png"))
GREEN_LASER = pygame.image.load(os.path.join("Assets", "pixel_laser_green.png"))
#player laser
YELLOW_LASER = pygame.image.load(os.path.join("Assets", "pixel_laser_yellow.png"))
#background
BG = pygame.transform.scale(pygame.image.load(
os.path.join('Assets', 'space.png')), (WIDTH, HEIGHT))
class Laser():
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
self.mask = pygame.mask.from_surface(self.img)
def draw(self, window):
window.blit(self.img, (self.x, self.y))
def move(self, vel):
self.y += vel
def off_screen(self, height):
return not(self.y <= height and self.y >= 0)
def collision(self, obj):
return collide(self, obj)
class Ship:
COOLDOWN = 30
def __init__(self, x, y, health = 100):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
def draw(self, window):
window.blit(self.ship_img, (self.x, self.y))
for laser in self.lasers:
laser.draw(window)
def move_lasers(self, vel, obj):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
self.lasers.remove(laser)
elif laser.collision(obj):
obj.health -= 10
self.lasers.remove(laser)
def cooldown(self):
if self.cool_down_counter >= self.COOLDOWN:
self.cool_down_counter = 0
elif self.cool_down_counter > 0:
self.cool_down_counter += 1
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def get_width(self):
return self.ship_img.get_width()
def get_height(self):
return self.ship_img.get_height()
class Player(Ship):
def __init__(self, x, y, health = 100):
super().__init__(x, y, health)
self.ship_img = YELLOW_SPACE_SHIP
self.laser_img = YELLOW_LASER
self.mask = pygame.mask.from_surface(self.ship_img)
self.max_health = health
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x + 26, self.y - 57, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def move_lasers(self, vel, objs):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
self.lasers.remove(laser)
else:
for obj in objs:
if laser.collision(obj):
objs.remove(obj)
if laser in self.lasers:
self.lasers.remove(laser)
def draw(self, window):
super().draw(window)
self.healthbar(window)
def healthbar(self, window):
pygame.draw.rect(window, (255, 0, 0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width(), 10))
pygame.draw.rect(window, (0, 255, 0), (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width()* (self.health/self.max_health),10))
class Enemy(Ship):
COLOR_MAP = {
"red": (RED_SPACE_SHIP, RED_LASER),
"green": (GREEN_SPACE_SHIP, GREEN_LASER),
"blue": (BLUE_SPACE_SHIP, BLUE_LASER)
}
def __init__(self, x, y, color, health = 100):
super().__init__(x, y, health)
self.ship_img, self.laser_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
def move(self, vel):
self.y += vel
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x - 3, self.y + 20, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def collide(obj1, obj2):
offset_x = obj2.x - obj1.x
offset_y = obj2.y - obj1.y
return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None
def main():
run = True
FPS = 60
level = 0
lives = 5
lost = False
lost_count = 0
main_font = pygame.font.SysFont("comicsans", 75)
lost_font = pygame.font.SysFont("comicsans", 500)
enemies = []
wave_length = 5
player_vel = 7
laser_vel = 7
enemy_vel = 1
player = Player(WIDTH // 2, 650)
clock = pygame.time.Clock()
def redraw_window():
WIN.blit(BG, (0,0))
#draw text
level_label = main_font.render(f"Level: {level}", 1, WHITE)
lives_label = main_font.render(f"Lives: {lives}", 1, WHITE)
WIN.blit(lives_label, (10, 10))
WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
player.draw(WIN)
for enemy in enemies:
enemy.draw(WIN)
if lost:
lost_label = lost_font.render("You Lost!", 1, (WHITE))
WIN.blit(lost_label, (WIDTH/2 - lost_label.get_width()/2, HEIGHT / 2 - lost_label.get_height() / 2))
pygame.display.update()
joysticks = []
for i in range(pygame.joystick.get_count()):
joysticks.append(pygame.joystick.Joystick(i))
for joystick in joysticks:
pygame.joystick.init()
print(pygame.joystick.get_init())
with open(os.path.join("ps4_keys.json"), 'r+') as file:
button_keys = json.load(file)
# 0: Left analog horizonal, 1: left analog verticle, 2: right analog horizonal
# 3: right analog verticle, 4: left Triger, 5: Right Trigger
analog_keys = {0:0, 1:0, 2:0, 3:0, 4:-1, 5:-1}
while run:
clock.tick(FPS)
redraw_window()
if lives <= 0 or player.health <= 0:
lost = True
lost_count += 1
if lost:
if lost_count > FPS * 3:
run = False
else:
continue
if len(enemies) == 0:
level += 1
wave_length += 5
for i in range(wave_length):
enemy = Enemy(random.randrange(100, WIDTH-100), random.randrange(-1500, -100), random.choice(["red", "blue", "green"]))
enemies.append(enemy)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.JOYAXISMOTION:
analog_keys[event.axis] = event.value
print(analog_keys)
if abs(analog_keys[0]) > .4:
if analog_keys[0] < -.7:
player.x -= 7
else:
continue
if analog_keys[0] < .7:
player.x += 7
for enemy in enemies[:]:
enemy.move(enemy_vel)
enemy.move_lasers(laser_vel, player)
if random.randrange(0, 120) == 1:
enemy.shoot()
if collide(enemy, player):
player.health -= 10
enemies.remove(enemy)
elif enemy.y + enemy.get_height() > HEIGHT:
lives -= 1
enemies.remove(enemy)
player.move_lasers(-laser_vel, enemies)
def main_menu():
title_font = pygame.font.SysFont("comicsans", 150)
run = True
while run:
WIN.blit(BG, (0,0))
title_label = title_font.render("Click the mouse to begin...", 1, WHITE)
WIN.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, HEIGHT / 2 - title_label.get_height() / 2))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
main()
pygame.quit()
main_menu()
^^^
so this is my code (here is the JSON file as well):
{
"x": 0,
"circle": 1,
"square": 2,
"triangle": 3,
"share": 4,
"PS": 5,
"options": 6,
"left_stick_click": 7,
"right_stick_click": 8,
"L1": 9,
"R1": 10,
"up_arrow": 11,
"down_arrow": 12,
"left_arrow": 13,
"right_arrow": 14,
"touchpad": 15
}
I'm trying to make the player be controlled by the controller left joystick and it returns no errors but my player does not move and it is printing true from the print(pygame.joystick.get_init()) and printing the joystick amounts from: print(analog_keys) but the player does not move. Any idea why?
Do not use the JOYAXISMOTION event. The event does not occur continuously, it only occurs once when the axis changes.
Use pygame.joystick.Joystick.get_axis to get the current position of the axis and move the player depending on the axis:
def main():
# [...]
while run:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if joysticks:
joystick = joysticks[0]
axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
if abs(axis_x) > 0.1:
player.x += round(7 * axis_x)
if abs(axis_y) > 0.1:
player.y += round(7 * axis_y)
# [...]
Minimal example:
import pygame
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
x, y = window.get_rect().center
if pygame.joystick.get_count() > 0:
joystick = pygame.joystick.Joystick(0)
joystick.init()
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
axis_x, axis_y = (joystick.get_axis(0), joystick.get_axis(1))
if abs(axis_x) > 0.1:
x = (x + round(7 * axis_x)) % window.get_width()
if abs(axis_y) > 0.1:
y = (y + round(7 * axis_y)) % window.get_height()
window.fill(0)
pygame.draw.circle(window, (255, 0, 0), (x, y), 10)
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()

Variable not switching to True?

I have a variable called left and it should turn to true when I hit the left arrow key but it doesn't seem to switch to true. It should also call the sprite walking left animation as a result of left turning true but obviously that isn't working I just need to know why the variable won't turn to true.
import pygame
import random
import math
pygame.init()
screenwidth = 500
screenheight = 500
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('First Game')
bkg = pygame.image.load('2.jpg')
char1 = pygame.image.load('guy.png')
char1 = pygame.transform.scale(char1, (100, 100))
walkRight = []
walkLeft = []
Howmany = 4
for i in range(1, 13):
walkRight.append(pygame.transform.scale(pygame.image.load('R' + str(i) + '.png'), (100, 100)))
for i in range(1, 13):
walkLeft.append(pygame.transform.scale(pygame.image.load('L' + str(i) + '.png'), (100, 100)))
GameO = pygame.image.load('GO.jpg')
rock = pygame.image.load('b.png')
rock = pygame.transform.scale(rock, (100, 100))
clock = pygame.time.Clock()
class player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.GameOver = False
self.vel = 10
self.walkCount = 0
self.left = False
self.right = False
self.lives = 3
self.hit = 0
self.hit1 = False
def draw(self, win):
if self.walkCount + 1 >= 27:
self.walkCount = 0
if self.left == True:
win.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
print ("hey we should be walking left right now ")
pygame.display.update()
elif self.right == True :
win.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
win.blit(char1, (self.x, self.y))
class rocky():
def __init__(self):
self.x = random.randrange(0, 430)
self.y = -100
def draw(self, win):
win.blit(rock, (self.x, self.y))
def redrawgamewindow():
win.blit(bkg, (0, 0))
man.draw(win)
rock1.draw(win)
pygame.display.flip()
def collided (rockx, rocky, manx, many):
man.hit = 0
distance = math.sqrt((math.pow(rockx-manx, 2) + (math.pow(rocky-many, 2))))
if distance < 75:
man.hit += 1
print("we be touched")
man.hit1 = True
else:
man.hit1 = False
my_list= []
for number in range(Howmany):
my_object = rocky()
my_list.append(my_object)
rock1 = rocky()
man = player(250, 400, 100, 100)
run = True
while run:
print (man.left)
# Setting fps
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
# Getting keys pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and man.x > 0:
man.x -= man.vel
man.left = True
man.right = False
elif keys[pygame.K_RIGHT] and man.x < 500 - man.vel - man.width:
man.x += man.vel
man.left = False
man.right = True
for rockk in my_list:
rock1.draw(win)
else:
man.left = False
man.right = False
man.walkCount = 0
rock1.y += 5
if rock1.y >= 500:
rock1.x = random.randrange(0, 430)
rock1.y = -100
if man.hit1 == True:
rock1.x = random.randrange(0, 430)
rock1.y = -100
if man.hit == 1:
man.lives -=1
if man.hit ==2:
man.lives -=1
if man.lives <= 0:
print("THE GAME IS OVER ")
exit()
collided(rock1.x, rock1.y, man.x, man.y)
redrawgamewindow()
win.blit(pygame.image.load('R1.png').convert_alpha(), (200, 200))
You have misplaced the else case. You accidentally put the else case at the end of for loop (else clause) and not after the if-elif statement:
if keys[pygame.K_LEFT] and man.x > 0:
man.x -= man.vel
man.left = True
man.right = False
elif keys[pygame.K_RIGHT] and man.x < 500 - man.vel - man.width:
man.x += man.vel
man.left = False
man.right = True
# INSERT
else:
man.left = False
man.right = False
man.walkCount = 0
for rockk in my_list:
rock1.draw(win)
# DELETE
#else:
# man.left = False
# man.right = False
# man.walkCount = 0

How to trigger an event when at least one round in a for loop is "True"

I am making a space invader/dodging game in pygame. I have items that you can touch to e.g. increase health. When the sprite touches the health item, I want the background to be green momentarily.
Below is what I have at the moment. Since I have more than 1 item on the screen at a time, I check for each time using (line 1). You can see that when touching potion, the fillcolor is set to green
The problem is if the sprite is only touching 1 of the 2 items in the screen, the background will be set to black when checking for the second one.
How do I make it so that if at least 1 of the 2 items is being touched, the background becomes green?
EDIT:
I had made the question too vague in fear of making it too long, so here are more details.
fillcolor is the variable that sets the background color of the window. There are three types of items that you can touch, and a maximum of 2 items can appear at once, regardless of the type of item.
This might be a bit long, but what is going wrong is:
By using the for loop, I am checking the 2 items on the screen, and checking if the item you hit is a potion, ammunition or "fever mode"(powerup item). As you can see if it is "potion", your health is increased and if it is "ammo" your ammo count is being increased. For example if there are two items on the screen and you are touching one of them, which is a potion. Then the background becomes green, however in the next round of the for loop when checking the second item, fillcolor instantly becomes black because you are not touching both of the items, only one of them. What is want to do is to make the background green if you are touching one of them, even if the second one is not touched.
for e in items:
ship.checkItemCollision(e, ship)
if ship.checkItemCollision(e, ship) == 'potion':
print('potion')
ship.health += 0.5
fillcolor = (0, 255, 0)
touchDatItem = True
elif ship.checkItemCollision(e, ship) == 'ammo':
print('ammo')
ammoCount += 1
fillcolor = (255, 255, 0)
touchDatItem = True
elif ship.checkItemCollision(e, ship) == 'fever':
print('fever')
feverMode = True
fillcolor = (255, 0, 0)
touchDatItem = True
elif not touchDatItem:
fillcolor = black
Here's the whole code:
import pygame as pg
import time
import random
import math
pg.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
bllue = (0, 0, 255)
green = (0, 200, 0)
bright_red =(255, 0, 20)
bright_green = (0, 255, 0)
yellow = (255,255,0)
dark_yellow = (150, 150, 0)
clock = pg.time.Clock()
potion = pg.image.load('revive.png')
ammo = pg.image.load('ammo.png')
fever = pg.image.load('fever.png')
gameDisplay = pg.display.set_mode((display_width, display_height))
pg.display.set_caption('Object Oriented')
class Item:
def __init__(self):
self.items = [potion, potion, potion, ammo, ammo,ammo, ammo, ammo, fever, fever, fever, fever, fever, fever, fever, fever, fever, fever, fever, fever, fever, ]
self.images = potion
self.speed = 3
self.width = 30
self.height = 30
self.x = 30
self.y = random.randrange(-1000, -300)
def move(self):
self.y += self.speed
if self.y > display_height:
self.x = random.randrange(0, (display_width - self.width))
self.y = random.randrange(-5000, -1000)
self.images = random.choice(self.items)
def draw(self):
gameDisplay.blit(self.images, (self.x, self.y))
class Thing:
def __init__(self):
self.width = 20
self.height = 20
self.x = random.randrange(0, (display_width - self.width))
self.y = random.randrange(-500, 0)
self.speedY = 3
self.speedX = 3
self.color = bright_red
self.ratio = random.randrange(-3, 3)
def move(self, count):
if self.ratio == 0:
self.y += self.speedY
else:
self.y += self.speedY
## self.x += random.randint(-5, 5)
self.x += self.ratio
if self.y > display_height:
self.x = random.randrange(0, (display_width - self.width))
self.y = random.randrange(-500, 0)
self.ratio = random.randrange(-3, 3)
return True
def draw(self):
pg.draw.rect(gameDisplay, self.color, [self.x, self.y, self.height, self.width])
## def randomizeX(self):
## self.x = random.randrange(0, (display_width - self.width))
## def resetY(self):
## self.y = 05
##def checkQuit():
## for event in pg.event.get():
## if event.type == pg.QUIT:
## pg.quit()
## quit()
class Ship:
def __init__(self):
self.x = display_width / 2
self.y = display_height / 2
self.speed = 10
self.height = 20
self.width = 20
self.color = yellow
self.changeX = 0
self.changeY = 0
self.health = 100
## def move(self, event):
##
## if event.type == pg.KEYDOWN:
## print(event.key)
## if event.key == pg.K_LEFT:
## self.change = -(self.speed)
## if event.key == pg.K_RIGHT:
## self.change = self.speed
## if event.type == pg.KEYUP:
## if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
## self.change = 0
## self.x += self.change
def draw(self):
pg.draw.rect(gameDisplay, self.color, [self.x, self.y, self.height, self.width])
def moveShip(self, event):
if event.type == pg.KEYDOWN:
## print(self.changeY)
## print(self.changeX)
if event.key == pg.K_LEFT:
self.changeX = -(self.speed)
if event.key == pg.K_RIGHT:
self.changeX = self.speed
if event.key == pg.K_UP:
self.changeY = -(self.speed)
if event.key == pg.K_DOWN:
self.changeY = self.speed
if event.type == pg.KEYUP:
if event.key == pg.K_LEFT or event.key == pg.K_RIGHT or event.key == pg.K_UP or event.key == pg.K_DOWN:
self.changeX = 0
self.changeY = 0
def testWallCollision(self):
if self.x > (display_width - self.width) or self.x < 0:
self.health = self.health/2
def checkThingCollision(self, t, ship, fillcolor, red, count):
# if thing_starty < (y + car_height) and y < (thing_starty+thing_height):
if (t.y - (t.height/2)) < (ship.y + ship.height) and ship.y < ((t.y - (t.height/2)) + t.height):
if (self.x > t.x and self.x < (t.x + t.width) or ((self.x + t.width) > t.x and (self.x + t.width) < t.x + t.width)):
self.health -= 0.5
t.x = random.randrange(0, (display_width - t.width))
t.y = random.randrange(-500, 0)
t.ratio = random.randrange(-10, 10)
def checkItemCollision(self, e, ship):
if e.y < (ship.y + ship.height) and ship.y < (e.y + e.height):
if (self.x > e.x and self.x < (e.x + e.width) or ((self.x + e.width) > e.x and (self.x + e.width) < e.x + e.width)):
if e.images == potion:
return 'potion'
elif e.images == ammo:
return 'ammo'
elif e.images == fever:
return 'fever'
class Bullet:
def __init__(self, ship):
self.speed = 20
self.color = white
self.x = ship.x + (ship.width / 2)
self.y = ship.y + (ship.width / 2)
self.height = 5
self.width = 5
def draw(self):
## print('IN DRAAAAAW')
## if event.key == pg.K_SPACE:
pg.draw.rect(gameDisplay, self.color, [self.x, self.y, self.height, self.width])
def move(self, ship):
self.y -= self.speed
## if self.y < 0:
## self.x = ship.x + (ship.width / 2)
## self.y = ship.y + (ship.width / 2)
def checkCollision(self, t, ship, count):
if t.y < (self.y + self.height) and self.y < (t.y + t.height):
if (self.x > t.x and self.x < (t.x + t.width) or ((self.x + t.width) > t.x and (self.x + t.width) < t.x + t.width)):
t.x = random.randrange(0, (display_width - t.width))
t.y = random.randrange(-500, 0)
t.ratio = random.randrange(-10, 10)
self.y = -self.height
return True
def healthNum(health, color):
font = pg.font.SysFont(None, 25)
text = font.render('health:' + str(health) + '/100', True, color)
gameDisplay.blit(text, (500, 0))
def ammoNum(ammoCount, color):
font = pg.font.SysFont(None, 25)
text = font.render('ammo:' + str(ammoCount), True, color)
gameDisplay.blit(text, (300, 0))
def things_dodged(count):
font = pg.font.SysFont(None, 25)
text = font.render('score: ' + str(count), True, white)
gameDisplay.blit(text, (0, 0))
def main_loop():
touchDatItem = False
feverTimer = 0
gameExit = False
allItems = [potion, ammo]
things = []
ship = Ship()
bullets = []
fillcolor = black
count = 0
items = []
ammoCount = 20
FEVER = False
LIST = []
feverMode = False
for t in range (30):
things.append(Thing())
for e in range(2):
items.append(Item())
while not gameExit:
print(fillcolor)
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
quit()
ship.moveShip(event)
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
## FEVER = True
if ammoCount > 0:
bullets.append(Bullet(ship))
if not feverMode:
ammoCount -= 1
if feverMode:
FEVER = True
else:
FEVER = False
if event.type == pg.KEYUP:
if event.key == pg.K_SPACE:
FEVER = False
if FEVER == True:
feverTimer += 1
if not feverTimer > 100:
if ammoCount > 0:
bullets.append(Bullet(ship))
else:
print('STAAAAAAAAAP')
FEVER = False
feverTimer = 0
feverMode = False
ship.x += ship.changeX
ship.y += ship.changeY
ship.testWallCollision()
gameDisplay.fill(fillcolor)
LIST = []
healthNum(ship.health, white)
ammoNum(ammoCount, white)
for t in things:
ship.checkThingCollision(t, ship, fillcolor, red, count)
if ship.checkThingCollision(t, ship, fillcolor, red, count) == True:
print('###########################')
ship.color = red
else:
ship.color = yellow
t.draw()
ship.draw()
t.move(count)
if t.move(count) == True:
count+= 1
for b in bullets:
b.draw()
for t in things:
b.checkCollision(t, ship, count)
if b.checkCollision(t, ship, count) == True:
count += 10
b.move(ship)
for e in items:
ship.checkItemCollision(e, ship)
if ship.checkItemCollision(e, ship) == 'potion':
LIST.append('potion')
print('potion')
ship.health += 0.5
touchDatItem = True
elif ship.checkItemCollision(e, ship) == 'ammo':
LIST.append('ammo')
print('ammo')
ammoCount += 1
touchDatItem = True
elif ship.checkItemCollision(e, ship) == 'fever':
LIST.append('fever')
print('fever')
feverMode = True
touchDatItem = True
if 'potion' in LIST:
fillcolor = (0, 255, 0)
elif 'ammo' in LIST:
fillcolor = (255, 255, 0)
elif 'fever' in LIST:
fillcolor = (255, 0, 0)
else:
fillcolor = black
e.draw()
e.move()
print('fillcolor = ' + str(fillcolor))
if ship.health < 1:
ship.health = 0
pg.quit()
quit()
things_dodged(count)
pg.display.update()
clock.tick(60)
pg.quit()
quit()
main_loop()
That happens when you invent your own collision detection function instead of using pygame's collision detection methods. ;) Your checkItemCollision method is incorrect.
Change this line ...
if (self.x > e.x and self.x < (e.x + e.width) or ((self.x + e.width) > e.x and (self.x + e.width) < e.x + e.width)):
to this:
if (self.x > e.x and self.x < e.x + e.width or self.x + self.width > e.x and self.x + self.width < e.x + e.width):
I'm still not 100% sure if everything is correct now. I'd give your objects a self.rect attribute and use it for the collision detection instead, e.g.:
# In __init__:
self.rect = pg.Rect(self.x, self.y, self.width, self.height)
# Then check if they collide with the `colliderect` method.
self.rect.colliderect(e.rect)
The rect needs to be moved as well when you update the positions.

Categories