How To Import Pygame in Visual Studio Code

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 Python

Download and install Python from python.org/downloads with default configurations.

Download Python
Head over to python.org/downloads. Then, download and install Python.

Installing Pygame

To install Pygame through VS Code, follow these steps:

  1. From the top-level “View” menu, select Terminal. Alternatively, you can press Ctrl + ‘.

    Terminal
    From the View menu, select the Terminal option.
  2. Inside the terminal, enter and run the following command to install Pygame:
    pip install pygame

    Install Pygame
    Run the “pip install pygame” command in the VS Code terminal.

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:

    1. 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.

      Open Folder
      Create and open a project folder in your preferred directory.
    2. Click on the New File button next to the project folder heading.

      New File
      Click on the New File button.
    3. Give a name to the file and add .py as an extension. I’m going to call it “app.py”

      Filename
      Enter a filename with .py as an extension.
    4. To import Pygame, type the following command in the code editor:
      import pygame
    5. 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()

      Pygame Code
      Enter the given code in the code editor to print Hello World.
    6. To launch the application, click on the Run Code button in the top-right corner of VS Code.

      Run
      Left-click on the Run Code button.

Voilà! We’ve successfully imported and created our first Pygame application in VS Code.

Output
This is our output.

Was this article helpful?

Leave a Comment