Pygame Loading fonts from external font file - python

I am trying to load a .woff formatted font file into my pygame. I have seen other posts talking about this issue, but their answers do not help answer my question. I tried using this:
fontObj = py.font.Font('brandon_blk-webfont.woff', 16)
textSurfaceObj = fontObj.render(self.fact, True, black, None)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (x * 1.5, y * 1.5)
gameDisplay.blit(textSurfaceObj, textRectObj)
Here is my error:
Traceback (most recent call last):
File "C:\Users\Sruthi\Desktop\Python\Pygame\Memorization Game\main.py", line 111, in <module>
gameLoop()
File "C:\Users\Sruthi\Desktop\Python\Pygame\Memorization Game\main.py", line 108, in gameLoop
create_button(mouse, 50, 50)
File "C:\Users\Sruthi\Desktop\Python\Pygame\Memorization Game\main.py", line 84, in create_button
fontObj = py.font.Font('Memorization Game/brandon_blk-webfont.woff', 16)
OSError: unable to read font file 'Memorization Game/brandon_blk-webfont.woff'
I have placed this font file in my current python file directory as you can see in this picture:
Shows that the font files are in the same directory
Also I know the font file isn't corrupted as I have seen a problem can be.

The first step to ensuring this isn't a corrupted font or windows compatibility issue would be to convert woff to ttf and attempt got get pygame to load that file. I went to this site: https://everythingfonts.com/woff-to-ttf and I tested it with my own woff font and it works just the same with ttf. I'm on Linux and my font/code worked for me.
I'll paste my font-loading code for you so you can test with that just in case.
Please let me know if things are still not working. If so, post your Windows + python versions so I can reproduce.
import pygame, sys, os
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400, 300))
# font-related code:
fpsClock = pygame.time.Clock()
# https://www.behance.net/gallery/31268855/Determination-Better-Undertale-Font
font = pygame.font.Font(os.path.join("res", "fonts", 'DeterminationMonoWeb.ttf'), 16)
screen.blit(font.render(text, 0, (255, 240, 230)), (10, 10))
pygame.display.flip()
# Main game loop
while True:
if pygame.event.wait().type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
break
pygame.display.update()
fpsClock.tick(60)

Related

NotImplementedError: font module not available PyGame Mac

In this code, I referenced the font, and python show me this problem.
I've seen other people have a similar problem, but nothing helped me. I understand that the problem is in the path to the file on line 12, but I don't know how to solve it.
Python - 64 bit,
pyGame - 64 bit,
macOS Mojave.
My error and my code:
Traceback (most recent call last):
File "/Users/lewstefanevskij/Desktop/TER/main.py", line 12, in <module>
myfont = pygame.font.Font('fonts/Roboto-Black.ttf',40)
^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pygame/__init__.py", line 70, in __getattr__
raise NotImplementedError(missing_msg)
NotImplementedError: font module not available (ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pygame/font.cpython-311-darwin.so, 2): Library not loaded: #loader_path/libfreetype.6.dylib
Referenced from: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pygame/.dylibs/libfreetype.6.dylib
Reason: image not found)
import pygame
pygame.init() # ініціалізація
screen = pygame.display.set_mode((600,300)) # розмір вікна
pygame.display.set_caption('GTA 5') # назва вікна
icon = pygame.image.load('images/icon.png') #завантаження фотки
pygame.display.set_icon(icon) # встановлення фотки
square = pygame.Surface((50,170)) # параметри квадрата
square.fill('Blue') # колір квадрата
myfont = pygame.font.Font('fonts/Roboto-Black.ttf',40)
text_surface = myfont.render('Lev',False,'Yellow',)
running = True
while running:
pygame.draw.circle(square,'Red',(10,17),10)
screen.blit(square,(200,100)) #створюєм квадрат
screen.blit(text_surface,(100,100))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()w
I tried reinstalling python, Sysfont, match_font and downloading python local.
I uninstalled python 3.11 and pygame 2.1.3, then installed python 3.8.5 and pygame 2.1.2.

I cannot get my Python (Pygame) code to get an image which is in the folder

I am using pygame and trying to display an image, however it keeps saying the following:
Exception has occurred: FileNotFoundError
No file 'images/vita_00.png' found in working directory 'C:\WINDOWS\System32\WindowsPowerShell\v1.0'. File "C:\Programing\Coding\Python\Python3\Tutorial\Developing a Platformer [Rik Cross]\platformer\platformer.py", line 17, in player_image = pygame.image.load('images/vita_00.png') FileNotFoundError: No file 'images/vita_00.png' found in working directory 'C:\WINDOWS\System32\WindowsPowerShell\v1.0'.
The file is in the same folder, I am following a tutorial which the link is: https://www.youtube.com/watch?v=kVj8-O4MUlQ&list=PLQaniv5ve2yhfYck8nsgU1bw_8bFDSs3h&index=2
The code I am working with is :
import pygame
# constant variables
SCREEN_SIZE = (700, 500)
DARK_GREY = (50, 50, 50)
# init
pygame.init()
screen = pygame.display.set_mode((SCREEN_SIZE))
pygame.display.set_caption('My Platformer')
# player
player_image = pygame.image.load('images/vita_00.png')
running = True
while running:
# game loop
# input
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
running = False
# update
# draw
screen.fill((DARK_GREY))
screen.blit(player_image, (0, 0))
pygame.display.flip()
# quit
pygame.quit()
I really do not understand what I am doing wrong, yes I am very new to python and coding its self.
I do also keep getting this message when running my program in the terminal: cd :
Cannot find path 'c:\Programing\Coding\Python\Python3\Tutorial\Developing a Platformer [Rik Cross]\platformer' because it does not exist.
At line:1 char:6
c:; cd 'c:\Programing\Coding\Python\Python3\Tutorial\Developing a Pl ...
CategoryInfo : ObjectNotFound: (c:\Programing\C...oss]\platformer:String) [Set-Location], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
Can someone please help me.
Thanks
I have tried the full file directory with no results.
Welcome to Python! For your script to work, you should be running it in the same directory where /images is. Needless to say, make sure that the name (including the png extension!) match what's in the script.
In addition, it looks like in the tutorial they're using some Linux distribution, which generally knows how to handle folder names with spaces. On Windows, on the other hand, you need to be careful about escaping spaces. Try renaming your directories (particularly Developing a Platformer [Rik Cross]) to names without spaces and see if that helps.

