Why is the background not loading? - python

import pygame
screen = pygame.display.set_mode((3840,2160))
running = True
pygame.display.set_caption("GermanBall")
bg = pygame.image.load("Tan.jpg")
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(bg,(0,0))
pygame.display.update()
i need to know why this doesnt work
i tried changing the resolution of the image and the screen but to no avail, the image and screen are of same size

I think you have an indentation problem on the two last lines. The blit and the update are outside the while loop:
import pygame
screen = pygame.display.set_mode((3840,2160))
running = True
pygame.display.set_caption("GermanBall")
bg = pygame.image.load("Tan.jpg")
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(bg,(0,0)) # <- HERE
pygame.display.update() # <- HERE

Related

Keep getting an error about pygame not being initialised

I keep getting an error about system not being initialised. The error is about the pygame.display.update()
Where is this meant to go?
import pygame #IMPORTS THE PYGAME CLASSES, METHODS AND ATTRIBUTES
from pygame.locals import * #IMPORTING ALL PYGAME MODULES
pygame.init() #INITIALISING PYGAME
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("On The Run")
blue = 146,244,255 #BACKGROUND COLOUR
width = 80
height = 60
x = 200 #X-POSITION OF THE CHARACTER
y = 100 #Y-POSITION OF THE CHARACTER
player1 = pygame.image.load('assets/characterMove3.jpg') #DISPLAYING THE IMAGE ONTO THE SCREEN
player1 = pygame.transform.scale(player1,(width,height)) #SCALING THE IMAGE TO SUITABLE DIMENSIONS
WINDOW.blit(player1,(x,y))
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False #WE WILL QUIT THE GAME AS THE VARIABLE run IS NOW FALSE
pygame.quit() #IT WON'T SHOW THE MOST RECENT THING I DREW UNLESS I MANUALLY UPDATE IT
pygame.display.update()
game_loop()
The problem is that pygame.quit() is called in the application loop. pygame.quit() deinitializes all Pygame modules and crashes all subsequent Pygame API calls. pygame.quit() must be the very last Pygame API call. Call pygame.quit() after the application loop:
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#pygame.quit() <-- DELETE
pygame.display.update()
pygame.quit() # <-- INSERT
game_loop()

Why is my pymunk program is way too slow?

My pymunk program is way too slow. Every time I run the program it takes 5 seconds while loading. Here is my code. Thanks in advance.
import pymunk # Import pymunk..
import pygame
pygame.init()
display = pygame.display.set_mode((800,800))
clock = pygame.time.Clock()
space = pymunk.Space() # Create a Space which contain the simulation
FPS = 30
def convert_coordinates(point):
return point[0], 800-point[1]
running = True
space.gravity = 0,-1000 # Set its gravity
# Set the position of the body
body = pymunk.Body()
shape = pymunk.Circle(body, 10)
body.position = (400,800)
shape.density = 1
space.add(body,shape)
while running: # Infinite loop simulation
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
clock.tick(FPS)
space.step(1/FPS)
display.fill((255,255,255))
x,y = convert_coordinates(body.position)
sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
pygame.quit()
It's a matter of Indentation. You have to draw the scene in the application loop rather than the event loop:
while running: # Infinite loop simulation
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# <--- INDENTATION
clock.tick(FPS)
space.step(1/FPS)
display.fill((255,255,255))
x,y = convert_coordinates(body.position)
sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
pygame.display.update()
pygame.quit()

How to make my pygame game window resizeable?

When I run this code the resizeable option is available but when I click on it to maximize the screen, there is this weird white outline that appears. How would I fix it?.
import pygame
pygame.init()
screen = pygame.display.set_mode((900, 500), pygame.RESIZABLE)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
You have to recreate the display Surface in the VIDEORESIZE event (see pygame.event):
import pygame
pygame.init()
screen = pygame.display.set_mode((900, 500), pygame.RESIZABLE)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.VIDEORESIZE:
screen = pygame.display.set_mode(event.size, pygame.RESIZABLE)
pygame.display.update()

Cannot find reference 'load' in 'image.py'

I want to blit out my image on the screen with Pygame, but it doesn't work; It gives me a warning :
Cannot find reference 'load' in 'image.py'
And during execution time, it gives no such fatal error. All I get is a blank white screen with no image. I have referred to this and this, but just does not seem to work. This is my code:
import pygame
class Bouncer(object):
display_width = 600
display_height = 400
color_white = (255, 255, 255)
clock = pygame.time.Clock()
game_exit = False
bar_image = pygame.image.load('bar.png') # <------ here is the issue
def __init__(self):
pygame.init()
self.game_display = pygame.display.set_mode((self.display_width,
self.display_height))
pygame.display.set_caption('Bouncy Bouncer')
def showBar(self):
self.game_display.blit(self.bar_image, (10, 10))
def gameLoop(self):
while not self.game_exit:
for event in pygame.event.get():
#on close quit
if event.type == pygame.QUIT:
self.game_exit = True
pygame.quit()
quit()
#on key press quit
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
self.game_exit = True
pygame.quit()
quit()
self.showBar()
self.game_display.fill(self.color_white)
pygame.display.update()
self.clock.tick(60)
game_instance = Bouncer()
game_instance.gameLoop()
I called fiest called my image then the fill function, so it overlapped the white background, thus, covering the image. So, what I did was first call the background, then the image.

pygame.error: video system not initialized

I don't seem to able to get rid of this error, when I try to exist the game. the game runs fine but only get the error when I try to exist the game.
import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
#screen
screen_width = 800
screen_height = 500
screen = pygame.display.set_mode([screen_width,screen_height])
#load images etc.
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=4
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
falling = True
finish = True
#start = False
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
break
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
game()
This is the error I get, I've changed quit() to QUIT but still no luck.
Traceback (most recent call last):
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 171, in <module>
game()
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 160, in game
for event in pygame.event.get():
pygame.error: video system not initialized
thank you :)
You should stop your main loop when you want to exit the game.
My suggestions, either of
call exit() after pygame.quit()
set finish = True and start = False (though due to some indentation issues with your pasted code it's not possible to tell that this would actually work)
You should call pygame.quit() only when you want to terminate your Python session.
My suggestion: if you want to call game() more than once, e.g. in an interactive session, you should remove the call to pygame.quit() inside game(). This function uninitializes pygame and naturally all attempts to call its functionality will fail then.
You called pygame.quit(), but I think you need to also call sys.exit().
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
This is what I do in all of my games.
I think it's because you call pygame.quit() manually. Pygame will auto-quit itself, when your script ends.
To double check pygame is working, you can run this boilerplate: http://ninmonkey.googlecode.com/hg/boilerplate/pygame/1.%20blank%20screen/1%20-%20basic.%20pygame%20--nocomments.py
When you want to quit, set done=True. ( See line 37 and line 64 in the above example. )
I had this issue trying some Kivy test files using Spyder. In my case, because I was just trying out demo files, what quickly worked was restarting the kernel.
I know it's a blunt solution, but if you are on an IDE and you don't mind doing it, it's faster than typing commands.
You can do :
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Here we exit the Loop and execute what after.
pygame.quit()
and It works fine !

Categories

Resources