How can I use letters to move player in pygame? [duplicate] - python

This question already has an answer here:
Why is my pygame application loop not working properly?
(1 answer)
Closed 2 years ago.
I wrote this code but it didn't work , I mean the window went unresponding :(.Please help!! Python_Army;)
Is the problem my laptop or my laptop or is it the code and if you could improve my code please answer me as fast as possible!!
here is the code:
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
background = pygame.image.load('C:/Users/H.S/Desktop/background.png')
player = pygame.image.load('C:/Users/H.S/Desktop/player.png')
file = pygame.image.load('C:/Users/Public/Pictures/Sample Pictures/Hydrangeas.jpg')
pygame.display.set_icon((file))
pygame.display.set_caption('a bit racey')
clock = pygame.time.Clock()
gameDisplay.blit(background, (0,0))
x = 300
y = 500
c = input()
if c == a:
x-=1
y = 500
pygame.display.flip()
pygame.display.update()
gameDisplay.blit(player, (x,y))
elif c == d:
x+=1
y = 500
pygame.display.update()
pygame.display.flip()
gameDisplay.blit(player, (x,y))
elif c == w:
y+=1
x = 300
pygame.display.flip()
pygame.display.update()
gameDisplay.blit(player, (x,y))
elif c == s:
y-=1
x = 300
pygame.display.flip()
pygame.display.update()
gameDisplay.blit(player, (x,y))
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True

You have to move and draw the player in the application loop. And of course you have to update the display in the application loop. The main application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
Use pygame.key.get_pressed() to get the states of the keys:
import pygame
pygame.init()
display_width, display_height = 800, 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
background = pygame.image.load('C:/Users/H.S/Desktop/background.png')
player = pygame.image.load('C:/Users/H.S/Desktop/player.png')
file = pygame.image.load('C:/Users/Public/Pictures/Sample Pictures/Hydrangeas.jpg')
pygame.display.set_icon((file))
pygame.display.set_caption('a bit racey')
clock = pygame.time.Clock()
x, y = 300, 500
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
x -= 1
if keys[pygame.K_d]:
x += 1
if keys[pygame.K_w]:
y -= 1
if keys[pygame.K_s]:
y += 1
gameDisplay.blit(background, (0,0))
gameDisplay.blit(player, (x, 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()

How do you cause an image to move in Pygame? [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
Closed 1 year ago.
I have this code:
plaxer = 20
player = 300
vel = 5
res = (720,720)
thistle = (216,191,216)
plum = (221,160,221)
screen = pygame.display.set_mode(res)
color = (255,255,255)
color_light = (255,0,0)
color_dark = (200,0,0)
red = (128, 0, 128)
reder = (31,0,31)
width = screen.get_width()
height = screen.get_height()
smallfont = pygame.font.SysFont('Corbel',35)
text = smallfont.render('Exit ' , True , color)
small = pygame.font.SysFont('Corbel',22)
texta = small.render('Customise Avatar ' , True , color)
screen.fill((0,0,255))
img1 = pygame.image.load("C:\\Users\\Path\\To\\Brown.png")
screen.blit(img1,(plaxer, player))
runs = True
while runs:
mouse = pygame.mouse.get_pos()
for ev in pygame.event.get():
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
plaxer =+ 0
screen.fill((0,0,255))
screen.blit(img1, (plaxer, player))
The problem is that the sprite doesn't move properly - it moves too robotically. How do I fix this?
You have to draw the player and update the display in the application loop:
while runs:
mouse = pygame.mouse.get_pos()
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
runs = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
plaxer += 1
screen.fill((0,0,255))
screen.blit(img1, (plaxer, player))
pygame.display.update()
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()

pygame image collsion trouble [duplicate]

This question already has an answer here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Closed 2 years ago.
I have tried to make a Zelda clone, and now I'm wondering how to calculate collision, can anyone tell me how to do that? I have tried colliderct and it simply won't work here is my code:
import pygame
pygame.init()
display = pygame.display.set_mode((800,600))
white=(255,255,255)
black=(0,0,0)
x=50
y=50
width = 40
height = 60
vel = 5
playerimg= pygame.image.load('link1.jpg').convert()
def player(x,y):
display.blit(playerimg,(x,y))
while True:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
x -= vel
if keys[pygame.K_d]:
x += vel
if keys[pygame.K_w]:
y -= vel
if keys[pygame.K_s]:
y += vel
display.fill(white)
player(x,y)
pygame.draw.rect(display, (255,0,0), hitbox,2)
pygame.display.update()
pygame.quit()
you can use 'hitboxes' to do this, one you must know the dimensions of your image
now that you got them, you can do
hitbox=(x,y, 102,131)
hitbox1=pygame.draw.rect(display, (255,0,0), hitbox,2)
if the_thing_it_hits.colliderect(hitbox) == True:
print('ouch')
put this in the while True: loop and it should be good
You can do a collision test by using pygame.Rect and colliderect(). For instance you can define an obstacle and get the rectangle from playerimg by get_rect(). Test if the 2 rectangles are colliding:
while True:
# [...]
hitbox = pygame.Rect(100, 100, 100, 100)
player_rect = playerimg.get_rect(topleft = (x, y))
if player_rect.colliderect(hitbox):
print("hit")
display.fill(white)
player(x,y)
pygame.draw.rect(display, (255,0,0), hitbox,2)
pygame.display.update()
Anyway, I recommend to use pygame.sprite.Sprite, pygame.sprite.Group and pygame.sprite.spritecollide().
Furthermore, your implementation of the QUIT event will not quit the game
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
because the break statement will just break the event loop, but not the application loop.
Use a variable instead:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

How to move the background image with keys in pygame?

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()

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