Reputation: 39
I made a program that displays a word and plays a sound effect everytime you click the space bar. My problem is that sometimes when the word is blited to the screen it either blits halfway on the screen or halfway off the screen. I tried using a statement that says if x > 800 but I know there has to be a better way to do that and I just don't know about it any help is much appreciated!
import pygame, random, sys
from pygame.locals import *
pygame.init()
screen_size = ((800,600))
pygame.mixer.music.load("Derp.wav")
screen = pygame.display.set_mode(screen_size)
while True:
newSat = random.randint(1,100)
r = random.randint(1,255)
g = random.randint(1,255)
b = random.randint(1,255)
newSize = random.randint(1,50)
myfont = pygame.font.SysFont("Ubuntu", newSize)
derp = myfont.render("Derp",newSat,(r,g,b))
newX = random.randint(1,800)
newY = random.randint(1,600)
newSpot = random.randint(1,800)
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
screen.blit(derp,(newX,newY))
pygame.mixer.music.play(0)
if event.key == K_ESCAPE:
sys.exit()
pygame.display.update()
Upvotes: 2
Views: 299
Reputation: 996
Right! So, to make sure that your blitted surface (in this case the rendered text) will always be inside the screen you need to put some restrictions in your random generations!
derp = myfont.render("Derp",newSat,(r,g,b))
newX = random.randint(1,800 - derp.get_width())
newY = random.randint(1,600 - derp.get_height())
That way irrespectively of the text's size, the random position will always be inside your screen :) And then you can safely blit your text:
screen.blit(derp,(newX,newY))
Hope that helped!,
Cheers, Alex
Upvotes: 2