Problem with flipping images in Pygame (python) - python

I am trying to create a game in which you can move a character with arrow keys. When moving left or right, I want the character (an image) to flip and point left/right accordingly. The original image/character is pointing left. But I cannot get the character to flip, please help me, thanks.
import pygame
pygame.init()#initiate pygame
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
display_width = 1200
display_height = 800
display = pygame.display.set_mode((display_width,display_height))
characterimg = pygame.image.load(r'/Users/ye57324/Desktop/Make/coding/python/characterimg.png')
def soldier(x,y):
display.blit(characterimg, (x,y))
x = (display_width * 0.45)
y = (display_height * 0.1)
pygame.display.set_caption('Game')
clock = pygame.time.Clock()#game clock
flip_right = False
x_change = 0
y_change = 0
start = True
while start:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change += -5
if flip_right == True:
pygame.transform.flip(characterimg, True, False)
flip_right = False
elif event.key == pygame.K_RIGHT:
x_change += 5
if flip_right == False:
pygame.transform.flip(characterimg, True, False)
flip_right = True
elif event.key == pygame.K_UP:
y_change += -5
elif event.key == pygame.K_DOWN:
y_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change += 5
elif event.key == pygame.K_RIGHT:
x_change += -5
elif event.key == pygame.K_UP:
y_change += 5
elif event.key == pygame.K_DOWN:
y_change += -5
x += x_change
y += y_change
display.fill(white)
soldier(x,y)
pygame.display.update()
clock.tick(60)#fps

Pygame's doc-page about pygame.transform.flip states
Flipping a Surface is non-destructive and returns a new Surface with the same dimensions.
This means that the surface you pass to that method remains unaffected. You have to keep the return-value around in order to see any effect.
In practice, this means that you should replace
pygame.transform.flip(characterimg, True, False)
with
characterimg = pygame.transform.flip(characterimg, True, False)
So that characterimg point to the new, flipped version of the image.
Note: Performance wise, this is not a very good method of doing things. Each time you call pygame.transform.flip, pygame has to allocated new memory for the new surface, go over each pixel of the original surface and copy it over to the new surface, transforming its position in the process. You'd better flip the image once at the beginning of your program, so that you have a variable characterimg_left and characterimg_right and then just assign those to your characterimg variable.

Related

Pygame - Movement Acceleration

I want to make a script in python/pygame that will make a character speed up as you hold a movement button (so, when I hold the left key, the character will accelerate to a specific speed and then the speed will even out, when I release the key it will slowly decrease in speed until stopping fully.)
at the moment, my code will recognize that the character must speed up, however the changes in speed only occur every time I press down and release the key (e.g: first key press will have the speed at 1, second press will be two, all the way up to the fifth or sixth press where it's at max speed, before resetting.)
I want to write my code so it means the character will accelerate whilst the key is being held down and not require multiple presses.
here is the movement section (with a few more random bits that were around it) of my code so far:
x = (display_width * 0.45)
y = display_height * 0.8
x_change = 0
negx = 0
posx = 0
bun_speed = 0
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
posx = 0
if negx != -5:
negx = negx - 1
x_change = negx
elif negx == -5:
negx = 0
x_change = -5
elif event.key == pygame.K_RIGHT:
negx = 0
if posx != 5:
posx = posx + 1
x_change = posx
elif posx == 5:
posx = 0
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
elif event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
display.fill(white)
bunny(x,y)
pygame.display.update()
clock.tick(60)
the two variables negx and posx decrease and increase respectively depending on the key pressed. pressing the key assigned to one variable resets the other to zero, so when that variable is next called when the opposite button is pressed it will accelerate from zero. Once either variable reaches the max speed, it resets for when the button is released meaning the character can accelerate once more.
If there's any way to make this work (as well as neaten up the code, if you're able to) then guidance as to how to get it to function would be much appreciated.
Define a variable for the acceleration (accel_x in the example), set it to the desired value in the event loop and add it to the x_change every frame to accelerate. To limit the x_change to the maximum speed, you have to normalize it and multiply it by the max_speed.
To decelerate the object, you can multiply x_change with a value below 1 when no key is pressed.
import pygame
pygame.init()
display = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
GRAY = pygame.Color('gray12')
display_width, display_height = display.get_size()
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
accel_x = 0
max_speed = 6
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
elif event.type == pygame.KEYDOWN:
# Set the acceleration value.
if event.key == pygame.K_LEFT:
accel_x = -.2
elif event.key == pygame.K_RIGHT:
accel_x = .2
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
accel_x = 0
x_change += accel_x # Accelerate.
if abs(x_change) >= max_speed: # If max_speed is exceeded.
# Normalize the x_change and multiply it with the max_speed.
x_change = x_change/abs(x_change) * max_speed
# Decelerate if no key is pressed.
if accel_x == 0:
x_change *= 0.92
x += x_change # Move the object.
display.fill(GRAY)
pygame.draw.rect(display, (0, 120, 250), (x, y, 20, 40))
pygame.display.update()
clock.tick(60)
pygame.quit()
I found another way of accelerating the character. Instead of changing distance, change time. I defined a variable which goes inside pygame.time.delay() and the delay is something I change. This is better because the character does not look like glitching when moving from one place to another.
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("ACCELERATE")
def main():
k = True
thita = 40
x = 250
y = 400
while k:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
thita = 40
if event.key == pygame.K_RIGHT:
thita = 40
if event.type == pygame.QUIT:
k = False
if keys[pygame.K_LEFT]:
x -= 4
pygame.time.delay(thita)
if thita > 12:
thita -= 1
if keys[pygame.K_RIGHT]:
x += 4
pygame.time.delay(thita)
if thita > 11:
thita -= 1
pygame.draw.rect(win, (255, 0, 0), (x, y, 10, 10))
pygame.display.update()
win.fill((0, 0, 0))
main()
You see the thita goes back to its original value as soon as we lift the key.
Kevin, what you have mentioned is a key point, but it is a very easy fix, you just need to replace decelerating code with something that checks whether the x_change is positive or negative and then adding or subtracting once you have figured it out.
For example his code is:
if accel_x == 0:
x_change *= 0.92
replace this with something along the lines of:
if accel_x == 0:
if x_change > 0:
x_change -= 0.2
if x_change < 0.2:
x_change = 0
elif x_change < 0:
x_change += 0.2
if x_change > -0.2:
x_change = 0

