Add GameObject and its derived classes. Create main game loop.

This commit is contained in:
Emil Shanaty
2025-03-09 04:18:50 +03:00
parent 68782a7c6e
commit 2811b3f95d
6 changed files with 72 additions and 1 deletions
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
import pygame
class GameObject:
x = 0
y = 0
def __init__(self, image_path, x=0, y=0):
self.image = pygame.image.load(image_path)
self.rect = self.image.get_rect(topleft=(x,y))
self.set_position(x, y)
def draw(self, surface):
surface.blit(self.image, self.rect)
def set_position(self, x, y): # TODO: FIX CENTERING
self.rect.x = x - self.image.get_width() / 2
self.rect.y = y - self.image.get_height() / 2
self.x = x - self.image.get_width() / 2
self.y = y - self.image.get_width() / 2
def move(self, dx, dy):
self.set_position(self.rect.x + dx, self.rect.y + dy)
def set_size(self, width, height):
self.image = pygame.transform.scale(self.image, (width,height))
self.rect = self.image.get_rect(topleft=(self.x,self.y))
def scale_by(self, scale):
self.image = pygame.transform.scale(self.image, (self.image.get_width() * scale, self.image.get_height() * scale))
self.rect = self.image.get_rect(topleft=(self.x,self.y))
class Horse(GameObject):
def __init__(self, image_path, x, y):
super().__init__(image_path, x, y)
class Background(GameObject):
def __init__(self, image_path, x, y):
super().__init__(image_path, x, y)
class Barrier(GameObject):
def __init__(self, image_path, x, y):
super().__init__(image_path, x, y)
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

+34 -1
View File
@@ -1 +1,34 @@
print("Hello world")
import pygame
import sys
from gameobjects import *
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("NIC_Project")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
grass = Background("images/grass.jpg", WIDTH/2, HEIGHT/2)
horse1 = Horse("images/horse.png",50, 50)
barrier1 = Barrier("images/barrier.png", 400, 300)
horse1.set_size(75, 75)
grass.set_size(WIDTH, HEIGHT)
gameobjects = [grass, horse1, barrier1]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
for object in gameobjects:
object.draw(screen)
pygame.display.flip()
pygame.time.Clock().tick(60)