Pygame moving backround (downward) image not loading [duplicate] - python

This question already has answers here:
How to scroll the background surface in PyGame?
(1 answer)
Making the background move sideways in pygame
(2 answers)
Closed 3 months ago.
i'm learning how to make a moving backround in pygame.
i learnd how to do it horizontal and trying now to do it vertical.
My problem is that my loop is not fully working , i manged to make it so the backround moves downward, but it wont make a third / fourth etc screen it just stops after 2 screens.
Thank you in advance for the help/ explenation. ^-^
import sys
import pygame
pygame.init()
fps = 60
framepersec = pygame.time.Clock()
white = (255, 255, 255)
screen_width = 400
screen_height = 600
display = pygame.display.set_mode((screen_width, screen_height))
display.fill(white)
pygame.display.set_caption("Backround test")
class Backround():
def __init__(self):
self.bgimage = pygame.image.load("image/test.png").convert()
self.rectbgimg = self.bgimage.get_rect()
self.bgy1 = 0
self.bgx1 = 0
self.bgy2 = -self.rectbgimg.height
self.bgx2 = 0
self.moving_speed = 3
def update(self):
self.bgy1 += self.moving_speed
self.bgy2 += self.moving_speed
if -self.rectbgimg.height >= self.bgy1:
self.bgy1 = self.rectbgimg.height
if -self.rectbgimg.height >= self.bgy2:
self.bgy2 = self.rectbgimg.height
def render(self):
display.blit(self.bgimage, (self.bgx1, self.bgy1))
display.blit(self.bgimage, (self.bgx2, self.bgy2))
backround = Backround()
while True:
framepersec.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
backround.update()
backround.render()
pygame.display.update()

Related

Why is the show text function not working in pygame [duplicate]

This question already has answers here:
Why is my pygame display not responding while waiting for input?
(1 answer)
How can I create a text input box with Pygame?
(5 answers)
Closed 5 months ago.
So basically what happened is, I am making a reminder app where it rings an alarm at a certain time, the problem is I'm having trouble displaying a time. I've used show text in this code to display the current time, but when I try to display an activity I'm not getting an error but it's not showing.
Code:
from pygame import mixer
from datetime import datetime
import pygame
from pygame.locals import *
pygame.init()
mixer.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("App")
mixer.music.load("song.mp3")
mixer.music.set_volume(0.7)
global o
o=0
#FUNCTIONS
def show_text(msg, x, y, color, size):
fontobj= pygame.font.SysFont("freesans", size)
msgobj = fontobj.render(msg,False,color)
screen.blit(msgobj,(x, y))
def Session():
session_name = input("What do you want to call your session?")
starttime = input("What time do you want to start? (Example 600 = 6:00)")
endtime = input("What time do you want to end? (Example 700 = 7:00)")
o=1
pygame.display.update()
#VARIABLES
green = (0,255,0)
black = (0,0,0)
white = (255,255,255)
activites = ""
start_time = ""
end_time = ""
counter = 0
hours = 60
#END OF VARIABLES
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x>239 and x<286 and y> 399 and y<446:
counter = 1
if counter == 1:
Session()
counter = 0
screen.fill(black)
#GETTING TIME
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
#END OF GETTING TIME
#GUI
show_text(str(current_time),220,10,green,20)
if o==1:
show_text(str(session_name), 180,200, white, 75)
show_text("Add Activity",220,375,green,20)
pygame.draw.rect(screen,green,(240,400,45,45))
pygame.draw.rect(screen,white,(260,403,5,40))
pygame.draw.rect(screen,white,(245,420,37,5))
#END OF GUI
pygame.display.update()
I Would appreciate a response on why it was wrong as well as a fixed code, thanks in advance!

How to get colors displayed into game I am making? [duplicate]

