Search code examples
pythonpygame

The 'flag' appears only when the first turtle touches the finish line


[[[enter image description here](https://i.sstatic.net/694bC.png)](https://i.sstatic.net/1jiZh.png)](https://i.sstatic.net/OG6D7.png)

The 'flag' which called 'win' appears only when the first turtle touches the finish line. Let's say when the 2nd turtle win, It still doesn't count it as a win, it waits for 1st turtle to touch the finish line. I tried fixing It, but I could't do that. So, If the 1st turtle touches the finish line, the 'flag' which is called 'win' should appear in front of the 1st turtle. And same for 2nd and 3rd turtles. But even if 2nd or 3rd turtle win, still the programe ends when the 1st turtle touches the finish line. I will be so gratefull if you help me. If you didn't understand something, you can write me and can explain it to you!

import pygame
from random import randint

pygame.init()
clock = pygame.time.Clock()
sc = pygame.display.set_mode((400, 350))
pl = pygame.image.load('pl.png')
t = pygame.image.load('tr.png')
win = pygame.image.load('win.png')
finish = pygame.image.load('finish.png')
r_f = pygame.Rect(360, 60, 60, 60)
x1 = x2 = x3 = 0
winner = 0

while winner == 0:
    sc.blit(pl, (0, 0))
    sc.blit(finish, r_f)

    r_t1 = pygame.Rect(x1, 64, 60, 60)
    r_t2 = pygame.Rect(x2, 160, 60, 60)
    r_t3 = pygame.Rect(x3, 240, 60, 60)

    sc.blit(t, r_t1)
    sc.blit(t, r_t2)
    sc.blit(t, r_t3)

    x1 = x1 + randint(0,3)
    x2 = x2 + randint(0,3)
    x3 = x3 + randint(0,3)
    
    if r_t1.colliderect(r_f):
        winner = 1
        sc.blit(win, (300, 20))
    if r_t2.colliderect(r_f):
        winner = 1
        sc.blit(win, (300, 100))
    if r_t3.colliderect(r_f):
        winner = 1
        sc.blit(win, (300, 200))

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

I tried fixing It, but I could't do that. So, If the 1st turtle touches the finish line, the 'flag' which is called 'win' should appear in front of the 1st turtle. And same for 2nd and 3rd turtles. But even if 2nd or 3rd turtle win, still the programe ends when the 1st turtle touches the finish line.


Solution

  • The problem is with your defined area for r_f. You only made the finish line area 60 pixels tall, so only r_t1 can ever collide with it.

    Try changing the rectangle for r_f to something like:

    r_f = pygame.Rect(360, 54, 10, 200)
    

    You can also use the size of the .png image to programmatically set it's position and the rectangle size as follows:

    finish = pygame.image.load('finish.png')
    finish_w, finish_h = finish.get_size()
    r_f = pygame.Rect(360, (350 - finish_h)//2, finish_w, finish_h)
    

    or if you want to manually adjust the y position, you could just use:

    r_f = pygame.Rect(360, 54, *finish.get_size())