Add collision and horse stopping on collision. Start implementing flags functionality

This commit is contained in:
Emil Shanaty
2025-03-15 05:11:44 +03:00
parent f156a35da9
commit ded99fca0c
4 changed files with 163 additions and 117 deletions
Binary file not shown.
Binary file not shown.
+33 -1
View File
@@ -1,4 +1,6 @@
import pygame
import random
class GameObject:
x = 0
y = 0
@@ -27,13 +29,18 @@ class GameObject:
class Horse(GameObject):
default_vacceleration = 1
default_vacceleration = 0.5
vspeed = 0
vacceleration = 0
stopped = False
color = ()
def __init__(self, image_path, x, y):
self.vspeed = 0
self.vacceleration = 0
self.stopped = False
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
super().__init__(image_path, x, y)
self.set_size(75, 75)
def apply_vspeed(self):
pos = self.get_position()
self.set_position(pos[0], pos[1] + self.vspeed)
@@ -51,6 +58,10 @@ class Horse(GameObject):
self.set_vacceleration(self.default_vacceleration)
def stay(self):
self.set_vacceleration(0)
def stop(self):
self.stopped = True
self.set_vacceleration(0)
self.set_vspeed(0)
@@ -63,3 +74,24 @@ class Barrier(GameObject):
def __init__(self, image_path, x, y):
super().__init__(image_path, x, y)
class UI:
children = []
horizontal_offset = 25
mark_size = 5
def __init__(self):
self.children = []
def add_children(self, children):
new_children = [child for child in children if child not in self.children]
self.children.extend(new_children)
def draw_marks(self, screen):
x0 = 50
y0 = 300
for child in self.children:
if isinstance(child, Horse):
x0 += self.horizontal_offset
x1 = x0 + self.mark_size
y1 = y0 - self.mark_size
pygame.draw.rect(screen, child.color, (x0, y0, x1, y1))
+16 -2
View File
@@ -10,18 +10,20 @@ pygame.display.set_caption("NIC_Project")
WHITE = (255, 255, 255)
UI = UI()
grass = Background("images/grass.jpg", 0, 0)
horse1 = Horse("images/horse.png", 50, 50)
barrier1 = Barrier("images/barrier.png", 400, 300)
BARRIER_SPEED = 1
horse1.set_size(75, 75)
grass.set_size(WIDTH, HEIGHT)
gameobjects = [grass, horse1, barrier1]
horses = [horse1]
horses = [Horse("images/horse.png", 50, 50) for i in range(5)]
barriers = [barrier1]
UI.add_children(horses)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
@@ -31,12 +33,15 @@ while True:
keys = pygame.key.get_pressed()
for horse in horses:
if horse.stopped == False:
if keys[pygame.K_UP]:
horse.up()
elif keys[pygame.K_DOWN]:
horse.down()
else:
horse.stay()
else:
horse.move(-BARRIER_SPEED, 0)
horse.apply_vacceleration()
horse.apply_vspeed()
@@ -45,8 +50,17 @@ while True:
for barrier in barriers:
barrier.move(-BARRIER_SPEED, 0)
# Checking collisions between horses and barriers
for horse in horses:
if horse.stopped == False:
for barrier in barriers:
if horse.rect.colliderect(barrier.rect):
horse.stop()
for object in gameobjects:
object.draw(screen)
UI.draw_marks(screen)
pygame.display.flip()
pygame.time.Clock().tick(60)