Problem is, whatever i tried to put in this part of the code:
LOPTICA = LOPTICA.move(BRZINA_LOPTICE)
if LOPTICA.left < 0 or LOPTICA.right > width:
##what i should put here
It got crashed application or ball ("LOPTICA") went out of the screen instead of getting back in the default position.
I need some variable or function to put in this, so ball ("LOPTICA") and the rest of the game get reset to the default positions.
import pygame
import os
width, height = 900, 500
screen = pygame.display.set_mode((width, height))
FPS = 60
BRZINA = 6
x = 450
y = 250
BRZINA_LOPTICE = [4.5, 4.5]
ikonica = pygame.image.load(os.path.join('dodaci', "ikonica.png"))
ime = pygame.display.set_caption('Ping Pong')
ikonica_u_igri = pygame.display.set_icon(ikonica)
pozadina = pygame.image.load(os.path.join('dodaci', 'pozadina.jpg'))
BOJALINIJE = (255, 255, 255)
BOJALOPTICE = (224, 15, 0)
LEVALINIJA = pygame.Rect(100, 220, 7, 100)
DESNALINIJA= pygame.Rect(800, 220, 7, 100)
radius= 10
LOPTICA = pygame.Rect(width//2, height//2, radius*2, radius)
def prikaz_pozadine():
screen.blit(pozadina, (0, 0))
pygame.draw.rect(screen, BOJALINIJE, LEVALINIJA)
pygame.draw.rect(screen, BOJALINIJE, DESNALINIJA)
pygame.draw.circle(screen, BOJALOPTICE, LOPTICA.center, radius)
pygame.display.update()
def kretanje_linija(LEVALINIJA, DESNALINIJA):
tasteri_kretanja = pygame.key.get_pressed()
if tasteri_kretanja[pygame.K_w] and LEVALINIJA.y - BRZINA > 0:
LEVALINIJA.y -= BRZINA
if tasteri_kretanja[pygame.K_s] and LEVALINIJA.y + BRZINA + LEVALINIJA.height < height:
LEVALINIJA.y += BRZINA
if tasteri_kretanja[pygame.K_UP] and DESNALINIJA.y - BRZINA > 0:
DESNALINIJA.y -= BRZINA
if tasteri_kretanja[pygame.K_DOWN] and DESNALINIJA.y + BRZINA + LEVALINIJA.height < height:
DESNALINIJA.y += BRZINA
def glavnica():
clock = pygame.time.Clock()
running = True
while running:
global LOPTICA
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
LOPTICA = LOPTICA.move(BRZINA_LOPTICE)
if LOPTICA.left < 0 or LOPTICA.right > width:
##what i should put here ?
if LOPTICA.top < 0 or LOPTICA.bottom > height:
BRZINA_LOPTICE[1] = -BRZINA_LOPTICE[1]
if LOPTICA.colliderect(LEVALINIJA):
BRZINA_LOPTICE[0] = abs(BRZINA_LOPTICE[0])
if LOPTICA.colliderect(DESNALINIJA):
BRZINA_LOPTICE[0] = -abs(BRZINA_LOPTICE[0])
prikaz_pozadine()
kretanje_linija(LEVALINIJA, DESNALINIJA)
if __name__ == "__main__":
glavnica()`
Just set the initial position of the rectangle:
Note, a
pygame.Rectaddresses the top left corner of the rectangle. If you assign a tuple with 2 coordinates totopleft, the rectangle will be modified so that the top left corner is at that position.