0
import pygame         
from sys import exit
import random

pygame.init()

WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game!")
fps = pygame.time.Clock()
active = True

test_font = pygame.font.Font("letters.ttf", 50)
text_surface = test_font.render("Samad ge mig ett A!", False, (64,64,64))
text_rect = text_surface.get_rect(center = (400,50))

#Box
box_x = random.randint(10, 800)
box = pygame.image.load("box.png").convert_alpha() 
box_rect = box.get_rect(midbottom = (box_x,540))

#Background och Ground
background = pygame.image.load("sky.png").convert()
ground = pygame.image.load("ground.png").convert()

#player PNG 
player = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.rotozoom(player,0,2.5)
player_rect = player.get_rect(midbottom = (400,325))

#pickaxe PNG
pickaxe = pygame.image.load("pickaxe.png").convert_alpha()
pickaxe = pygame.transform.rotozoom(pickaxe,0,3.5)
pickaxe_rect = pickaxe.get_rect(center = (400,325))

#Gravity
player_gravity = 0
pickaxe_gravity = 0

while True:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      exit()
  
    if active:
      if event.type == pygame.MOUSEBUTTONDOWN:
        if player_rect.collidepoint(event.pos) and player_rect.bottom >= 325: 
          player_gravity = -20
          pickaxe_gravity = -20
      
      if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT or event.key == pygame.K_a:
          player_rect.x -= 20
          pickaxe_rect.x -= 20

        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
          player_rect.x += 20
          pickaxe_rect.x += 20
          
        if (event.key == pygame.K_SPACE or event.key == pygame.K_w or event.key == pygame.K_UP) and player_rect.bottom >= 325:
          player_gravity = -20
          pickaxe_gravity = -20
          
  if active:
    screen.blit(background,(0,0))
    screen.blit(ground,(0,300))
    screen.blit(box, box_rect)
    screen.blit(pickaxe, pickaxe_rect)
    screen.blit(player,player_rect)
    screen.blit(text_surface, text_rect)
    
    player_gravity += 1
    pickaxe_gravity += 1
    player_rect.y += player_gravity
    pickaxe_rect.y += pickaxe_gravity
    if pickaxe_rect.bottom >= 325: pickaxe_rect.bottom = 325
    if player_rect.bottom >= 325: player_rect.bottom = 325

    if player_rect.x <= -10 and pickaxe_rect.x <= -10:
      player_rect.x = -10
      pickaxe_rect.x = player_rect.x - 70

    if player_rect.colliderect(box_rect): print("1")

  pygame.display.update()
  fps.tick(60)

I was trying to get the player to collide with the box but whenever I try it, it always says that it collided even tho i clearly see that it hasn't. Please tell me how to fix it.

I thought that when the player was on the box (or touching it) then it would print "1" that it touched it but it always says "1" even thought i didnt touch it.

0 Answers0