0

This is the boiler plate code from a course that I am doing and when I run this, this error is showing up

C:\Users\Tanish\Desktop\Coding\cs50 ai>"C:/Program Files/Python39/python.exe" 
"c:/Users/Tanish/Desktop/Coding/cs50 ai/tictactoe/runner.py"
pygame 2.0.1 (SDL 2.0.14, Python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last)

 File "c:\Users\Tanish\Desktop\Coding\cs50 ai\tictactoe\runner.py", line 18, in <module>
mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28)
FileNotFoundError: [Errno 2] No such file or directory: 'OpenSans-Regular.ttf'

Although I have the font .ttf file in the same directory.

code:

import pygame
import sys
import time

import pygame

import tictactoe as ttt

pygame.init()
size = width, height = 600, 400

# Colors
black = (0, 0, 0)
white = (255, 255, 255)

screen = pygame.display.set_mode(size)

mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28)
largeFont = pygame.font.Font("OpenSans-Regular.ttf", 40)
moveFont = pygame.font.Font("OpenSans-Regular.ttf", 60)

directory: folder image

1 Answers1

1

This is due to where you are running the file from.

Currently you are running it from C:\Users\Tanish\Desktop\Coding\cs50 ai. However, your .tff file is in c:/Users/Tanish/Desktop/Coding/cs50 ai/tictactoe/.

In pygame.font.Font("OpenSans-Regular.ttf", 28), you are telling the program to open the file from your current directory which of course does not exist.

A solution is to find the absolute path of your files:

import os, sys

ttf_path = os.path.join(sys.path[0], "OpenSans-Regular.ttf")
pygame.font.Font(ttf_path, 28)

Alternatively, you can run the code from inside tictactoe/ directory.

drum
  • 5,416
  • 7
  • 57
  • 91