Can't figure out why my image wont move in pygame

I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player():
pygame.draw.circle(game_screen,red,(x,y),15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
dead = False
while dead != True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = -1
elif event.key == pygame.K_RIGHT:
player_x = +1
if event.key == pygame.K_UP:
player_y = +1
elif event.key == pygame.K_DOWN:
player_y = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_x = 0
if event.key == pygame.K_UP or pygame.K_DOWN:
player_y = 0
game_screen.fill(black)
player()
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()
quit()
Your indendation is all messed up.
Your code won't do anything unless the event is QUIT... which then makes it quit.
Your boolean logic is wrong.
This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.
I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN
Lastly, it wont' keep moving as you say you want.
It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.
Here is a fixed version, hope this helps:
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player(game_screen, red, point): # Use parameters not globals
pygame.draw.circle(game_screen, red, point, 15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
pygame.time.set_timer(pygame.USEREVENT, 1) # 1 per second
dead = False
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
elif event.type == pygame.USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 1) # Set another timer for another 1 second
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = +10
elif event.key == pygame.K_RIGHT:
player_x = -10
elif event.key == pygame.K_UP:
player_y = +10
elif event.key == pygame.K_DOWN:
player_y = -10
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
player_x = 0
elif event.key in [pygame.K_UP, pygame.K_DOWN]:
player_y = 0
game_screen.fill(black)
player(game_screen,red,(x,y))
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()

Falling mechanics (gravity) in pygame

How would I get some mechanics for falling when in an empty space, many answers on the internet said to add gravity but I couldn't understand how they did that they just showed me a bunch of equations.
Also, how would I set an image as my background?
Here's my source code:
import pygame
pygame.init()
display_width = 2560
display_height = 1440
white = (255,255,255)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('RGB')
clock = pygame.time.Clock()
filler = pygame.image.load('filleraftergimp.png')
def fill(x,y):
gameDisplay.blit(filler,(x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
diedorgameover = False
while not diedorgameover:
for event in pygame.event.get():
if event.type == pygame.QUIT:
diedorgameover = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_change = -5
elif event.key == pygame.K_d:
x_change = 5
elif event.key == pygame.K_s:
y_change = 5
elif event.key == pygame.K_w:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
if event.key == pygame.K_s or event.key == pygame.K_w:
y_change = 0
x += x_change
y += y_change
gameDisplay.fill(white)
fill(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
To implement gravity in your game (as in a 2D platformer), you can just increase the y_change variable each frame, so that you move the object a bit faster downwards each time. Take a look at this example:
import pygame as pg
pg.init()
LIGHTBLUE = pg.Color('lightskyblue2')
DARKBLUE = pg.Color(11, 8, 69)
display = pg.display.set_mode((800, 600))
width, height = display.get_size()
clock = pg.time.Clock()
player_image = pg.Surface((30, 60))
player_image.fill(DARKBLUE)
x = width * 0.45
y = 0
x_change = 0
y_change = 0
on_ground = False
# A constant value that you add to the y_change each frame.
GRAVITY = .3
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_a:
x_change = -5
elif event.key == pg.K_d:
x_change = 5
elif event.key == pg.K_s:
y_change = 5
elif event.key == pg.K_w:
if on_ground: # Only jump if the player is on_ground.
y_change = -12
on_ground = False
elif event.type == pg.KEYUP:
if event.key == pg.K_a and x_change < 0:
x_change = 0
elif event.key == pg.K_d and x_change > 0:
x_change = 0
# Add the GRAVITY value to y_change, so that
# the object moves faster each frame.
y_change += GRAVITY
x += x_change
y += y_change
# Stop the object when it's near the bottom of the screen.
if y >= height - 130:
y = height - 130
y_change = 0
on_ground = True
# Draw everything.
display.fill(LIGHTBLUE)
pg.draw.line(display, (0, 0, 0), (0, height-70), (width, height-70))
display.blit(player_image, (x, y))
pg.display.update()
clock.tick(60)
pg.quit()

Image not moving for the life of me

import pygame
# Some colors
GREEN = ( 0,255,0)
BLUE = ( 0, 0, 255)
WHITE = ( 255, 255, 255)
BLACK = ( 0, 0, 0)
pygame.init()
clock = pygame.time.Clock()
#Screen
SCREEN = pygame.display.set_mode([1000,700])
#Title
pygame.display.set_caption("Trying to move things")
#Variables
x_position = 100
y_position = 100
x_speed = 0
y_speed = 0
#Positions
image_image_positions = [x_position,y_position]
#Graphics
image_image = pygame.image.load("izzat.png").convert()
image_image.set_colorkey(BLACK)
#Main loop ____
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Keyboard commands.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_speed = -5
elif event.key == pygame.K_DOWN:
y_speed = 5
elif event.key == pygame.K_w:
x_speed = -5
elif event.key == pygame.K_s:
x_speed = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
x_speed += 0
if y_position + y_speed >=0 and y_position + y_speed + 60 <=500:
y_position += y_speed
x_position += x_speed
SCREEN.fill(GREEN)
SCREEN.blit(image_image, image_image_positions)
print(x_position)
print(y_position)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Hello, I have been having a problem which I'm really not happy at because I have been trying to fix it for a while now. So basically I have a image, and I wish to move the image based on the keyboard inputs, yet whatever I try nothing works. I then wondered maybe the y and x position aren't changing at all which is why the images positions are not changing, well I did print( those positions) but it the positions are definitely changing, the variables, so I do not get how the image positions do not change at all. Then I thought maybe because it's a tuple, so I changed it to parenthesis, that also did not work. I just don't get why my image position doesn't move if the variables for the position of the image do change. Thank you if you could help me in any way. I have looked this up but I couldn't find any help. Thank you for your help if you help me!
Update__________
Ok so apparently the image_image_position stays the same despite the variables changing when I printed the positions of image_image_position. Is there any way to change them and not have them stay at 100,100 all the time and change with the variables being changed?
You haven't assigned the speeds.
image_image_positions[0] = xspeed
image_image_positions[1] = yspeed
You are only changing your variables yspeed and xspeed, but you are not setting the actual positions of the image. Add the following line before the blit:
image_image_positions = [x_position,y_position]
Full code:
import pygame
# Some colors
GREEN = ( 0,255,0)
BLUE = ( 0, 0, 255)
WHITE = ( 255, 255, 255)
BLACK = ( 0, 0, 0)
pygame.init()
clock = pygame.time.Clock()
#Screen
SCREEN = pygame.display.set_mode([1000,700])
#Title
pygame.display.set_caption("Trying to move things")
#Variables
x_position = 100
y_position = 100
x_speed = 0
y_speed = 0
#Positions
image_image_positions = [x_position,y_position]
#Graphics
image_image = pygame.image.load("izzat.png").convert()
image_image.set_colorkey(BLACK)
#Main loop ____
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Keyboard commands.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_speed = -5
elif event.key == pygame.K_DOWN:
y_speed = 5
elif event.key == pygame.K_w:
x_speed = -5
elif event.key == pygame.K_s:
x_speed = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
x_speed += 0
if y_position + y_speed >=0 and y_position + y_speed + 60 <=500:
y_position += y_speed
x_position += x_speed
image_image_positions = [x_position,y_position]
SCREEN.fill(GREEN)
SCREEN.blit(image_image, image_image_positions)
print(x_position)
print(y_position)
pygame.display.flip()
clock.tick(60)
pygame.quit()
While you ARE updating the x/y positions, this isn't changing where the image is being drawn:
SCREEN.blit(image_image, image_image_positions)
image_image_positions, is never changed throughout the life-span of your application (besides startup).
To fix this simply add the update into your loop:
image_image_positions = [x_position,y_position]

How do I make a certain sprite move in pygame?

I need to make the player move continuously when I press a certain key.The problem that I have is that the image of the player is moving once (when I press one of the defined keys) and then it stops.
enter code here
import pygame
import sys
import os
import random
import time
from pygame.locals import *
pygame.init()
white = ( 255, 255, 255 )
black = ( 0, 0, 0 )
screenw = 800
screenh = 600
screen = pygame.display.set_mode( ( screenw, screenh ) )
pygame.display.set_caption( "Game" ) # Here I create a display.
clock = pygame.time.Clock()
class Car(pygame.sprite.Sprite): # Here I create a class.
def __init__( self, color = black, width = 100, height = 100 ):
pygame.sprite.Sprite.__init__( self )
self.image = pygame.Surface( ( width, height ) )
self.image.fill( color )
self.rect = self.image.get_rect()
def set_pos(self, x, y):
self.rect.x = x
self.rect.y = y
def set_img( self, filename = None):
if filename != None:
self.image = pygame.image.load( filename )
self.rect = self.image.get_rect()
def main():*I create a game loop
x_change = 0
y_change = 0
x = 0
y = 0
car_group = pygame.sprite.Group() # Make a group
player = Car()
player.set_img( "images.jpg" )
car_group.add( player )
exit = False
FPS = 60
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
elif event.key == pygame.K_RIGHT:
x_change = 10
elif event.key == pygame.K_UP:
y_change = -10
elif event.key == pygame.K_DOWN:
y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.type == pygame.K_DOWN:
x_change = 0
y_change = 0
x += x_change
y += y_change
screen.fill( white )
player.set_pos( x, y ) # Blit the player to the screen
car_group.draw( screen )
clock.tick( FPS )
pygame.display.update()
main()
pygame.quit()
quit()
Well the problem is that you are only allowing the sprite to move once. For example, take this piece of your code:
if event.key == pygame.K_LEFT:
x_change = -10
This will allow the x position to be smaller by 10. Then it stops. You maybe want to make a update function. A variable will also be made to allow the function to be used or not to be used. Another one will be used to control the direction it goes. Here is the update function. Feel free to change it to be able to fit your needs:
def update():
global direction
if direction == 'LEFT':
x -= 10
elif direction == 'RIGHT':
x += 10
elif direction == 'UP'
y -= 10
elif direction == 'DOWN':
y += 10
Now we will need the variable to control whether the function will run or not. Add these two lines for our new two variables:
run = 0
direction = 'NONE'
They should be before the code for the class. You absolutely change the lines from your event.key lines, it should be (in proper indention):
if event.key == pygame.K_LEFT:
direction = 'LEFT'
run = 1
elif event.key == pygame.K_RIGHT:
direction = 'RIGHT'
run = 1
elif event.key == pygame.K_UP:
direction = 'UP'
run = 1
elif event.key == pygame.K_DOWN:
direction = 'DOWN'
run = 1
Of course, there must be something to stop the car from repeatedly moving infinitely right? Add these lines with the lines above:
elif event.key == pygame.K_SPACE:
direction = 'NONE'
run = 0
Now put these two lines in the while loop but before you for loop:
if run == 1:
Car.update()
else:
pass
This should work because as long run is equal to 1, the car will continue its movement in the given direction until stopped by pressing the spacebar. I hope this helps you!

Categories