I am currently making a small game but it is showing a strange error message. Namely:
'Pygame Error': Font Not Initialized
What does this mean?
This is my code:
import pygame, random, sys, os, time
import sys
from pygame.locals import *
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
levens = 3
dead = False
Mousevisible = False
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: #escape quits
terminate()
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#fonts
font = pygame.font.SysFont(None, 30)
#def gameover():
#if dead == True:
#pygame.quit
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('hit the blocks')
pygame.mouse.set_visible(Mousevisible)
# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
And this is the error:
Traceback (most recent call last):
File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\schietspel.py", line 30, in <module>
font = pygame.font.SysFont(None, 30)
File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 320, in SysFont
return constructor(fontname, size, set_bold, set_italic)
File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 243, in font_constructor
font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized
The problem is that you're setting the font before initializing the game. To fix this, move font = pygame.font.SysFont(None, 30) after pygame.init().
Also, for your code to work, you'll need to define TEXTCOLOR as well. It should be a tuple with RGB values eg. TEXTCOLOR = (255, 255, 255) for white (you can put it at the top with the WINDOWHEIGHT).
I think you have to initialize pygame.font.
Try pygame.font.init() after from pygame.locals import *
For me, adding pygame.init() before pygame.font.Font() fixed the problem.
Related
I have the problem with pygame. Specifically, I stuck on how to resize the text proportionally to the window (window is re-sizable and with picture).
Here is my code.
import pygame
from pygame.locals import *
import numpy as np
import matplotlib.pyplot as plt
import argparse
import threading, os, sys, time
pygame.init()
pygame.display.set_caption("AI Battlehip Game")
FPS = pygame.time.Clock()
red = (255,0,0)
screen = pygame.display.set_mode((1200,700), HWSURFACE|DOUBLEBUF|RESIZABLE)
add_screen = screen.copy()
back_end_image_set = pygame.image.load(r'/Users/User1/Desktop/Project work/images/backgroundimage1.jpg')
screen.blit(pygame.transform.scale(back_end_image_set, (1200,700)), (0,0))
pygame.display.flip()
myFont = pygame.font.SysFont("monospace", 300)
label = myFont.render("Check 1", 40, (red))
add_screen.blit(pygame.transform.scale(label, (700, 500)), (0,0))
FPS.tick(60)
try:
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(event.dict['size'], HWSURFACE|DOUBLEBUF|RESIZABLE)
screen.blit(pygame.transform.scale(back_end_image_set, event.dict['size']), (0,0))
pygame.display.flip()
except:
raise
Any help will be fully appreciated.
First store the original size of the surface:
original_size = (1200,700)
screen = pygame.display.set_mode(original_size, HWSURFACE|DOUBLEBUF|RESIZABLE)
Then you've 2 options.
Option 1:
Use pygame.font and render the text to a surface:
myFont = pygame.font.SysFont("monospace", 300)
label = myFont.render("Check 1", 40, (red))
Scale the text surface by the ratio of the new window size and original window size and blit it to the surface:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(event.dict['size'], HWSURFACE|DOUBLEBUF|RESIZABLE)
new_size = event.dict['size']
screen.blit(pygame.transform.scale(back_end_image_set, new_size), (0,0))
label_w = label.get_width() * new_size[0] // original_size[0]
label_h = label.get_height() * new_size[1] // original_size[1]
screen.blit(pygame.transform.scale(label, (label_w, label_h)), (0,0))
pygame.display.flip()
Option 2:
Use pygame.freetype:
import pygame.freetype
myFont = pygame.freetype.SysFont('monospace', 30)
Calculate the scaled size of the text area and render it directly to the resized screen. Note the text is scaled by the ratio of the new window width and original window width.
This implementation keeps the ration of the width and height of the text and doesn't stretch or squeeze the text:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(event.dict['size'], HWSURFACE|DOUBLEBUF|RESIZABLE)
new_size = event.dict['size']
screen.blit(pygame.transform.scale(back_end_image_set, new_size), (0,0))
myFont.render_to(screen, (0, 0), "Check 1", fgcolor=red, size = 300 * new_size[0] // original_size[0])
pygame.display.flip()
I am working on a game and seem to be having some issues here. This is my first time working with sprite sheets, so I apologize if my error is simple.
I apologize in advance for the large amount of code, but unfortunately I believe the problem could be anywhere in this code. The error I am receiving says "TypeError: argument 1 must be pygame.Surface, not method
". This is referring to the all_sprites.draw(screen) command. I know screen is formatted correctly, so its not that. My teacher said it is likely any of the sprites. One of them is not formatted correctly, or doesn't properly interact with the images. Please let me know if you find the solution to my issue, and again I apologize for the large extent of the code.
Thanks!
(I labeled my different files btw, gsettings, gmain, and gsprites. You can see I use them in the imports, shouldn't be a big deal, just thought I would clarify)
FULL EXCEPTION `
Traceback (most recent call last):
File "/Users/AddisonWeatherhead/PycharmProjects/PyGame/Game 2/gmain.py", line 191, in <module>
game_play()
File "/Users/AddisonWeatherhead/PycharmProjects/PyGame/Game 2/gmain.py", line 128, in game_play
all_sprites.draw(screen)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pygame/sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
TypeError: argument 1 must be pygame.Surface, not method
Process finished with exit code 1
gsettings
WHITE = (255, 255, 255)
BLACK = (0, 0, 0,)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (180, 180, 180)
MAROON = (128, 0, 0)
NAVY = (0, 0, 128)
YELLOW = (255, 255, 0)
LIGHT_GRAY = (250, 250, 250)
LIGHT_BLUE = (144, 195, 212)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 800
FPS=60
gsprites
class sprite_sheet():
def __init__ (self, filename):
self.spritesheet = pygame.image.load(filename)
def get_image(self, x, y, width, height):
image = pygame.Surface((width, height))
image.blit(self.spritesheet, (0,0), (x, y, width, height))
return image
class Player(pygame.sprite.Sprite):
def __init__(self, hero_left_list, hero_right_list, left_shoot, right_shoot):
pygame.sprite.Sprite.__init__(self)
self.hero_left_list=hero_left_list
self.hero_right_list=hero_right_list
self.left_shoot=left_shoot
self.right_shoot=right_shoot
self.image = self.hero_right_list[0]
self.rect=self.image.get_rect()
self.rect.x=self.rect.x
self.rect.y=self.rect.y
self.changex=0 #Horizontal movement speed
self.changey=0 #Vertical movement speed
self.current_frame=0
self.delay=50 #In millisecond, this will be the delay BETWEEN each frame of a spritesheet (character walking, explosion exploding, etc)
self.last=pygame.time.get_ticks() #gets the time in milliseconds since pygame.init() was called
self.running_right=False
self.running_left=False
def update(self):
self.rect.x+=self.changex
self.rect.y+=self.changey
if pygame.key.get_pressed()[pygame.K_RIGHT]:
self.now=pygame.time.get_ticks() #also gets the time in milliseconds since pygame.init() was called, however this time its LATER than self.delay
self.running_right=True
self.changex=5
if self.now - self.last >self.delay: #Confirming that at least 5 milliseconds has passed since the last call of the function
self.last=self.now
self.current_frame=(self.current_frame+1)%(int(len(self.hero_right_list)))
self.image=self.hero_right_list[self.current_frame]
self.image=sprite_sheet("hero.png").get_image
elif pygame.key.get_pressed()[pygame.K_LEFT]:
self.running_left=True
self.changey=5
self.image=sprite_sheet.get_image("hero.png", )
elif pygame.key.get_pressed()[pygame.K_UP]:
self.running_left=False
self.running_right=False
self.image=sprite_sheet.get_image("hero.png")
gmain
import pygame
from gsettings import *
from gsprites import *
import time
pygame.init()
clock = pygame.time.Clock()
##########################################################################################
def score(score, lives):
background = sprite_sheet("background.jpg").get_image(0, 0, 800, 800)
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
screen.blit(background, [0,0])
font = pygame.font.SysFont('Impact', 40, True, False)
text = font.render(('Score'+str(score)), True, WHITE)
screen.blit(text, (200, 50))
##########################################################################################
def game_start():
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
text = "Press enter to play"
font = pygame.font.SysFont('Impact', 50, True, False)
text_render=font.render(text, True, BLACK)
background=sprite_sheet("background.jpg").get_image(0, 0, 800, 800)
screen.blit(background, [0, 0])
started=False
while started == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
quit()
sprite_sheet("background.jpg").get_image(0, 0, 800, 800)
screen.blit(text_render, [(DISPLAY_WIDTH / 2) - 150, (DISPLAY_HEIGHT / 2)])
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
screen.blit(background, [0, 0])
print('last')
return True
print(started)
pygame.display.flip()
clock.tick(FPS)
##########################################################################################
def game_play():
pygame.init()
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
hero_right_list = []
for x in range(6):
for y in range(2, 3):
right_image = sprite_sheet("hero.png").get_image(80 * x, 94 * y, 80, 94)
hero_right_list.append(right_image)
# Player is 80 wide 94 tall
hero_left_list = []
for image in hero_right_list:
hero_left_list.append(pygame.transform.flip(image, True, False))
explosion_list = []
for x in range(25):
for y in range(1, 2):
explosion_image = sprite_sheet("Explosion.png").get_image(192 * x, 195 * y, 192, 195)
explosion_list.append(explosion_image)
shoot_right=(sprite_sheet("hero.png").get_image(0, 94*3, 80, 94))
shoot_left=pygame.transform.flip(shoot_right, True, False)
#Creating Sprite groups
all_sprites=pygame.sprite.Group()
enemy_sprites=pygame.sprite.Group()
player_sprite=pygame.sprite.Group()
laser_sprites=pygame.sprite.Group()
explosion_sprite=pygame.sprite.Group()
#sprite objects
player=Player(hero_left_list, hero_right_list, shoot_left, shoot_right)
all_sprites.add(player)
player_sprite.add(player)
for val in range(10):
enemy_right=Enemy('right')
enemy_left=Enemy('left')
enemy_sprites.add(enemy_right)
enemy_sprites.add(enemy_left)
all_sprites.add(enemy_right)
all_sprites.add(enemy_left)
global game_score
game_score = 0
started=True
while started==True:
for event in pygame.event.get():
# events to end the game
if event.type == pygame.QUIT:
quit()
player.update()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
player.image=shoot_right
laser_hits=pygame.sprite.groupcollide(laser_sprites, enemy_sprites, True, True)
for hit in laser_hits:
game_score+=5
explosion=Explosion(explosion_list)
explosion_sprite.add(explosion)
all_sprites.add(explosion)
enemy=Enemy()
enemy_sprites.add(enemy)
all_sprites.add(enemy)
score(score, 5)
#enemy_sprites.draw(screen) #NO ISSUES
#explosion_sprite.draw(screen) #NO ISSUES
#laser_sprites.draw(screen) #NO ISSUES
player_sprite.draw(screen) #ISSUES
pygame.display.flip()
clock.tick(FPS)
##########################################################################################
def game_over(score):
over_screen=pygame.display.set_mode([DISPLAY_WIDTH, DISPLAY_HEIGHT])
clock.tick(FPS)
end_message_1="GAME OVER!"
end_message_2="Your score was", score
end_message_3="Replay"
end_message_4="Quit"
font = pygame.font.SysFont('Comic Sans', 75, True, False)
#rendering text
end_message_1_render=font.render(end_message_1, True, RED)
end_message_2_render=font.render(end_message_2, True, BLACK)
end_message_3_render=font.render(end_message_3, True, BLACK)
end_message_4_render=font.render(end_message_4, True, BLACK)
started=False
while started == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
clicked=pygame.mouse.get_pressed()
pos=pygame.mouse.get_pos()
if pos[0]>0 and pos[0]<100 and pos[1]>0 and pos[1]<100:
if pygame.mouse.get_pressed()[0] ==1:
started=False
over_screen.fill(WHITE)
over_screen.blit(end_message_1, [(DISPLAY_WIDTH//2), (DISPLAY_HEIGHT//2)])
over_screen.blit(end_message_2, ((DISPLAY_WIDTH//2), ((DISPLAY_HEIGHT//2)+50)))
over_screen.blit(end_message_3, [((DISPLAY_WIDTH // 2)-20), ((DISPLAY_HEIGHT // 2) + 120)])
over_screen.blit(end_message_4, [((DISPLAY_WIDTH // 2)+20), ((DISPLAY_HEIGHT // 2) + 120)])
pygame.display.flip()
pygame.time.clock.tick(FPS)
started=True
##########################################################################################
game_start()
while True:
game_play()
game_over(game_score)
pygame.quit()
On the line of the error, spr.image is a method, not a pygame.Surface, which is what's expected by surface_blit().
EDIT (in response to comments):
The error is on line 475 of sprite.py.
Just started a Python course at my school, and our first assignment requires us to write out text on multiple lines. I still cannot figure out how to do so with my code so if anyone could help, that'd be great. Code posted below.
import pygame, sys
from pygame.locals import *
pygame.init()
pygame.display.set_caption('font example')
size = [640, 480]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
myfont = pygame.font.SysFont(None, 48)
text = myfont.render('My Name', True, (0, 0, 0), (255, 255, 255))
textrect = text.get_rect()
textrect.centerx = screen.get_rect().centerx
textrect.centery = screen.get_rect().centery
screen.fill((255, 255, 255))
screen.blit(text, textrect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
clock.tick(20)
simply you can start new line after each print or sys stdout stream output by specify "\n" (ex: print ("hello" + "\n"
then your application will write to diffrent lines
I've have this dodging aliens game and it's not working. I can get the front begin screen to open but then when I hit enter to start it crashes and freezes. I've tried running it from python.exe instead of just IDLE but in that case it just pops up then closes right down. A few errors popped up the first few times I tried to run it but now there are no errors indicating what might be wrong. It just stops responding. What am I doing wrong here?
import pygame, random, sys
from pygame.locals import *
def startGame():
if event.type == K_ENTER:
if event.key == K_ESCAPE:
sys.exit()
return
def playerCollision():
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont(None, 55)
playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')
drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) + 65)
pygame.display.update()
topScore = 0
while True:
aliens = []
score = 0
playerRect.topleft = (750 /2, 750 - 50)
alienAdd = 0
while True:
score += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: x -=3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_ESCAPE]: sys.exit()
alienAdd += 1
if alienAdd == addedaliens:
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a)
screen.fill(0,0,0)
drawText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.update()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
pygame.display.update()
startGame()
Here's my new code after modifying it some
import pygame, random, sys
from pygame.locals import*
alienimg = pygame.image.load('C:\Python27\alien.png')
playerimg = pygame.image.load('C:\Python27\spaceship.png')
def playerCollision(): # a function for when the player hits an alien
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
def screenText(text, font, screen, x, y): #text display function
textobj = font.render(text, 1, (255, 255, 255))
textrect = textobj.get_rect()
textrect.topleft = (x,y)
screen.blit(textobj, textrect)
def main(): #this is the main function that starts the game
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont("monospace", 55)
pressed = pygame.key.get_pressed()
aliens = []
score = 0
alienAdd = 0
addedaliens = 0
while True: #our while loop that actually runs the game
for event in pygame.event.get(): #key controls
if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == KEYDOWN and event.key == pygame.K_LEFT:
playerRect.x -= 3
elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
playerRect.x += 3
playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
playerRect = playerImage.get_rect()
playerRect.topleft = (750 /2, 750 - 50)
alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images
alienAdd += 1
pygame.display.update()
if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a) #removes the aliens when they get to the bottom of the screen
screen.blit(screen, (0,0))
screenText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.flip()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
pygame.display.update()
main()
I still see several issues with your code and I think you're trying to do too much at once for the very beginning. Try to keep it as simple as possible. Try creating a display and draw some image:
import pygame
pygame.init()
display = pygame.display.set_mode((750, 750))
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
display.blit(img, (0, 0))
pygame.display.flip()
You'll have to adjust the img path of course. Running this you should either get an explicit Error (which you should then post in another thread) or see your img on the screen. BUT the program will not respond as there's no event handling and no main loop at all.
To avoid this, you could introduce a main loop like:
import sys
import pygame
pygame.init()
RESOLUTION = (750, 750)
FPS = 60
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
This should result in a program that displays the same img over and over, and it can be quit properly using the mouse. But still it's like a script, and if someone imported this, it would execute immediately, which is not what we want. So let's fix that as well and wrap it all up in a main function like this:
import sys
import pygame
#defining some constants
RESOLUTION = (750, 750)
FPS = 60
def main(): # <--- program starts here
# setting things up
pygame.init()
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
if __name__ == "__main__":
main()
The 'if name == "main":' ensures that the program does not execute when it's imported.
I hope this helps. And remember: Don't try too much all at once. Take small steps, one after another, and try to keep the control over your program. If needed, you can even put a print statement after every single line of code to exactly let you know what your program does and in what order.
So I decided to start making a game and I was testing it a bit and then I got this error:
Traceback (most recent call last):
File "TheAviGame.py", line 15, in <module>
font = pygame.font.Font(None,25)
pygame.error: font not initialized
I have no idea what I have done wrong so far...
Code:
#!/usr/bin/python
import pygame
blue = (25,25,112)
black = (0,0,0)
red = (255,0,0)
white = (255,255,255)
groundcolor = (139,69,19)
gameDisplay = pygame.display.set_mode((1336,768))
pygame.display.set_caption("TheAviGame")
direction = 'none'
clock = pygame.time.Clock()
img = pygame.image.load('player.bmp')
imgx = 1000
imgy = 100
font = pygame.font.Font(None,25)
def mts(text, textcolor, x, y):
text = font.render(text, True, textcolor)
gamedisplay.blit(text, [x,y])
def gameloop():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.pygame == pygame.KEYDOWN:
if event.key == pygame.RIGHT:
imgx += 10
gameDisplay.fill(blue)
pygame.display.update()
clock.tick(15)
gameloop()
You never initialized pygame and pygame.font after importing:
# imports
pygame.init() # now use display and fonts
In order to use some pygame modules, either pygame or that specific module has to be initialised before you start using them - this is what the error message is telling you.
To initialize pygame:
import pygame
...
pygame.init()
To initialize a specific library (eg font):
import pygame
...
pygame.font.init()
In most cases, you will want to initialise all of pygame, so use the first version. In general, I would place this at the top of my code, just after importing pygame
You put None in the font:
font = pygame.font.Font(None, 25)
You can’t do that.
You have to put a type of font there.
And you should call pygame.init().