How to scroll image with mouse in pygame? - python

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

Related

How to stop my rect from leaving a trail when moving over my background image

I am making a pong game and the ball object leaves a trail when it moves and I was wondering how to stop it from doing this any help would be greatly appreciated. Thank you in advance.
Here is my code:
import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
# screen setup
screen_width = 1200
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
background = pygame.image.load("spacebackground.png").convert_alpha()
pygame.mouse.set_visible(False)
pygame.display.set_caption('pong')
# set up player and opponent and ball rect
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
opponent = pygame.Rect(10,screen_height/2 - 70,10,140 )
ball = pygame.Rect(screen_width/2-15, screen_height/2 - 15,30, 30)
ball_speed_x = 7
ball_speed_y = 7
# defining clock and colour
red = (0,0,0)
clock = pygame.time.Clock()
while True:
pygame.display.update(ball)
pygame.display.flip()
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
ball.x += ball_speed_x
ball.y += ball_speed_y
# Drawing the rects
pygame.draw.rect(background, red, player)
pygame.draw.rect(background, red, opponent)
pygame.draw.ellipse(background, red, ball)
pygame.display.update(ball)
clock.tick(60)
Draw the objects on the screen instead of on the background:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
ball.x += ball_speed_x
ball.y += ball_speed_y
# draw background on the screen
screen.blit(background, (0, 0))
# draw objects on the screen
pygame.draw.rect(screen, red, player)
pygame.draw.rect(screen, red, opponent)
pygame.draw.ellipse(screen, red, ball)
# update the display
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()

surface doesn't disappear at the next frame

I'm pretty new to Python and programming in general.
I'm trying to draw a square (200px by 200px) on the screen when the user clicks on the screen.
I tried to create a surface and a rect around the surface ( when the user clicks on the screen) and then using the rect, placed the surface on the screen using the blit method.
for the x and y of the rect I used mouse position.
So, this in my head should have changed the position of the square whenever a user clicks somewhere else on the screen but it rather creates a new square every time.
so I have a couple of questions:
If the way I'm implementing this is wrong, then how can I implement this feature?
Shouldn't the square change place as Pygame draws it every frame?
Thank you :)
pygame.init()
# --- Column --------------- #
col_num = 8
col_size = 120
# --- Screen --------------- #
screen = pygame.display.set_mode((col_num * col_size, col_num * col_size))
screen.fill((255, 255, 255))
draw_board()
# --- Clock ---------------- #
clock = pygame.time.Clock()
white_player = Player()
# --- test surface --------- #
surface = pygame.Surface((200, 200))
surface.fill((255, 255, 255))
# --- Main Loop ------------ #
check = False
while True:
white_player.draw_piece()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(), sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
check = True
a_rect = surface.get_rect(center=pygame.mouse.get_pos())
print('here!')
if check:
screen.blit(surface, a_rect)
pygame.display.update()
clock.tick(60)
Output:
Even trying with a simple surface and a screen it doesn't work.
It adds another surface to the screen with the new x.
import pygame as pg
import sys
pg.init()
screen = pg.display.set_mode((400, 400))
clock = pg.time.Clock()
surface = pg.Surface((200, 200))
surface.fill((255, 255, 255))
xpos = 50
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit(), sys.exit()
xpos += 1
screen.blit(surface, (xpos, 100))
pg.display.flip()
clock.tick(60)
Oh, I just realized I forgot to fill the screen before each frame. fixed

Pygame sprite creating duplicate instead of moving

