How to use Snippets in Sublime Text for Python or Pygame

Snippets are pieces of code that you can save and re-use.

You can save a lot of time, not writing always the same code to initialize stuff like, for example, in pygame. Who wants to write every time the code for the screen, clock, quit button etc.? Let’s see how to do it.

How to make it in Sublime text

You can do it in sublime text going into:

  • tools / developers / snippets

 

You will find this

<snippet>
	<content><![CDATA[
Hello, ${1:this} is a ${2:snippet}.
]]></content>
	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
	<!-- <tabTrigger>hello</tabTrigger> -->
	<!-- Optional: Set a scope to limit where the snippet will trigger -->
	<!-- <scope>source.python</scope> -->
</snippet>

This is a template of a snippet, you can do a snippet for pygame like this:

Here is an example of a snippet to use it in python files

<snippet>
	<content><![CDATA[
import pygame


size = w, h = ${1:400}, ${2:500}
screen = pygame.display.set_mode((size))
pygame.display.set_caption("${3:Window title}")


def main():
    pygame.init()
    pygame.font.init()
    clock = pygame.time.Clock()
    loop = 1
    while loop:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = 0
        pygame.display.update()
        clock.tick(60)

    pygame.quit()


main()



]]></content>
	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
	<tabTrigger>pygame</tabTrigger>
	<!-- Optional: Set a scope to limit where the snippet will trigger -->
	<scope>source.python</scope>
</snippet>

Hit the tabtrigger keyword and go

So, once, you crate an empty (or not) python file, if you digit ‘pygame’ and then you press the ‘tab’ key you will magically have this:

import pygame


size = w, h = 400, 500
screen = pygame.display.set_mode((size))


def main():
    pygame.init()
    pygame.font.init()
    clock = pygame.time.Clock()
    loop = 1
    while loop:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = 0
        pygame.display.update()
        clock.tick(60)

    pygame.quit()


main()

and it’s not all, if you press the ‘tab’ again, the selection will automatically go on the words that you highlighted in the snippet script with the ${1:text}… so that you can customize those stuff for your needs, like the dimention of the window that can be different for every game you want to make.

Video on the creation of snippets on Sublime text


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.