This question already has answers here:
Pygame window not responding after a few seconds
(3 answers)
Pygame unresponsive display
(1 answer)
Pygame window freezes when it opens
(1 answer)
Closed 2 years ago.
This is the first time I am using Pygame. And I am just starting to learn programming. At the moment I learning for about 4 to 7 months.
I followed the tutorial for the game I am making. (How to Program a Game! (in Python) by Keith Galli)
Unfortenately the colors will not be displayed in the game. So at the moment I am just staring at a black 'box'.
The game is a kind of 'space invaders'-game. So there are blue bricks falling from the top of the 'box', but at the moment you don see them.
Because I am jusing Linux Mint as my OS, I thought: mayby I need other code for the colours.
I tried ANSI code:
# ANSI escae code for colours:
#RED = "\e[0;31m"
#BLUE = "\e[34mBlue"
#YELLOW= "\e[33mYellow"
#BACKGROUND_COLOUR = "\e[30m"
instead of RGB:
# RGB colours:
RED = (255, 0, 0))
BLUE = (0, 0, 255))
YELLOW= (204, 204, 0)
BACKGROUND_COLOUR = (0, 0, 0))
But I stil do not see anything when I run the game :(
Here is some code:
import pygame
import random
import sys
import colorama
pygame.init()
WIDTH = 800
HEIGHT = 600
# ANSI escae code for colours:
#RED = "\e[0;31m"
#BLUE = "\e[34mBlue"
#YELLOW= "\e[33mYellow"
#BACKGROUND_COLOUR = "\e[30m"
# RGB colours:
RED = (255, 0, 0))
BLUE = (0, 0, 255))
YELLOW= (204, 204, 0)
BACKGROUND_COLOUR = (0, 0, 0))
player_size = 50
player_pos = [WIDTH/2, HEIGHT - 2 * player_size]
enemy_size = 50
enemy_pos = [random.randint(0, WIDTH - enemy_size), 0]
enemy_list = [enemy_pos]
SPEED = 10
screen = pygame.display.set_mode((WIDTH,HEIGHT))
# gameloop
game_over = False
score = 0
clock = pygame.time.Clock()
myFont = pygame.font.sysFont("monospace", 35)
def set_level(score,SPEED):
if score < 20:
SPEED = 5
elif score < 40:
SPEED = 8
elif score < 60:
SPEED = 12
else:
SPEED = 18
return SPEED
# SPEED = score / 5 +1
# return SPEED
def drop_enemies(enemy_list):
delay = random.random()
if len(enemy_list) < 10 and delay < 0.1:
x_pos = random.randint(0, WIDTH - enemy_size)
y_pos = 0
enemy_list.append([x_pos, y_pos])
def draw_enemies(enemy_list):
for enemy_pos in enemy_list:
pygame.draw.rect(screen, BLUE, (enemy_pos[0], enemy_pos[1],
enemy_size, enemy_size))
I hope to see the bricks in the game.
Whick colorcoding to use... and how to implement these?
Blue for the ones falling from the sky, red for the player itself.
You need a main loop, which does the following:
clear the screen with the back ground color (pygame.Surface.fill())
draw all the objects
update the display (pygame.display.update() or pygame.display.flip())
e.g.:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(BACKGROUND_COLOUR)
draw_enemies(enemy_list)
pygame.display.update()

Very simple PyGame very slow [duplicate]

This question already has answers here:
Lag when win.blit() background pygame
(2 answers)
Closed 2 years ago.
I want to make a (a bit bigger) game in PyGame, but even with this simple code I just get arround 10 fps instead of 60? Here's the code:
import pygame
res = 1280,720
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load("Background.png"), res)
a = 0
while True:
pygame.time.Clock().tick(60)
display.fill((0,0,0))
a += 10
display.blit(background, (0,0)) #Without this line: arround 20 fps
pygame.draw.rect(display,(255,0,0), (a,8,339,205))
pygame.display.update()
pygame.quit()
What am I doing wrong?
Thank you!
Try the following optimizations:
Use the convert() method on your image pygame.image.load("Background.png").convert()). This makes the animation about 5 times faster.
Instead of re-blitting entire background every frame, only update the changed parts of the screen.
You don't need to clear the screen before drawing the background.
Use the same Clock instance every frame.
Here's the code:
import pygame
pygame.init()
res = (1280, 720)
display = pygame.display.set_mode(res, pygame.RESIZABLE)
pygame.display.set_caption("Test")
background = pygame.transform.smoothscale(pygame.image.load(r"E:\Slike\Bing\63.jpg").convert(), res)
a = 0
clock = pygame.time.Clock()
display.blit(background, (0, 0))
pygame.display.update()
while True:
clock.tick(60)
rect = (a,8,339,205)
display.blit(background, rect, rect) # draw the needed part of the background
pygame.display.update(rect) # update the changed area
a += 10
rect = (a,8,339,205)
pygame.draw.rect(display, (255,0,0), rect)
pygame.display.update(rect) # update the changed area

How to centre an image in pygame? [duplicate]

This question already has an answer here:
How to center an image in the middle of the window in pygame?
(1 answer)
Closed 6 months ago.
I am using python 2.7, I would like to know if there is a way to centre an image in pygame. I have set the screen to fullscreen, is this possible? If it helps i will attach the code, thanks.
import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
pygame.init()
screen = pygame.display.set_mode((0, 0))
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill((0, 0, 0))
screen.blit(get_image('sw.png'), (0, 0)
pygame.display.flip()
clock.tick(60)
Yeah, it's possible.
You have to create a rect object of the image:
image = "insert image"
rect = image.get_rect ()
And then:
rect.center = ("coordinates of center")
This StackOverflow question might be able to help you.
Pygame Image position
Basically though, you'd get the image rectangle. From there there are a lot of useful functions you can call to position it.

Pygame fading error when it is in a function

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.

Categories