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

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

Related

Pygame mouse hover [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How do I add a border to a sprite when the mouse hovers over it, and delete it after the mouse stops?
(1 answer)
Closed 5 months ago.
So im trying to remake a simple card game in pygame. Im trying to make it where whenever you hover over a card it will turn slightly transparent by changing the alpha of the card.
However I can't seem to get this to work and im genuinely confucious as to why my code doesnt work.
while running:
mX, mY = pygame.mouse.get_pos()
if 50 + 60 > mX > 50 and 500 + 84 > mY > 500:
hand[0].set_alpha(100)
else:
hand[0].set_alpha(255)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Hover()
if printHand:
#print(hand)
#print(cardSize)
#print(hand[0].get_width())
#print(hand[0].get_height())
#print(hand[0].get_rect(center=(80, 542)))
printHand = False
if displayHand:
DisplayHand(hand)
DisplayBoard(pile1)
DisplayBoard(pile2)
displayHand = False
print(50 + 60 > mX > 50 and 500 + 84 > mY > 500)
pygame.display.update()
Where hand is an array of surfaces from image.load
As of right now this code doesnt do anything but the print statement at the end returns true
Here is a minimal example that creates a Card sprite with two images, swapping the image if the mouse is over the card.
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
class Card(pygame.sprite.Sprite):
"""A playing card like sprite"""
def __init__(self, color="white", pos=(0, 0)):
pygame.sprite.Sprite.__init__(self)
self.color = pygame.Color(color)
# if you're loading an image, make sure to use .convert()
self.orig_image = pygame.Surface((50, 100), pygame.SRCALPHA)
self.orig_image.fill(self.color)
# create a copy of the image
self.alt_image = self.orig_image.copy()
self.alt_image.set_alpha(127) # make the copy transparent
self.image = self.orig_image
self.rect = self.image.get_rect(center=pos)
def update(self):
if self.rect.collidepoint(pygame.mouse.get_pos()):
self.image = self.alt_image
else:
self.image = self.orig_image
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
cards = pygame.sprite.Group()
# create five cards distributed across the bottom of the screen
for x in range(5):
card = Card(pos=((x + 1) * (WIDTH // 6), HEIGHT - 90))
cards.add(card)
pygame.display.set_caption("♠♣♥♦ Cards")
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
pass
# update game elements
cards.update()
# draw surface - fill background
window.fill("black")
## draw sprites
cards.draw(window)
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
pygame.quit()
This will look like this, although the screenshot doesn't include the mouse cursor:

How can I limit the screen in pygame? [duplicate]

This question already has answers here:
Setting up an invisible boundary for my sprite
(1 answer)
Use vector2 in pygame. Collide with the window frame and restrict the ball to the rectangular area
(1 answer)
How to make ball bounce off wall with PyGame?
(1 answer)
Not letting the character move out of the window
(2 answers)
Closed 10 months ago.
I just started trying out pygame, so I watched a tutorial. When the guy showed, how to create edges left and right from the screen, it just didn't work when I did it, even though I've written it 100% equal as the tutorial guy. The tutorial is already two years old, so maybe pygame just has changed. Can somebody help me?
That's my code:
import pygame
import sys
pygame.init()
background = pygame.image.load("C:\Programmieren\Python\Grafiken\pygame test1 - background.png")
screen = pygame.display.set_mode([1200,595])
clock = pygame.time.Clock()
pygame.display.set_caption("pygame test1")
def draw():
screen.blit(background, (0, 0))
pygame.draw.rect(screen, (0, 0, 255), (x, y, width, height))
pygame.display.update()
x = 300
y = 300
speed = 3
width = 40
height = 80
left_wall = pygame.draw.rect(screen, (0,0,0), (-2,0,2,600), 0)
right_wall = pygame.draw.rect(screen, (0,0,0), (1201,0,2,600), 0)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
character = pygame.Rect(x,y,width, height)
pressed = pygame.key.get_pressed()
if presses[pygame.K_UP] or pressed[pygame.K_w] or pressed[pygame.K_SPACE]:
y -= speed
if pressed[pygame.K_RIGHT] or pressed[pygame.K_d] and not character.colliderect(right_wall):
x += speed
if pressed[pygame.K_DOWN] or pressed[pygame.K_s]:
y += speed
if pressed[pygame.K_LEFT] or pressed[pygame.K_a] and not character.colliderect(left_wall):
x -= speed
draw()
clock.tick(60)
The following code works for me after replacing the background.png path with a picture that exists on my computer. I changed left_wall and right_wall to call pygame.Rect instead of pygame.draw.rect and copied the draw.rect calls that were previously assigned to left_wall and right_wall to draw() function, and added some needed parentheses in two of the if statements. Also fixed a typo where pressed was spelled presses.
Without the parentheses, the character would always move right when right key is pressed even past the right edge of the window. When "d" is pressed, it would check against colliderect. Same for left arrow and "a" keys. or short-circuits, so if K_RIGHT or K_LEFT is pressed, it doesn't check the right hand side of the or in the if statements. With the parentheses added, the "move right" if statement always checks colliderect when K_RIGHT or K_d is pressed, instead of only when K_d is pressed.
import pygame
import sys
pygame.init()
background = pygame.image.load("C:\Programmieren\Python\Grafiken\pygame test1 - background.png")
screen = pygame.display.set_mode([1200,595])
clock = pygame.time.Clock()
pygame.display.set_caption("pygame test1")
def draw():
screen.blit(background, (0, 0))
pygame.draw.rect(screen, (0, 0, 255), (x, y, width, height))
pygame.draw.rect(screen, (0,0,0), left_wall, 0)
pygame.draw.rect(screen, (0,0,0), right_wall, 0)
pygame.display.update()
x = 300
y = 300
speed = 3
width = 40
height = 80
left_wall = pygame.Rect(-2,0,2,600)
right_wall = pygame.Rect(1201,0,2,600)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
character = pygame.Rect(x,y,width, height)
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] or pressed[pygame.K_w] or pressed[pygame.K_SPACE]:
y -= speed
if (pressed[pygame.K_RIGHT] or pressed[pygame.K_d]) and not character.colliderect(right_wall):
x += speed
if pressed[pygame.K_DOWN] or pressed[pygame.K_s]:
y += speed
if (pressed[pygame.K_LEFT] or pressed[pygame.K_a]) and not character.colliderect(left_wall):
x -= speed
draw()
clock.tick(60)

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

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

I'm having trouble making the paddles stay in the screen? [duplicate]

This question already has answers here:
Not letting the character move out of the window
(2 answers)
Closed 2 years ago.
I'm trying to make the paddles move up and down : 1 rectangle. moving with w/a/s/d keys 2 rectangle. with arrows. I'm having trouble making the paddles stay in the screen?
You will make two “paddles” (i.e. Rectangles), one on the left side and one on the right side of the screen. These rectangles should be taller than they are wide (i.e. Look like a paddle from a pong game). The paddle on the left should be able to move up and down using the w and s keys, the paddle on the right should move up and down using the up and down arrow keys. Both paddles should not be allowed to leave the top or bottom of the screen. (* for this assignment you are just creating the paddles and getting them moving properly,, no balls necessary). Try to avoid hardcoded values.
# import the necessary modules
import pygame
import sys
#initialize pygame
pygame.init()
# set the size for the surface (screen)
screen_h = 800
screen_w = 600
screen = pygame.display.set_mode((screen_h,screen_w),0)
# set the caption for the screen
pygame.display.set_caption("Template")
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 50
R1h = 132
R1dx = 0
R1dy = 0
#variables for second rectangle
R2x = 10
R2y = 300
R2w = 50
R2h = 132
R2dx = 0
R2dy = 0
#speed
speed = 3
screen.fill(BLACK)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
R1dx = 0
R1dy = -speed
elif event.key == pygame.K_DOWN:
R1dx = 0
R1dy = speed
if event.key == pygame.K_w:
R2dx = 0
R2dy = -speed
elif event.key == pygame.K_s:
R2dx = 0
R2dy = speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
R1dx = 0
R1dy = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
R2dx = 0
R2dy = 0
# move the x and y positions of the rectangles
oldR1x = R1x
oldR1y = R1y
R1x = R1x + R1dx
R1y = R1y + R1dy
if R1x >= screen_w-50:
R1x = oldR1x
R1y = oldR1y
if R1x<= 50:
R1x = oldR1x
R1y = oldR1y
if R1y>= screen_h-50:
R1x = oldR1x
R1y = oldR1y
if R1y<= 50:
R1x = oldR1x
R1y = oldR1y
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()
First of all you have swapped the screen width (screen_w) and the screen height (screen_h). It has to be:
# set the size for the surface (screen)
screen_w = 800
screen_h = 600
screen = pygame.display.set_mode((screen_w,screen_h),0)
The paddles move just up an down, so it sufficient to limit the y coordinate of the pddels to the range [0, screen_h-R1h]. Note, R1y respectively R2y are the top coordinate of the paddles:
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
Furthermore, the screen has to be cleared in the main application loop (screen.fill(BLACK)):
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
# [...]
# move the x and y positions of the rectangles
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
# clear screen
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
Note, it the paddles would move along the x axis too (left, right), then the restriction of the x coordinate is similar:
R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))

How to scroll image with mouse in pygame?

I need to move my paddle image vertically by mouse, how can i do so? Here is my code. I want to move my mouse and associate movement with paddle as in pong game.
import pygame
pygame.init()
width = 900
height = 600
black = (0,0,0)
white = (255, 255, 255)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
paddle1Img = pygame.image.load('paddle.png')
paddle1Img = pygame.transform.scale(paddle1Img,(600, 300))
paddle2Img = pygame.image.load('paddle.png')
paddle2Img = pygame.transform.scale(paddle2Img,(600, 300))
def paddle1(paddle1X, paddle1Y):
screen.blit(paddle1Img,(paddle1X, paddle1Y))
def paddle2(paddle2X, paddle2Y):
screen.blit(paddle2Img, (paddle2X, paddle2Y))
def gameloop():
paddle1X = -90
paddle1Y = 0
paddle2X = width - 125
paddle2Y = 0
gameOver = False
while not gameOver:
for event in pygame.event.get():
if(event.type == pygame.QUIT):
gameOver = True
if(event.type == pygame.MOUSEMOVE):
# i want to add here something that i cant understand that is how to associate paddleImg with mouse movement
screen.fill(white)
paddle1(paddle1X, paddle1Y)
paddle2(paddle2X, paddle2Y)
pygame.display.update()
clock.tick(60)
gameloop()
pygame.quit()
quit()
You have event pygame.MOUSEMOTION to get mouse move.
It has mouse positon event.pos which you can use to set paddle position.
Or you can get event.rel to see how much mouse was moved since previous MOUSEMOTION.
I use Surface to generate paddle so everyone can run it without images.
I use Rect to keep positon because it has not only x and y but also center, left, right, top, bottom, etc. so I can check "collision" with border.
import pygame
# --- constants --- (UPPER_NAMES)
WIDTH = 900
HEIGHT = 600
BLACK = (0 , 0, 0)
WHITE = (255, 255, 255)
# --- classes --- (CamelNames)
# empty
# --- functions --- (lower_names)
# empty
# --- main --- (lower_names)
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# - objects -
paddle1_image = pygame.surface.Surface((100,25))
paddle1_rect = paddle1_image.get_rect(x=90, y=10)
# - mainloop -
clock = pygame.time.Clock()
game_over = False
while not game_over:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.MOUSEMOTION:
# move padle with mouse
mouse_x, mouse_y = event.pos
paddle1_rect.centerx = mouse_x
# - updates (detect collision)-
# keep padle inside window
if paddle1_rect.left < 0:
paddle1_rect.left = 0
elif paddle1_rect.right > WIDTH:
paddle1_rect.right = WIDTH
# - draws -
screen.fill(WHITE)
screen.blit(paddle1_image, paddle1_rect)
pygame.display.update()
# - FPS -
clock.tick(30) # 30 FPS is enough for human eye to see animation
# - end -
pygame.quit()

Categories

Resources