Image Loading by keystrokes in Python with pygame - python

Im trying to make a simple image gallery which loads images with keystrokes using pygame in python, and this is how far i got
import pygame
pygame.init()
width=1366;
height=768
screen = pygame.display.set_mode((width, height ), pygame.NOFRAME)
pygame.display.set_caption('Katso')
penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()
x = 0; # x coordnate of image
y = 0; # y coordinate of image
*keys = pygame.event.get()
for event in keys:
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
screen.blit(mickey,(x,y)); pygame.display.update()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
screen.blit(penguin,(x,y)); pygame.display.update()*
running = True
while (running): # loop listening for end of game
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#loop over, quit pygame
pygame.quit()
i expect to press the arrow keys to load certain images
the screen opens but no image gets loaded

Program never wait for keypress so you have to check keys inside while loop.
import pygame
# --- constants --- (UPPER_CASE)
WIDTH = 1366
HEIGHT = 768
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
pygame.display.set_caption('Katso')
# - objects -
penguin = pygame.image.load("download.png").convert()
mickey = pygame.image.load("mickey.jpg").convert()
x = 0 # x coordnate of image
y = 0 # y coordinate of image
# - mainloop -
running = True
while running: # loop listening for end of game
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
#screen.fill( (0, 0, 0) )
screen.blit(mickey,(x,y))
pygame.display.update()
elif event.key == pygame.K_RIGHT:
#screen.fill( (0, 0, 0) )
screen.blit(penguin,(x,y))
pygame.display.update()
# - end -
pygame.quit()

Related

