I want in my game to end the game whenever the green triangle hits the square. I don't know why the collision doesnt work, could you help me with this problem?
import os
pygame.font.init()
pygame.init()
import time
#VARIABLES
#-------------------------
#SCREEN
width, height = 900, 500
WIN = pygame.display.set_mode((width, height))
FPS = 100
clock = pygame.time.Clock()
FONT = pygame.font.SysFont('verdana', 100)
#EVENTS
square_hit = pygame.USEREVENT + 1
#COLORS
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0, 255, 0)
blue = (0, 0, 255)
#-------------------------
Here i'm desplaying the window
def draw_window(square, triangle, score):
#SCREEEN
WIN.fill(black)
#SCORE
score_text = FONT.render("Score: " +str(score), 1, white)
WIN.blit(score_text, (width - score_text.get_width() - 10, 10))
#OBJECTS
#LINE
pygame.draw.line(WIN, blue, (0, 400), (900, 400), 10)
#SQUARE
square.draw()
#TRIANGLE
triangle.draw()
pygame.display.update()
Here is the triangle (enemy) class
class Triangle():
def __init__(self):
self.x = 700
self.vel = 10
self.triangle_rect = pygame.draw.polygon(WIN, green, [[self.x, 395], [self.x + 50, 395], [self.x + 25, 345]])
def draw(self):
pygame.draw.polygon(WIN, green, [[self.x, 395], [self.x + 50, 395], [self.x + 25, 345]])
def move(self, score):
self.x -= 5
if self.x == -50:
self.x = 900
score += 1
return score
PROBABLY HERE IS THE PROBLEM
def collision(self, square, square_hit):
if square.square_rect.colliderect(self.triangle_rect):
pygame.event.post(pygame.event.Event(square_hit))
return square_hit
Here is square (character) class
class Square():
def __init__(self):
self.y = 295
self.vel = 10
self.square_rect = pygame.draw.rect(WIN, red, pygame.Rect(50, self.y, 100, 100))
def draw(self):
pygame.draw.rect(WIN, red, pygame.Rect(50, self.y, 100, 100))
def jump(self, jumpCount):
jump = True
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
self.y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 0.5
else:
jump = False
jumpCount = 10
return jump, jumpCount
Here is main game loop
score = 0
jump = False
jumpCount = 10
triangle = Triangle()
square = Square()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#JUMPING
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
if event.type == square_hit:
pygame.time.delay(2000)
if jump:
jump, jumpCount = square.jump(jumpCount)
triangle.collision(square, square_hit)
score = triangle.move(score)
draw_window(square, triangle, score)
pygame.quit()
if __name__ == "__main__":
main()