Pygame fading error when it is in a function - python

I am making an RPG in Pygame and I am having an error that is ruining the point of a fade. What is happening is that when I try to put the fading code in a function, so I don't have to have it dozens of times, it completely skips over the fading part and just flashes.
This is the working code
import pygame
import time
delay = time.sleep
white = 255,255,255
black = 0,0,0
pygame.display.set_caption("Liam's RPG")
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()
menuIntro = False
while not menuIntro:
menuIntro = True
logo = pygame.image.load("logo.png").convert()
logo.set_alpha(0)
for alpha in range(255):
screen.fill(black)
screen.blit(logo, (100,35))
logo.set_alpha(alpha)
clock.tick(200)
pygame.display.update()
delay(1.5)
This is the code that causes the fade to skip and mess up
import pygame
import time
delay = time.sleep
white = 255,255,255
black = 0,0,0
pygame.display.set_caption("Liam's RPG")
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()
menuIntro = False
sprite = ""
fade_x = 0
fade_y = 0
clocking = clock.tick(10)
def fading(sprite,clocking,fade_x,fade_y):
logo = pygame.image.load(sprite + ".png").convert()
logo.set_alpha(0)
for alpha in range(255):
screen.fill(black)
screen.blit(logo, (fade_x,fade_y))
logo.set_alpha(alpha)
clocking
while not menuIntro:
menuIntro = True
sprite = 'logo'
fade_x = 100
fade_y = 35
clocking = clock.tick(200)
fading(sprite,clocking,fade_x,fade_y)
pygame.display.update()
delay(1.5)
Here is the logo thing that I am trying to fade in, it needs to be in the same directory as the file

In correct code you have tick and update inside for alpha loop. In incorrect code you have tick and update outside this loop - and it doesn't work as you expect.

Related

I'm trying to move a monkey with arrow keys but every time I try to move it, the monkeys leaves a black trail behind

import pygame
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
fps = 60
screen_width = 864
screen_height = 936
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Flappy Bird')
#define game variables
ground_scroll = 0
scroll_speed = 4
flying = False
game_over = False
#load images
bg = pygame.image.load('forest.png')
ground_img = pygame.image.load('ground.png')
Monkey = pygame.sprite.Sprite()
Monkey.image = pygame.image.load("monkey.png")
#boundaries
Monkey.rect = Monkey.image.get_rect()
x=400
y=200
movex=0
movey=0
#draw background
screen.blit(bg, (0,0))
#draw the ground
screen.blit(ground_img, (ground_scroll, 768))
while(True):
Monkey.rect.topleft=(x,y)
screen.blit(Monkey.image, Monkey.rect)
x=x+movex
y=y+movey
pygame.display.update()
event=pygame.event.poll()
if(event.type==pygame.QUIT):
break
elif(event.type==pygame.KEYDOWN):
#KEYDOWN means a key is pressed
if(event.key==pygame.K_RIGHT):
movex=3
elif(event.key==pygame.K_LEFT):
movex=-3
elif(event.key==pygame.K_UP):
movey=-3
elif(event.key==pygame.K_DOWN):
movey=3
elif(event.type==pygame.KEYUP):
movex=0
elif (event.type==pygame.KEYUP):
movey = 0
movex = 0
pygame.display.update()
pygame.quit()
This is my code, it's supposed to be a monkey in a forest and I want to be able to control it with the arrow keys without the monkey leaving black trail behind.For some reason every time I move the monkey, these black like leave a trail and cover the whole screen. I just can't figure out how to get rid of them.
So pygame is interesting in the way it implements animation. It is not moving your monkey but actually redrawing it over and over again on the same screen. What you need to do is redraw your background over and over on top of the old images.
<code>
#draw background
screen.blit(bg, (0,0))
#draw the ground
screen.blit(ground_img, (ground_scroll, 768))
while(True):
Monkey.rect.topleft=(x,y)
</code>
instead
<code>
while(True):
#draw background
screen.blit(bg, (0,0))
#draw the ground
screen.blit(ground_img, (ground_scroll, 768))
Monkey.rect.topleft=(x,y)
</code>
Generally you need to clean the whole screen and render all itens again for don't leave a black trail through the item was moved.
FPS = Frames Per Second. For each time that something move in a frame the frame need be deleted and a new frame need be render again, with the new position of the object, without It you just are rendering new object's movement without clean the previous and make that image of "black trail".
Solution: for each frame draw the background again, then ground, etc... You'll see that the game will be fine
CAUTION: you need find the right sequence of each event, with the wrong you will just see the background's color

