So I have this Pygame 3.3.2 code of 2 classes. I tried to make it as simpler as possible, but ofcourse to show the problems I have with thedesign.
import pygame
import sys
class MainWindow(object):
''' Handles main surface '''
def __init__(self, width, height):
self.WIDTH = width
self.HEIGHT = height
self.SURFACE = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Placeholder')
self.draw_rect = DrawRect(self) # <-- this line looks really strange to me
def update(self):
pygame.display.update()
class DrawRect(object):
''' Draw rect on the surface '''
def __init__(self, window):
self.window = window
self.my_rect = pygame.Rect((50, 50), (50, 50))
def update(self):
pygame.draw.rect(self.window.SURFACE, (0, 0, 255), self.my_rect)
def main():
pygame.init()
Window = MainWindow(900, 500)
Draw = DrawRect(Window)
Window.draw_rect.update() # <-- this looks very missleading to me
Window.update()
main()
According to StackOverflow question -
If B
want to expose the complete interface of A
- Indicates Inheritance
.
If B
want to expose only some part of A
- Indicates Composition
.
I don't need all of the content of the MainWindow
so I use composition.
The naming conventions and specialy the line Window.draw_rect.update()
in the main()
function.
Later on, I will use a class Player
, do I need to put something like self.player = Player(self)
, inside the MainWindow __init__
method?
Let's say I want to use the width, height
of the window to perform some method for positioning the Player.
Is there a better way to write this code, to look profesional and clear?