I am fairly new to Pygame.
I am attempting to re-create Pong in Python using Pygame, but I have hit a roadblock.
Here is my code:
import pygame
pygame.init()
UP = "up"
DOWN = "down"
white = (255,255,255)
black = (0,0,0)
pygame.mouse.set_visible(True)
resolution = (800,600)
window = pygame.display.set_mode(resolution)
pygame.display.set_caption("Pong!")
clock = pygame.time.Clock()
sprites_list = pygame.sprite.Group()
running = True
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((25,100))
self.image.fill(white)
pygame.draw.rect(self.image,white, (0,0,25,100))
self.rect = self.image.get_rect()
def move(self,direction,pixels):
if direction == DOWN:
self.rect.y -= pixels
if direction == UP:
self.rect.y += pixels
player1 = Paddle()
player1.rect.x = 0
player1.rect.y = 200
sprites_list.add(player1)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
player1.move(DOWN, 5)
if keys[pygame.K_UP]:
player1.move(UP, 5)
sprites_list.update()
sprites_list.draw(window)
pygame.display.flip()
clock.tick(60)
pygame.quit()
I am trying to make player1, a Paddle object, move up or down depending on which key is pressed. When I run this code, player1 is stretched out after the up or down arrows are pressed; 5 pixels are added onto player1.rect.
What am I doing wrong and why will sprites_list.update() not put player1 in its new position?
You have to clear screen before you draw elements in new loop.
You can fill window with black color window.fill((0,0,0)) or draw background image in every loop.
This is your code after reorganization and adding window.fill(BLACK)
import pygame
# --- constants --- (UPPER_CASE_NAMES)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
UP = "up"
DOWN = "down"
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# --- classes ---- (CamelCaseNames)
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((25,100))
self.image.fill(WHITE)
# you don't have to draw white rect if all surface already is white
#pygame.draw.rect(self.image,white, (0,0,25,100))
self.rect = self.image.get_rect()
def move(self, direction, pixels):
if direction == DOWN:
self.rect.y += pixels
if direction == UP:
self.rect.y -= pixels
# --- functions --- (lower_case_names)
# empty
# --- main --- (lower_case_names)
# - init -
pygame.init()
pygame.mouse.set_visible(True)
window = pygame.display.set_mode(resolution)
pygame.display.set_caption("Pong!")
# - objects -
sprites_list = pygame.sprite.Group()
player1 = Paddle()
player1.rect.x = 0
player1.rect.y = 200
sprites_list.add(player1)
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
player1.move(DOWN, 5)
if keys[pygame.K_UP]:
player1.move(UP, 5)
# - updates (without draws) -
sprites_list.update()
# - draws (without updates) -
window.fill(BLACK) # <--- clear screen
sprites_list.draw(window)
pygame.display.flip()
clock.tick(60)
# - end -
pygame.quit()

PyGame Mouse Cursor Center of Player Image

Have just started using PyGame in Python. I have managed to set the player_image to follow the mouse cursor, but the image is not centred over the position of the cursor. The cursor always seems to be in the top left corner of the image. Could anyone help me with getting it so that the image is over the centre of the mouse cursor? I can then turn the mouse cursor off and the image track the movement correctly.
I have the below section of code so far, with a background set in the pygame window:
player_image = pygame.image.load("spaceship.png").convert_alpha()
player_image_rect = player_image.get_rect()
player_image_rect.centerx = player_image.get_rect().centerx
player_image_rect.centery = player_image.get_rect().centery
screen.blit(player_image, player_image_rect)
pygame.mouse.set_visible(True)
Thanks
Full code (I've slowly been adding in mixture of features):
import sys
import pygame
import random
black = (0, 0, 0)
white = (255, 255, 255)
# Initialise PyGame
pygame.init()
#Set screen dimensions and title
width = 802
height = 585
screen=pygame.display.set_mode([width, height])
pygame.display.set_caption("Space Attack Game v1")
#Load and set up graphics position
background_position = [0, 0]
background_image = pygame.image.load("solarsystem.jpg").convert()
#Set game title on screen text
basicfont = pygame.font.SysFont(None, 68)
text = basicfont.render('Space Attack', True, white).convert_alpha()
text_rect = text.get_rect()
#textrect.centerx = screen.get_rect().centerx
#textrect.centery = screen.get_rect().centery
#Set player mouse control image
player_image = pygame.image.load("spaceship.png").convert_alpha()
player_image_rect = player_image.get_rect()
pos = pygame.mouse.get_pos()
player_image_rect.center = pos
#player_image_rect.centerx = player_image.get_rect().centerx
#player_image_rect.centery = player_image.get_rect().centery
screen.blit(player_image, player_image_rect.center)
pygame.mouse.set_visible(True)
#Load star
star_image = pygame.image.load("star.png").convert_alpha()
screen.blit(star_image, (random.randint(0,width),random.randint(0,height)) )
#star_image_rect = star_image.get_rect()
pygame.display.flip()
#######################################################
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.blit(star_image, (random.randint(0,width),random.randint(0,height)))
class ball:
def __init__(self,X,Y):
self.velocity = [1,1]
self.ball_image = pygame.image.load('alien.png').convert()
self.ball_image.set_colorkey(black)
self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
self.screen = pygame.display.get_surface()
#self.sound = pygame.mixer.Sound ('Collide.wav')
if __name__ =='__main__':
num_balls = 5
ball_list = []
for i in range(num_balls):
ball_list.append( ball(random.randint(0, width),random.randint(0, height)) )
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
for ball in ball_list:
if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
#ball.sound.play()
ball.velocity[0] = -1 * ball.velocity[0]
if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
#ball.sound.play()
ball.velocity[1] = -1 * ball.velocity[1]
ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
screen.blit (ball.ball_image, ball.ball_boundary)
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
pygame.display.flip()
screen.blit(background_image, background_position)
screen.blit(text, text_rect)
screen.blit(player_image, [x,y])
pygame.quit()
Just set the center of your Rect to the mouse position, like
pos = pygame.mouse.get_pos()
player_image_rect.center = pos

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