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.
Step 1: Download Python
Download and install Python from python.org/downloads with default configurations.
Step 2: Install Pygame
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
Step 3: Create a new Pygame project
After installing the Pygame library, we must import all functions from it. We use the “import” keyword to import a library.
For this example, let us create a simple Pygame application that displays Hello World on the screen. Follow the steps below:
- 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 name 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 the Run Code button on the top-right corner of the code console.
Voilà! We’ve successfully imported and created our first Pygame application in VS Code.