Continuous errors occurring while trying to run a file importing pygame on VS Code

I have been struggling for the past few hours on what I should do, and finally decided to resort to asking on StackOverflow.
PROBLEM: I keep getting terminal traceback calls but I have no idea what I should do about them. I will admit, it is probably me being stupid and not knowing what is happening, but it was my first time on VSCode and importing stuff. When I googled at first, I couldn’t get any answers.
CODE (I have a second file with dvd-image.png):
import pygame, time
pygame.init()
width, height = 800, 600
dvdLogoSpeed = [1, 1]
backgroundColor = 0, 0, 0
screen = pygame.display.set_mode((width, height))
dvdLogo = pygame.image.load("dvd-image.png")
dvdLogoRect = dvdLogo.get_rect()
while True:
screen.fill(backgroundColor)
screen.blit(dvdLogo, dvdLogoRect)
dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed)
if dvdLogoRect.left < 0 or dvdLogoRect.right > width:
dvdLogoSpeed[0] = -dvdLogoSpeed[0]
if dvdLogoRect.top < 0 or dvdLogoRect.bottom > height:
dvdLogoSpeed[1] = -dvdLogoSpeed[1]
pygame.display.flip()
time.sleep(10 / 1000)
TRACEBACK CALLS:
Traceback (most recent call last):
File "/Users/xxx/Desktop/untitled101/pygame.py", line 1, in
import pygame
File "/Users/xxx/Desktop/untitled101/pygame.py", line 3, in
pygame.init()
AttributeError: partially initialized module 'pygame' has no attribute 'init' (most likely due to a circular import)
EXTRA INFORMATION:
Device: MacBook Air
Chip: M1
VSCode Download: Universal
Coder: Knows nothing good about tracebacks
pygame is a Python package and you have your own project named "pygame".
Pylance will recognize your project as the pygame package.
You can change your projcet name to solve it.

How to change to get python to read images inside multiple folders

I'm trying to display an image in python, and whenever I try, I've gotten this error:
Traceback (most recent call last):
File "C:/Users/Brandon/PycharmProjects/UnstableUnicorns/UnstableUnicorns Test.py", line 15, in <module>
BabyNarwhal = pygame.image.load(r'CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png').convert()
pygame.error: Couldn't open CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png
I agree that the image path is a little convoluted, but I can't seem to find a way to get it to load the file. I've tried putting in the whole file path, I've tried to change the read location, but I can't seem to be able to load this image. I really don't want to have to put the images in the same folder as the code since there are a lot of different images I want to display. Here's my code:
import pygame
pygame.init()
xDisplay = 1000
yDisplay = 500
white = (255, 255, 255)
BabyNarwhal = pygame.image.load(r'CardImages\BasicDeck\BabyUnicorns\Baby Narwhal.png').convert()
def main():
display = pygame.display.set_mode((xDisplay, yDisplay))
while True:
display.fill(white)
display.blit(BabyNarwhal, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
main()
and here is the full image path:
C:\Users\Brandon\PycharmProjects\UnstableUnicorns\CardImages\BasicDeck\BabyUnicorns
Using spaces in a filename isn't recommended. And using '/' instead of '\' can resolve the error.
So, you should rename your image without spaces, and use :
babynarwhal_img = pygame.image.load(CardImages/BasicDeck/BabyUnicorns/BabyNarwhal.png).convert()
Note : modified the variable name because of the folder with the same name, can cause problems on certains versions.

Attempting to embed a video in pygame using pyglet

im trying to display a video on a pygame surface using the pyglet library to import, play and then convert the frames into an image. I managed to battle my way through installing avbin but now I'm hitting a type error with my code
def cutscene(window_surface, filename):
player = pyglet.media.Player()
source = pyglet.media.load(filename)
player.queue(source)
player.play()
pygame.display.flip()
while True:
window_surface.fill(0)
player.dispatch_events()
tex = player.get_texture()
raw = tex.get_image_data().get_data('RGBA',tex.width*4)
raw = ctypes.string_at(ctypes.addressof(raw), ctypes.sizeof(raw))
img = pygame.image.frombuffer(raw, (tex.width, tex.height), 'RGBA')
window_surface.blit(img, (0,0))
pygame.display.flip()
when I run, i get the following error
Traceback (most recent call last):
File "dino_game.py", line 348, in <module>
main()
File "dino_game.py", line 45, in main
cutscene(window_surface, "Cutscenes/Cutscene1.mov")
File "dino_game.py", line 68, in cutscene
raw = tex.get_image_data().get_data('RGBA',tex.width*4)
AttributeError: 'NoneType' object has no attribute 'get_image_data'
Nothing that I do seems to solve it
EDIT: So after testing both this file and the sample files provided by pyglet, it seems that I get this error no matter what filetype I use, could this be an installation error with pyglet or AVbin?
Gave up trying to use pyglet and swapped to VLC where I just have to pass the window ID for the game and it does the rest for me
VLC script: https://wiki.videolan.org/Python_bindings/

Categories

Resources