Why does my sprite reset to the top left of the screen when I try to rotate it with pygame.transform.rotate? [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 1 year ago.
I'm trying to rotate a sprite 90 degrees whenever the player presses the A and D keys, and I've got that working, but the sprite is always sent to the top left corner of the screen whenever this happens. Can someone shed some light on this? As well as that, I've tried to get a shooting system working with shooting asteroids, by creating an asteroid and appending it to a list, but it seems to become a tuple instead of a pygame rectangle when I try to change the y of it, can someone help with that as well?
import pygame, sys, random
from pygame.locals import *
#Imports pygame, system and random as modules to use later in the code.
#Also imports extra stuff from pygame that contains useful variables.
pygame.init()
mainClock = pygame.time.Clock()
FONT = pygame.font.SysFont(None, 48)
#Initialises pygame, sets up the clock to stop the program running too fast
#And also makes the font (must happen after pygame initialises)
WINDOWWIDTH = 1000
WINDOWHEIGHT = 1000
BACKGROUNDCOLOUR = (255, 255, 255)
TEXTCOLOUR = (0, 0, 0)
FPS = 60
PLAYERSPEED = 5
PLAYERIMAGE = pygame.image.load("images/P1.png")
PLAYERRECT = PLAYERIMAGE.get_rect()
ASTEROIDIMAGE = pygame.image.load("images/asteroid.png")
ASTEROIDRECT = ASTEROIDIMAGE.get_rect()
ASTEROIDMINSIZE = 3
ASTEROIDMAXSIZE = 5
ASTEROIDSPEED = 5
ASTEROIDS = []
#Defining Variables and setting up player sprite
def terminate():
pygame.quit()
sys.exit()
def pendingKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOUR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#Defining functions, to quit pygame and the system.
#And to wait for the escape key to be pressed to start the terminate function.
#And to wait for the quit event (such as at the end of the game).
#And a function to create text on the screen, such as for the title.
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Penguin Remastered')
pygame.mouse.set_visible(False)
#Creates the games window, sets the name of the window, and makes the mouse invisible
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
drawText('Space Penguin Remastered', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start!', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
pendingKey()
#Sets the colour of the background and draws the title and some basic instructions
#And updates the display and activates the terminate function
while True:
LEFT = RIGHT = UP = DOWN = SHOOT = LEFTROTATE = RIGHTROTATE = False
#Sets the players start position to half through the screen, and 50 pixels down
#And sets the movement variables to false
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
#Checks for events, first event being the game quitting
if event.type == KEYDOWN:
if event.key == K_LEFT:
RIGHT = False
LEFT = True
if event.key == K_RIGHT:
LEFT = False
RIGHT = True
if event.key == K_UP:
DOWN = False
UP = True
if event.key == K_DOWN:
UP = False
DOWN = True
if event.key == K_SPACE:
SHOOT = True
if event.key == K_a:
RIGHTROTATE = False
LEFTROTATE = True
if event.key == K_d:
LEFTROTATE = False
RIGHTROTATE = True
#Checks for keys being pressed, corresponding to movement.
if event.key == K_ESCAPE:
terminate()
#Checks for escape being pressed, which quits the game.
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT:
LEFT = False
if event.key == K_RIGHT:
RIGHT = False
if event.key == K_UP:
UP = False
if event.key == K_DOWN:
DOWN = False
if event.key == K_SPACE:
SHOOT = False
if event.key == K_a:
RIGHTROTATE = False
LEFTROTATE = False
if event.key == K_d:
LEFTROTATE = False
RIGHTROTATE = False
#Checks whether keys have been let go of.
if LEFT and PLAYERRECT.left > 0:
PLAYERRECT.move_ip(-1 * PLAYERSPEED, 0)
if RIGHT and PLAYERRECT.right < WINDOWWIDTH:
PLAYERRECT.move_ip(PLAYERSPEED, 0)
if UP and PLAYERRECT.top > 0:
PLAYERRECT.move_ip(0, -1 * PLAYERSPEED)
if DOWN and PLAYERRECT.bottom < WINDOWHEIGHT:
PLAYERRECT.move_ip(0, PLAYERSPEED)
if SHOOT:
ASTEROIDS.append(ASTEROIDIMAGE.get_rect(center=PLAYERRECT.midtop))
if LEFTROTATE:
PLAYERIMAGE = pygame.transform.rotate(PLAYERIMAGE, 90)
PLAYERRECT = PLAYERIMAGE.get_rect()
if RIGHTROTATE:
PLAYERIMAGE = pygame.transform.rotate(PLAYERIMAGE, -90)
PLAYERRECT = PLAYERIMAGE.get_rect()
for asteroid in ASTEROIDS:
asteroid.y -= 4
for asteroid in ASTEROIDS:
WINDOWSURFACE.blit(ASTEROIDIMAGE, asteroid)
#Moves the player a certain number of pixels in a direction and shoots asteroids
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
WINDOWSURFACE.blit(PLAYERIMAGE, PLAYERRECT)
pygame.display.update()
mainClock.tick(FPS)
#Fills the background, draws the players image on the rectangle
#And updates the screen and selects how many frames per second the game should tick by
Thanks in advance
Note that you should only call pygame.event.get() once in your application.
When you rotate, you set your player rect as such:
PLAYERRECT = PLAYERIMAGE.get_rect()
You have never specified the value of PLAYERIMAGE.get_rect() and it is (0, 0) by default, so if the player is transported to the top left of the screen. To fix that, simply remove it, it serves no purpose.
Also, your movement code can be simplified.
keys = pygame.key.get_pressed()
PLAYERRECT.move_ip
(
(keys[K_RIGHT] - keys[K_LEFT]) * PLAYERSPEED,
(keys[K_DOWN] - keys[K_UP]) * PLAYERSPEED
)
Thats it.
Code to handle rotation can be simplified as well. Make a function that gets the players rotation angle:
def getPlayerRotation(keys):
if keys[K_a]: return 90
elif keys[K_d]: return -90
return 0
Then use that to rotate your image and draw it.
#https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame
rotated_image = pygame.transform.rotate(PLAYERIMAGE, getPlayerRotation(keys))
new_rect = rotated_image.get_rect(center = PLAYERIMAGE.get_rect(topleft = PLAYERRECT.topleft).center)
WINDOWSURFACE.blit(rotated_image, new_rect)
Your asteroid isn't drawing because you are trying to draw it before you clear the screen, which draws over the asteroids.
Also you cannot do
ASTEROIDS.append(ASTEROIDIMAGE.get_rect(center=PLAYERRECT.midtop))
because there is only one asteroid.rect object, so what you are appending is a reference to the same object over and over. You need to create a new rect if your want to use a rect, but I got around the problem by using a list.
ASTEROIDS.append(list(PLAYERRECT.center))
and then later:
for asteroid in ASTEROIDS:
asteroid[1] -= 4
Lastly I changed pending key function:
def pendingKey(events):
for event in events:
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
It takes events as argument to avoid calling pygame.event.get() in the function. I also removed the return statement at the end of it since it was causing the function to exit before it got to to through all the events.
Here is the new code:
import pygame, sys, random
from pygame.locals import *
WINDOWWIDTH = 1000
WINDOWHEIGHT = 1000
pygame.init()
mainClock = pygame.time.Clock()
FONT = pygame.font.SysFont(None, 48)
BACKGROUNDCOLOUR = (255, 255, 255)
TEXTCOLOUR = (0, 0, 0)
FPS = 60
PLAYERSPEED = 5
PLAYERIMAGE = pygame.image.load("images/P1.png")
PLAYERRECT = PLAYERIMAGE.get_rect()
ASTEROIDIMAGE = pygame.image.load("images/asteroid.png")
ASTEROIDRECT = ASTEROIDIMAGE.get_rect()
ASTEROIDMINSIZE = 3
ASTEROIDMAXSIZE = 5
ASTEROIDSPEED = 5
ASTEROIDS = []
#Defining Variables and setting up player sprite
def terminate():
pygame.quit()
sys.exit()
def pendingKey(events):
for event in events:
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOUR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Penguin Remastered')
pygame.mouse.set_visible(False)
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
drawText('Space Penguin Remastered', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start!', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
def getPlayerRotation(keys):
if keys[K_a]: return 90
elif keys[K_d]: return -90
return 0
while True:
events = pygame.event.get()
pendingKey(events)
keys = pygame.key.get_pressed()
PLAYERRECT.move_ip((keys[K_RIGHT] - keys[K_LEFT]) * PLAYERSPEED, (keys[K_DOWN] - keys[K_UP]) * PLAYERSPEED)
#https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame
rotated_image = pygame.transform.rotate(PLAYERIMAGE, getPlayerRotation(keys))
new_rect = rotated_image.get_rect(center = PLAYERIMAGE.get_rect(topleft = PLAYERRECT.topleft).center)
for event in events:
if event.type == KEYDOWN and event.key == K_SPACE:
ASTEROIDS.append(list(PLAYERRECT.center))
for asteroid in ASTEROIDS:
asteroid[1] -= 4
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
WINDOWSURFACE.blit(rotated_image, new_rect)
for asteroid in ASTEROIDS:
WINDOWSURFACE.blit(ASTEROIDIMAGE, asteroid)
pygame.display.update()
mainClock.tick(FPS)

After playing my game once, if i select it again from the main menu it instantly cuts to the game over screen (pygame)

Basically whenever i select my game from the main menu it will play, but then if i go back to the main menu and select it again, it just shows the game over screen, and wont play again.
In the code below its about the zy_mainloop() part of the main_menu that doesnt run after the first time. I'd really appreciate some help with this
def main_menu():
WIDTH = 1280
HEIGHT = 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
main_menu = True
while main_menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
WIDTH = 480
HEIGHT = 600
pygame.display.set_mode((WIDTH, HEIGHT))
g.new()
g.show_go_screen()
main_menu = False
if event.key == pygame.K_2:
zy_mainloop()
main_menu = False
screen.blit(mainmenu_img, mainmenu_rect)
pygame.display.flip()
def start_screen():
WIDTH = 1280
HEIGHT = 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
start_screen = True
while start_screen:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
main_menu()
start_screen = False
screen.blit(startscreen_img, startscreen_rect)
pygame.display.flip()
def game_over_noscore():
WIDTH = 1280
HEIGHT = 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.blit(gameovernoscore_img, noscore_rect)
pygame.display.flip()
gameover_screen = True
while gameover_screen:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
main_menu()
gameover_screen = False
def zy_mainloop():
WIDTH = 480
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
zy_running = True
while zy_running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
zy_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and zyplayer.shotsfired <= 1:
zyplayer.shoot()
# Update
zy_all_sprites.update()
# Hit Check
hits = pygame.sprite.groupcollide(zy_bullets, zy_enemybullets, True, True, pygame.sprite.collide_circle)
for hit in hits:
m = zyEnemyBullet()
zy_all_sprites.add(m)
zy_enemybullets.add(m)
zyplayer.shotsfired -= 1
hits = pygame.sprite.spritecollide(zyplayer, zy_enemybullets, True, pygame.sprite.collide_circle)
for hit in hits:
zyplayer.lives -= 1
m = zyEnemyBullet()
zy_all_sprites.add(m)
zy_enemybullets.add(m)
hits = pygame.sprite.groupcollide(zy_bullets, zy_enemies, True, False, pygame.sprite.collide_circle)
for hit in hits:
zy_enemy.enemylives -= 1
zyplayer.shotsfired -= 1
hits = pygame.sprite.spritecollide(zyplayer, zy_enemies, False, pygame.sprite.collide_circle)
for hit in hits:
zyplayer.lives -= 3
# Win / Lose condition
if zyplayer.lives == 0:
game_over_noscore()
if zy_enemy.enemylives == 0:
game_over_noscore()
# Draw
zy_drawgame()
I had not seem code doing multiple windows, depending on the pygame.QUIT event, and then calling pygame.display.set_mode again before.
Maybe the "QUIT" event is persisting across function calls?
I'd suggest you to prefix each pygame.display.set_mode call in there with a pygame.event.get() - that would flush pending events, and ensure no events from a previous screen are on queue.
Looking back at your code - how does calling game_over_noscore() makes your program exit the mainloop? Or it does not, and only keeps displaying things until the player closes the window?

Why does Pygame Movie Rewind Only on Event Input

I'm working on a small script in Python 2.7.9 and Pygame that would be a small display for our IT department. The idea is that there are several toggle switches that indicate our current status (in, out, etc) , some information about our program at the school, and play a short video that repeats with images of the IT staff etc. I have an older version of Pygame compiled that still allows for pygame.movie to function.
All of the parts of the script work, but when it gets to the end of the .mpg, the movie will not replay until there is an EVENT, like switching our status or moving the mouse. I have tried to define a variable with movie.get_time and call to rewind at a certain time, but the movie will not rewind (currently commented out) . Is there a way to play the movie on repeat without requiring an event, or maybe I could spoof an event after a certain length of time (note that the documentation for pygame.movie is outdated, the loops function does not work) ?
Thank you for the help!
import pygame, sys, os, time, random
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("DA IT Welcome Sign")
pygame.font.get_default_font()
bg = pygame.image.load('da.jpg')
in_img = pygame.image.load('in.png')
out_img = pygame.image.load('out.png')
etc_img = pygame.image.load('etc.png')
present = in_img
done = False
img = 1
clock = pygame.time.Clock()
movie = pygame.movie.Movie('wallace.mpg')
movie_screen = pygame.Surface(movie.get_size()).convert()
playing = movie.get_busy()
movie.set_display(movie_screen)
length = movie.get_length()
currenttime = movie.get_time()
movie.play()
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
You need to take the code for replaying the movie out of the for loop that gets current events. Do this for that code and any other code you want to happen continuously without waiting for an event by moving the code 4 spaces to the left.
Like so:
while not done:
for event in pygame.event.get(): #gets most recent event, only executes code below when there is an event
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
#code below is out of the event for loop and thus executes whenever the while loop runs through
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
I have run into this problem too while trying to do things with pygame, it seems to be a common error.

pygame.key.get_pressed() - doesn't work - pygame.error: video system not initialized

I have two problems with my program:
When I close my program it has error: keys = pygame.key.get_pressed() pygame.error: video system not initialized
Square moves while I'm pressing 'd' and when I press something (or move mouse)
Important part of code is:
import pygame
from pygame.locals import*
pygame.init()
screen = pygame.display.set_mode((1200, 700))
ticket1 = True
# ...
c = 550
d = 100
# ...
color2 = (250, 20, 20)
while ticket1 == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
pygame.quit()
pygame.display.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
If I write keys = pygame.key.get_pressed() in just while loop it doesn't have error but it seems slower.
I also have another error: pygame.error: display Surface quit, but I always and in all my pygame programs have it and it isn'n so important but other things are important.
1.--------------
After pygame.quit() you don't need pygame.display.quit() but sys.exit().
pygame.quit() doesn't exit program so program still try to call screen.fill() and other function below pygame.quit()
Or you have to put pygame.quit() outside while ticket == True: (and then you don't need sys.exit())
You can use while ticket1: in place of while ticket == True: - it is more pythonic.
while ticket1: # it is more pythonic
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
pygame.quit()
2.--------------
if keys[pygame.K_d]: c += 1 is inside for event loop so it is call only when event is happend - when mouse is moving, when key is pressed or "unpressed". Move it outside of for event loop.
while ticket1: # it is more pythonic
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
keys = pygame.key.get_pressed()
# outside of `for event` loop
if keys[pygame.K_d]:
c += 1
# ...
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
pygame.quit()
Some people do it without get_pressed()
# clock = pygame.time.Clock()
move_x = 0
while ticket1 == True:
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
ticket1 = False
elif event.key == pygame.K_d:
move_x = 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d:
move_x = 0
# variable modification
c += move_x
# ...
# draws
screen.fill((255, 250, 245))
pygame.draw.rect(screen, color2, pygame.Rect(c, d, 50, 75))
pygame.display.flip()
# 60 FPS (Frame Per Second) to make CPU cooler
# clock.tick(60)
pygame.quit()
BTW: use pygame.time.Clock() to get the same FPS on fast and slow computers. Without FPS program refresh screen thousends times per second so CPU is busy and hot.
If you use FPS you have to add to c bigger value to get the same speed then before.

image is bad with python in pygame

I have a program in python:
import sys, random, pygame
from pygame.locals import *
pygame.init()
# Preparing Pygame
size = width, height = 718, 502
screen = pygame.display.set_mode(size)
framerate = pygame.time.Clock()
pygame.display.set_caption('Flappy Cube')
#Peparing background
background_x = 0
background_y = 0
background = pygame.image.load("background.jpg")
#Preparing Cube
cube_x = 100
cube_y = 200
cube_unscaled = pygame.image.load("cube.png")
cube = pygame.transform.smoothscale(cube_unscaled, (64, 64))
#Preparing Tubes
tube_x = 750
tube_y= 300
tube_unscaled = pygame.image.load("tube.png")
tube = pygame.transform.smoothscale(tube_unscaled, (125, 500))
# The main game loop
def exit_game():
sys.exit()
while True:
#Background
screen.blit(background, (background_x,background_y))
background_x = background_x+254.5
screen.blit(cube,(cube_x, cube_y))
#Tube
tube_x = tube_x -.075
screen.blit(tube,(tube_x, tube_y))
# If exit
for event in pygame.event.get():
if event.type == pygame.QUIT: exit_game()
# If Space Key is presed
elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
cube_y = cube_y-10
#If Clicked
elif pygame.mouse.get_pressed()[0]:
cube_y = cube_y-10
framerate.tick(60)
pygame.display.flip()
run_game()
I get this result: http://i.stack.imgur.com/MKYRM.png
I have to boost framerate.tick(60) to framerate.tick(700) it looks a glichy. when I program the gravity the multiple images won't look good.
how can i fix the images been drawn multiple times before the screen updates?
Try:
cube_unscaled = pygame.image.load("cube.png").convert_alpha()
You shouldn't need to boost your FPS in such way, 60 is a good value.
Also, I like better this order for your main loop: check events, draw, update, tick.
I don't think it makes a difference to your problem, but I think it easier to understand that way.
while True:
# If exit
for event in pygame.event.get():
if event.type == pygame.QUIT: exit_game()
# If Space Key is presed
elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
cube_y = cube_y-10
#If Clicked
elif pygame.mouse.get_pressed()[0]:
cube_y = cube_y-10
#Background
screen.blit(background, (background_x,background_y))
background_x = background_x+254.5
screen.blit(cube,(cube_x, cube_y))
#Tube
tube_x = tube_x -.075
screen.blit(tube,(tube_x, tube_y))
pygame.display.flip()
framerate.tick(60)
I fixed it! I just needed to fill the screen with black before "bliting" it.

Categories