How to move the background image with keys in pygame? - python

I am making a game in pygame. In this game, the background image is large. On the screen, player only sees about 1/20th of the background image. I want, when player presses the left, right, up or down arrow keys, the background image moves respectively, but, it stops moving when player reaches the end of the image. I have no idea how to do this.
My code up to this point :-
import pygame
FPS = 60
screen = pygame.display.set_mode((1000, 1000))
bg = pygame.image.load('map.png')
clock = pygame.time.Clock()
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
Thanks in Advance :-

Get the sice of the background and the screen by get_size():
screen_size = screen.get_size()
bg_size = bg.get_size()
Define the initial start of the background in range [0, bg_size[0]-screen_size[0]]. e.g. center of the background:
bg_x = (bg_size[0]-screen_size[0]) // 2
Get the list of the key states by pygame.key.get_pressed():
keys = pygame.key.get_pressed()
Change bg_x dependent on the state of left and right:
if keys[pygame.K_LEFT]:
bg_x -= 10
if keys[pygame.K_RIGHT]:
bg_x += 10
Clamp bg_x to the range [0, bg_size[0]-screen_size[0]]:
bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x))
blit the background at -bg_x on the screen:
screen.blit(bg, (-bg_x, 0))
See the example:
import pygame
FPS = 60
screen = pygame.display.set_mode((1000, 1000))
bg = pygame.image.load('map.png')
screen_size = screen.get_size()
bg_size = bg.get_size()
bg_x = (bg_size[0]-screen_size[0]) // 2
bg_y = (bg_size[1]-screen_size[1]) // 2
clock = pygame.time.Clock()
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
bg_x -= 10
if keys[pygame.K_RIGHT]:
bg_x += 10
if keys[pygame.K_UP]:
bg_y -= 10
if keys[pygame.K_DOWN]:
bg_y += 10
bg_x = max(0, min(bg_size[0]-screen_size[0], bg_x))
bg_y = max(0, min(bg_size[1]-screen_size[1], bg_y))
screen.blit(bg, (-bg_x, -bg_y))
pygame.display.flip()

Related

pygame movement speed is not constant [duplicate]

This question already has answers here:
Pygame clock and event loops
(1 answer)
Framerate affect the speed of the game
(1 answer)
Closed last year.
I recently started with pygame and im trying to create movement but when I move my rectangle the speed changes at various times. it becomes slower and faster at various times
import pygame
pygame.init() # inisializing pygame
WIN = pygame.display.set_mode((500, 500)) # the width and hieght of the window
pygame.display.set_caption('pygame tutorial') # give the window a title
x = 50
y = 50 # character x and y positions
width = 40
height = 60 # rectangle width and height
vel = 5 # velocity (speed)
run = True # boolean variable
while run: # forever loop
for event in pygame.event.get(): # specifing the event
if event.type == pygame.QUIT: # pygame.QUIT makes the red x work so you can close the window
run = False # run = false so the while loop stops
key = pygame.key.get_pressed()
if key [pygame.K_a]:
x -= vel
if key[pygame.K_d]:
x += vel
if key[pygame.K_w]:
y -= vel
if key[pygame.K_s]:
y += vel
WIN.fill((0,0,0))
pygame.draw.rect(WIN, (255, 0, 0), (x, y, width, height))
'''
create a rectangle with 3 arguements, the window, the rgb colour, and the x,y positions width and height
'''
pygame.display.update()
pygame.quit()
You have wrong indentations so some code is executed inside many times in for-loop but it should be executed only once after for-loop
After changing indentations code work too fast and I needed to add clock.tick(60) to reduce speed to max 60 frames per second. This way it should run with the same speed on computers with older and newer CPU.
WIN = pygame.display.set_mode((500, 500)) # the width and hieght of the window
pygame.display.set_caption('pygame tutorial') # give the window a title
x = 50
y = 50 # character x and y positions
width = 40
height = 60 # rectangle width and height
vel = 5 # velocity (speed)
run = True # boolean variable
clock = pygame.time.Clock()
while run: # forever loop
for event in pygame.event.get(): # specifying the event
if event.type == pygame.QUIT: # pygame.QUIT makes the red x work so you can close the window
run = False # run = false so the while loop stops
# --- after loop --
key = pygame.key.get_pressed()
if key [pygame.K_a]:
x -= vel
if key[pygame.K_d]:
x += vel
if key[pygame.K_w]:
y -= vel
if key[pygame.K_s]:
y += vel
WIN.fill((0,0,0))
pygame.draw.rect(WIN, (255, 0, 0), (x, y, width, height))
'''
create a rectangle with 3 arguments, the window, the rgb colour, and the x,y positions width and height
'''
pygame.display.update()
clock.tick(60) # reduce speed to max 60 frames per seconds
pygame.quit()

Can't move character in pygame