pygame.time.wait() crashes the program

In a pygame code I wannted to do a title that changes colors.
I tried to do a simple title that changes colors, but it not even turned the color to blue (or do it for a second), and the program crash. The code:
title_font = pygame.font.SysFont("monospace", TITLE_SIZE)
while True:
title = title_font.render("game", 5, RED)
game_display.blit(title, TITLE_POS)
pygame.display.update()
pygame.time.wait(2000)
title = title_font.render("game", 5, BLUE)
game_display.blit(title, TITLE_POS)
pygame.display.update()
pygame.time.wait(3000)
title = title_font.render("game", 5, RED)
game_display.blit(title, TITLE_POS)
pygame.display.update()
pygame.time.wait(2000)
It also happens with pygame.time.delay(), and I don't know where is the problem...
Don't use pygame.time.wait or delay because these functions make your program sleep for the given time and the window becomes unresponsive. You also need to handle the events (with one of the pygame.event functions) each frame to avoid this.
Here are some timer examples which don't block: Countdown timer in Pygame
To switch the colors, you can just assign the next color to a variable and use it to render the text.
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
title_font = pygame.font.SysFont('monospace', 50)
BACKGROUND_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('blue')
RED = pygame.Color('red')
# Assign the current color to the color variable.
color = RED
timer = 2
dt = 0
done = False
while not done:
# Handle the events.
for event in pygame.event.get():
# This allows the user to quit by pressing the X button.
if event.type == pygame.QUIT:
done = True
timer -= dt # Decrement the timer by the delta time.
if timer <= 0: # When the time is up ...
# Swap the colors.
if color == RED:
color = BLUE
timer = 3
else:
color = RED
timer = 2
screen.fill(BACKGROUND_COLOR)
title = title_font.render('game', 5, color)
screen.blit(title, (200, 50))
pygame.display.flip()
# dt is the passed time since the last clock.tick call.
dt = clock.tick(60) / 1000 # / 1000 to convert milliseconds to seconds.
pygame.quit()

Get higher resolution pygame

I am trying to make a game in python and pygame. I want to make a game with decent resolution, but I can't get higher resolution, any ways?
import pygame
import time
import random
import os
pygame.init()
height = 600
width = 800
window = pygame.display.set_mode((width,height))
white = 255,255,255
black = 0,0,0
red = 255,0,0
blue = 0,0,255
def update():
pygame.display.update()
def game():
stop_game = False
while not stop_game:
window.fill(white)
loaded_image = pygame.image.load("Player.png")
loaded_image = pygame.transform.scale(loaded_image,(150,150))
window.blit(loaded_image,(0,0))
update()
game()
print pygame.display.list_modes()
This will list the available display modes for you. Mine goes up to (2646, 1024).

Why does this pygame program freeze?

Below is a program using pygame which updates the histogram as values change.
However after a few seconds of running, the program freezes. Can someone point out the error?
import random
import pygame
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FRAME_RATE = 50
BACKGROUND_COLOR = pygame.Color("white")
BAR_COLOR = pygame.Color("Black")
BUCKET_CNT = 20
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
screen.fill(BACKGROUND_COLOR)
buckets = BUCKET_CNT*[0]
bar_w = SCREEN_WIDTH / BUCKET_CNT
clock = pygame.time.Clock()
background = pygame.Surface(screen.get_size())
background.fill(BACKGROUND_COLOR)
while True:
clock.tick(FRAME_RATE)
random.seed()
idx = random.randrange(BUCKET_CNT)
buckets[idx] += 1
# Create rectangles representing bars in the histogram.
bars = [pygame.Rect(i*bar_w,
SCREEN_HEIGHT - buckets[i],
bar_w, buckets[i]) for i in range(BUCKET_CNT)]
# Draw bars on the background
[pygame.draw.rect(background, BAR_COLOR, b, 5) for b in bars]
# Blit the background
screen.blit(background, (0, 0))
# Show "stuff" on the screen
pygame.display.flip()
EDIT
These are very good suggestions. I've changed my code using to follow them, however the code still freezes. Here is how the code looks now:
import random
import pygame
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
FRAME_RATE = 50
BACKGROUND_COLOR = pygame.Color("white")
BAR_COLOR = pygame.Color("Black")
BUCKET_CNT = 20
GROWTH_RATE = 10
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
screen.fill(BACKGROUND_COLOR)
buckets = BUCKET_CNT*[0]
bar_w = SCREEN_WIDTH / BUCKET_CNT
clock = pygame.time.Clock()
background = pygame.Surface(screen.get_size())
background.fill(BACKGROUND_COLOR)
# Create rectangles representing bars in the histogram.
bars = [pygame.Rect(i*bar_w,
SCREEN_HEIGHT - buckets[i],
bar_w, buckets[i]) for i in range(BUCKET_CNT)]
random.seed()
while True:
clock.tick(FRAME_RATE)
idx = random.randrange(BUCKET_CNT)
buckets[idx] += 1
bars[idx].inflate_ip(0, GROWTH_RATE)
# Draw bars on the background
pygame.draw.rect(background, BAR_COLOR, bars[idx])
# Blit the background
screen.blit(background, (0, 0))
# Show "stuff" on the screen
pygame.display.flip()
I want to apologize for taking everybody's time. As it turns out there is no issue with the code. My work machine was simply overloaded with various processes. It is running a multi-threaded test and a virtual machine (which is currently compiling a very large code base). That all explains why my program was freezing. Thank you DJMcMayhem for trying out the code. A special shout out to Alex Van Leiw. Thanks to you I learned a few new things about pygame today.

