Pygame is a library that helps us create games using Python. Pygame uses SDL (short for Simple DirectMedia Layer) which helps us get access to the keyboard, mouse, and graphics. Pygame runs on almost every platform. This guide shows you how to import Pygame in Visual Studio Code.
Download and install Python from python.org/downloads with default configurations.
To install Pygame through VS Code, follow these steps:
- From the top-level “View” menu, select Terminal. Alternatively, you can press Ctrl + ‘.
- Inside the terminal, enter and run the following command to install Pygame:
pip install pygame
Creating A Pygame Project
After installing the Pygame library, we need to import all functions from it. We use the “import” keyword to import a library. Let us create a simple Pygame application that displays Hello World on the screen. Follow the below steps:
- Click on the Open Folder button from the “Explorer” tab. Then, open or create a folder from your preferred directory. In my case, I’m creating a folder named “Test,” which will be saved on my Desktop.
- Click on the New File button next to the project folder heading.
- Give a name to the file and add .py as an extension. I’m going to call it “app.py”
- To import Pygame, type the following command in the code editor:
- Here is the entire code to print Hello World:
import pygame #initialising pygame pygame.init() #defining size of game window windowsSize = pygame.display.set_mode((800,600)) pygame.display.set_caption("Hello World Printer") #defining font attributes myFont = pygame.font.SysFont("Segoe UI", 90) helloWorld = myFont.render("Hello World", 1, (255, 0, 255), (255, 255, 255)) while 1: for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() windowsSize.blit(helloWorld, (0, 0)) pygame.display.update()
- To launch the application, click on the Run Code button in the top-right corner of VS Code.
Voilà! We’ve successfully imported and created our first Pygame application in VS Code.