Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] boilerplate
#1
Boilerplate is the basic code you need in order for something to work.  The bare minimum, with a little added on top to help you understand how to use it.  Anytime you start a new script, boilerplate code is what you start with, and you make your modifications based upon that.

Here's my version of pygame boilerplate.  There's some setup and teardown, and also a basic surface is added to demonstrate how drawing works, and how to blit things to the screen.

import pygame

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# initialize pygame
pygame.init()
screen_size = (700, 500)

# create a window
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("pygame Test")

# clock is used to set a max fps
clock = pygame.time.Clock()

# create a demo surface, and draw a red line diagonally across it
surface_size = (25, 45)
test_surface = pygame.Surface(surface_size)
test_surface.fill(WHITE)
pygame.draw.aaline(test_surface, RED, (0, surface_size[1]), (surface_size[0], 0))

running = True
while running:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = False
	
	#clear the screen
	screen.fill(BLACK)
	
	# draw to the screen
	# YOUR CODE HERE
	x = (screen_size[0]/2) - (surface_size[0]/2)
	y = (screen_size[1]/2) - (surface_size[1]/2)
	screen.blit(test_surface, (x, y))

	# flip() updates the screen to make our changes visible
	pygame.display.flip()
	
	# how many updates per second
	clock.tick(60)

pygame.quit()
If you run it, you'll see this (click for full size):     
It's dangerous to go alone!  Take this: https://docs.python.org/3/library/index.html
HackerRank seems neat: https://www.hackerrank.com/nilamo
Quote
#2
One thing that I like do right off the bat is put the mainloop in a "main()" function, so that I can just return out of the function.
Running Manjaro Linux 16.08/OpenRC/i3wm on a Dell Precision 5510.

John 3:17
Quote
#3
Agreed. Once you start making something that is in any way complicated, the main loop should at least be a function, or even a collection of objects.
It's dangerous to go alone!  Take this: https://docs.python.org/3/library/index.html
HackerRank seems neat: https://www.hackerrank.com/nilamo
Quote
#4
Here how I handle it
scene.py
import pygame_sdl2 as pygame

# internal working of my scene.
class Scene(object):
    # scene loading before seen
    def has_focus(self): pass
    # scene dumping before switching
    def lost_focus(self): pass
    # scene drawing
    def blit(self, surface): pass
    # scene time updates
    def update(self, tick): pass
    # scene events
    def event(self, event): pass

# scene switching
class Handler(object):
    # for passing variables without passing object
    scenes = {}
    fps = None
    running = False
    set_scene = None
    size = None

    # set caption and window
    def __init__(self, caption, size, flags=0, depth=0):
        Handler.size = size
        self.current_scene = Scene()
        self.screen = pygame.display.set_mode(size, flags, depth)
        pygame.display.set_caption(caption)
        self.clock = pygame.time.Clock()

    # main loop
    def loop(self, start_scene=None, fps=60):
        Handler.fps = fps
        Handler.running = True
        Handler.set_scene = start_scene

        while Handler.running:
            if Handler.set_scene:
                self.current_scene.lost_focus()
                self.current_scene = Handler.scenes[Handler.set_scene]
                self.current_scene.has_focus()
                Handler.set_scene = None

            for event in pygame.event.get():
                self.current_scene.event(event)

            self.current_scene.blit(self.screen)
            tick = pygame.time.get_ticks()
            self.current_scene.update(tick)

            pygame.display.flip()
            self.clock.tick(Handler.fps)

# function for quick access to variables.
def add_scene(scene_name, scene):
    Handler.scenes[scene_name] = scene

def set_scene(scene_name):
    Handler.set_scene = scene_name

def quit_scene():
    Handler.running = False

def get_screensize():
    return Handler.size

def set_fps(fps):
    Handler.fps = fps
I just import my boilerplate
example.py
import pygame_sdl2 as pygame
import scene

pygame.init()

class Example(scene.Scene):
    def __init__(self):
        scene.Scene.__init__(self)
        # scene variables here

    def blit(self, surface):
        surface.fill((0,0,120))
        # draw code here

    def event(self, event):
        # event code here
        if event.type == pygame.QUIT:
            scene.quit_scene()

if __name__ == '__main__':
    handler = scene.Handler('Example', (800,600))
    E = Example()
    scene.add_scene('Example', E)
    handler.loop('Example')

    pygame.quit()
Quote
#5
bolerplate code would depend on each person and how far they are into the learning process. For example, this is mostly my boiler plate code when i start a new game (minus the movie)

https://github.com/Mekire/pygame-mutisce...with-movie

Also you should use pygame rects instead. This will help tremendously as your game gets more and more complex the more you add. As you can see it is much easier to read and understand. This is an example of your post modified to such that. 
import pygame
 
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
 
# initialize pygame
pygame.init()
screen_size = (700, 500)
 
# create a window
screen = pygame.display.set_mode(screen_size)
screen_rect = screen.get_rect()
pygame.display.set_caption("pygame Test")
 
# clock is used to set a max fps
clock = pygame.time.Clock()
 
# create a demo surface, and draw a red line diagonally across it
#surface_size = (25, 45)
test_surface = pygame.Surface([25,45])
test_surface_rect = test_surface.get_rect(center=screen_rect.center)
test_surface.fill(WHITE)

 
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
     
    #clear the screen
    screen.fill(BLACK)
     
    # draw to the screen
    # YOUR CODE HERE
    #x = (screen_size[0]/2) - (surface_size[0]/2)
    #y = (screen_size[1]/2) - (surface_size[1]/2)
    #screen.blit(test_surface, (x, y))
    screen.blit(test_surface, test_surface_rect)
    pygame.draw.aaline(screen, RED, test_surface_rect.bottomleft, test_surface_rect.topright)
 
    # flip() updates the screen to make our changes visible
    pygame.display.flip()
     
    # how many updates per second
    clock.tick(60)
 
pygame.quit()

*Describe the environment in which it occurs.                                    *Describe the symptoms of your problem clearly.
*Describe the research you did to try and understand the problem.      *Describe the goal, not the step. 
*Use meaningful, specific subject headers                                          *Write in clear, grammatical, correctly-spelled language
*Describe the problem's symptoms, not your guesses                         *Describe your problem's symptoms in chronological order
*Describe the diagnostic steps you took to try and pin down the problem yourself.
*Describe any possibly relevant recent changes in your computer or software configuration. 
*Provide a way to reproduce the problem in a controlled environment.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)