How do I add more than 2 sprites into an animation in pygame?

#Importing the pygame functions
import pygame
import sys
import os
from pygame.locals import *
#Allows for the editing of a window
pygame.init()
#Sets screen size
window = pygame.display.set_mode((800,600),0,32)
#Names the window
pygame.display.set_caption("TEST")
#Types of colors (red,green,blue)
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
yellow = (255,255,0)
red = (255,0,0)
purple = (255,0,255)
lightblue = (0,255,255)
white = (255,255,255)
pink = (255,125,125)
clock = pygame.time.Clock()
L1="bolt_strike_0001.PNG"
L1=pygame.image.load(L1).convert_alpha()
L2="bolt_strike_0002.PNG"
L2=pygame.image.load(L2).convert_alpha()
L3="bolt_strike_0003.PNG"
L3=pygame.image.load(L3).convert_alpha()
L4="bolt_strike_0004.PNG"
L4=pygame.image.load(L4).convert_alpha()
lightingCurrentImage = 1
#Loop
gameLoop = True
while gameLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop=False #Allows the user to exit the loop/game
window.fill(black) #used to fill the creen with the certian color variables
if (lightingCurrentImage==1):
window.blit(L1, (0,0))
if (lightingCurrentImage==2):
window.blit(L2, (0,0))
if (lightingCurrentImage==3):
window.blit(L3, (0,0))
if (lightingCurrentImage==4):
window.blit(L4, (0,0))
if (lightingCurrentImage==2):
lightingCurrentImage=1
if (lightingCurrentImage==3):
lightingCurrentImage=2
if (lightingCurrentImage==4):
lightingCurrentImage=3
else:
lightingCurrentImage+=3;
pygame.display.flip() #must flip the image o the color is visable
clock.tick(5)
pygame.quit() #quit the pygame interface
exit(0)
I'm having problems stitching together 10 images of a lightning bolt animation in pygame. What I have at the moment works but its not what I want it to look like. What happens when I run this is the lightning bolt creates the animation sequence once then disappears and never restarts the sequence again. If I set lightingCurrentImage+=3 to lightingCurrentImage+=2 it appears and stays on the screen but doesn't ever disappear. Please help me to see what the problem is if you can. Thanks! (I want the lightning bolt to begin and go all the way through the animation then disappear. Then begin again and repeat).
First create list of images then you can use it this way:
bold_imgs = []
bold_imgs.append( pygame.image.load("bolt_strike_0001.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0002.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0003.PNG").convert_alpha() )
bold_imgs.append( pygame.image.load("bolt_strike_0004.PNG").convert_alpha() )
lightingCurrentImage = 0
while True:
# here ... your code with events
window.fill(black)
window.blit( bold_imgs[ lightingCurrentImage ], (0,0))
lightingCurrentImage += 1
if lightingCurrentImage = len( bold_imgs ):
lightingCurrentImage = 0
pygame.display.flip()
clock.tick(5)
You can use tick(25) to get faster but smoother animation.
Human eye needs at least 25 images per second to see it as smooth animation.

Categories