I am trying to move my character (a spaceship) in pygame but what I have done so far has not worked. Everything runs and it displays the character but it does not move when I press the keys.
class Player:
vel = 10
x = width/2-PLAYER.get_width()/2
y = 450
def __init__(self, width, height):
self.width = width
self.height = height
def draw_player(self, win):
win.blit(PLAYER, (self.x, self.y))
def main():
running = True
clock = pygame.time.Clock()
fps = 30
while running:
bg = Background(0, 0)
bg.draw_background()
sc = Score(f"Score: {score}", WHITE)
sc.draw_score()
player = Player(50, 50)
player.draw_player(win)
pygame.display.set_caption("Space Invaders Game")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
player.x += 1
if keys[pygame.K_LEFT]:
player.x -= 1
pygame.display.flip()
clock.tick(fps)
if __name__ == "__main__":
main()
When you create an instance of a class, the constructor is executed and the object attributes are initialized. Hence, you continuously create a new player in his starting position. You are drawing the player at the same position over and over again. Actually the player is moving, but you never see the movement because a new player is immediately created at the starting position to replace the first player.
You must create the instance object of the Player class before the application loop instead of in the application loop:
def main():
player = Player(50, 50) # <--- ADD
running = True
clock = pygame.time.Clock()
fps = 30
while running:
bg = Background(0, 0)
bg.draw_background()
sc = Score(f"Score: {score}", WHITE)
sc.draw_score()
# player = Player(50, 50) <--- REMOVE
player.draw_player(win)
pygame.display.set_caption("Space Invaders Game")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
player.x += 1
if keys[pygame.K_LEFT]:
player.x -= 1
pygame.display.flip()
clock.tick(fps)

How do i make continuous player movement in pygame?

I've been watching a pygame tutorial on youtube on player movement, and by using this code below, the guy making the video was able to hold down a key and the character would keep moving, but when i hold down a key the character will move once and then stop. Any ideas on how to fix this?
Code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("huge honkabonkaros")
x = 50
y = 440
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
It is a matter of Indentation. The continuous movement must be in the application loop and not in the event loop. The application loop runs once per frame, but the event loop only runs once per event. When a key is pressed a KEYDOWN event occurs and when a key is released a KEYUP event occurs, but there is no event when a key is held down:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("huge honkabonkaros")
x = 50
y = 440
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# INDENTATION
#<--|
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()

Pygame collision detection issue

I am making a game with pygame where you have to dodge falling objects. I am having trouble with the collision detection, as when the obstacle touches the player, it just passes through to the bottom. Here is my code.
pygame.K_LEFT:
p_x_change = 0
screen.fill(WHITE)
pygame.draw.rect(screen,BLUE,(p_x,p_y, 60, 60))
pygame.draw.rect(screen,RED,(e_x,e_y,100,100))
p_x += p_x_change
e_y += e_ychange
if e_y > display_height:
e_y = 0
e_x = random.randint(1,display_width)
#Collision detection below
elif e_y == p_y - 90 and e_x == p_x :
done = True
clock.tick(60)
pygame.display.update()
Could you tell me what is wrong with my code?
I suggest to create two pygame.Rects, one for the player and one for the enemy. Then move the enemy by incrementing the y attribute of the rect and use the colliderect method to see if the two rects collide.
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
display_width, display_height = screen.get_size()
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('dodgerblue1')
RED = pygame.Color('firebrick1')
# Create two rects (x, y, width, height).
player = pygame.Rect(200, 400, 60, 60)
enemy = pygame.Rect(200, 10, 100, 100)
e_ychange = 2
done = False
while not done:
# Event handling.
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player.x -= 5
elif keys[pygame.K_d]:
player.x += 5
# Game logic.
enemy.y += e_ychange # Move the enemy.
if enemy.y > display_height:
enemy.y = 0
enemy.x = random.randint(1, display_width)
# Use the colliderect method for the collision detection.
elif player.colliderect(enemy):
print('collision')
# Drawing.
screen.fill(BG_COLOR)
pygame.draw.rect(screen, BLUE, player)
pygame.draw.rect(screen, RED, enemy)
pygame.display.flip()
clock.tick(30)
pygame.quit()

Making image move straight with pygame

I have to move the rectangular object straight through the pygame window. I have tried some code with pygame. The code is
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
movement = "straight"
x = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
if movement == 'straight':
x += 50
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
pygame.display.flip()
timer.tick(25)
Here the image didnt moves. What I need is that the image must be moved in a straight way.
x is adding, but that does not affect player, which actually affects the drawing of the rectangle.
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
timer = pygame.time.Clock()
movement = "straight"
x = 0
player = pygame.Rect((x, 100, 50, 50))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
if movement == 'straight':
x += 10
player = pygame.Rect((x, 100, 50, 50))
if x >= 300:
x = 0
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
pygame.display.flip()
timer.tick(25)
You need to adjust the player rectangle each time you change x. From http://www.pygame.org/docs/ref/rect.html, you can see that the first two arguments are "left" and "top". So, if you want to the rectangle to move from left to right, you'll want something like this:
player = pygame.Rect((100 + x, 100, 50, 50))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
import pygame
BLACK = pygame.color.Color('Black')
GREY = pygame.color.Color('Grey')
pygame.init()
screen = pygame.display.set_mode((300, 300))
screen_rect = screen.get_rect()
timer = pygame.time.Clock()
movement = "straight"
player = pygame.Rect(0, 100, 50, 50) # four aguments in place of tuple (,,,)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if movement == 'straight':
player.x += 10
if player.x >= 300: # check only when `player.x` was changed
player.x = 0
screen.fill(BLACK)
pygame.draw.rect(screen, GREY, player)
pygame.display.flip()
timer.tick(25)
BTW:
don't use raise to exit program.
use readable variable - not s_r but screen_rect
you don't need x - you have player.x
you can create rectangle only once
remove repeated empty lines when you add code to question

Categories

Resources