How do I implement sliding window algorithm on an image? - python

I'm making the Super Mario Bros. game on python using the pygame library. I wanted to fit only a portion of the map of mario bros level and I have no idea how am I supposed to do that. One of my seniors told me that I could use the sliding window algorithm. However, the problem is I don't know how to implement this algorithm on the image. If I can get any help that would be really appreciated.mario level world 1-1
I have also been able to print out the map to a suitable scaling:
map on code
edit: I am sorry I did not post my code. here it is:
import pygame
import pygame.transform
i = pygame.init()
X = 640
Y = 480
Window = pygame.display.set_mode ((X, Y))
pygame.display.set_caption ("Game")
Mario_Standing_Left = pygame.image.load("F:\\Mario in Python\\Mario_Standing_Left.png")
Mario_Standing_Right = pygame.image.load("F:\\Mario in Python\\Mario_Standing_Right.png")
x = 50
y = 430
width = 40
height = 60
speed = 5
isjump = False
jumpcount = 10
left = False
right = False
WalkCount = 0
ScreenWidth = X - width - speed
ScreenHeight = Y - height - speed
isjump = False
jumpcount = 10
run = True
while run:
pygame.time.delay (50) #time in pygame measured in milliseconds
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > speed:
x -= speed
if keys[pygame.K_RIGHT] and x <= ScreenWidth:
x += speed
if not (isjump):
if keys[pygame.K_SPACE]:
isjump = True
else:
if jumpcount >= -10:
neg = 1
if jumpcount < 0:
neg = -1
y -= (jumpcount ** 2) * 0.5 * neg
jumpcount -= 1
else:
isjump = False
jumpcount = 10
Window.fill ((0,0,0))
#(surface, (the window defined above, (colour), (the object being drawn)))
pygame.display.update()
world = pygame.image.load('World 1-1.png').convert()
world = pygame.transform.smoothscale(world,(8750,1400))
while True:
Window.blit(world,(0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()

You should use area in blit(..., area=...) to display only some part of world
I use area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT) to keep information what area to display. And I change area.x to scroll it right and left.
import pygame
# --- constants --- # PEP8: all constants directly after imports
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
# --- main --- # PEP8: `lower_case_names` for variables
pygame.init()
window = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT))
world_image = pygame.image.load('World 1-1.png').convert()
world_image = pygame.transform.smoothscale(world_image, (8750,1400))
world_rect = world_image.get_rect()
area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT)
direction = 'right'
# - mainloop -
clock = pygame.time.Clock()
run = True
while run:
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
if direction == 'right':
# move right
area.x += 2
# change direction
if area.right > world_rect.right:
area.right = world_rect.right
direction = 'left'
else:
# move left
area.x -= 2
# change direction
if area.left < world_rect.left:
area.left = world_rect.left
direction = 'right'
#window.fill((0, 0, 0))
window.blit(world_image, (0,0), area=area)
pygame.display.flip()
clock.tick(FPS) # keep speed 60 FPS (Frames Per Second)
# - end -
pygame.quit()
PEP 8 -- Style Guide for Python Code
EDIT:
If you will have other elements then you may need to create Surface with size of world to blit world and other elements before on this surface and later display it in window using area.
import pygame
# --- constants ---
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
# --- main --- # PEP8: `lower_case_names` for variables
pygame.init()
window = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT))
window_rect = window.get_rect()
world_image = pygame.image.load('World 1-1.png').convert()
world_image = pygame.transform.smoothscale(world_image, (8750,1400))
world_rect = world_image.get_rect()
player_image = pygame.Surface((40, 40))
player_image.fill((255, 0, 0)) # red
player_rect = player_image.get_rect(centerx=window_rect.centerx, centery=window_rect.centery+300 )
area = pygame.Rect(0, 300, SCREEN_WIDTH, SCREEN_HEIGHT)
direction = 'right'
buffer = pygame.Surface(world_rect.size)
# - mainloop -
clock = pygame.time.Clock()
run = True
while run:
for event in pygame.event.get ():
if event.type == pygame.QUIT:
run = False
if direction == 'right':
# move right
area.x += 5
player_rect.x += 5
# change direction
if area.right > world_rect.right:
area.x -= 5
player_rect.x -= 5
#area.right = world_rect.right
direction = 'left'
else:
# move left
area.x -= 5
player_rect.x -= 5
# change direction
if area.left < world_rect.left:
area.x += 5
player_rect.x += 5
#area.left = world_rect.left
direction = 'right'
#player_rect.center = area.center
buffer.blit(world_image, (0,0))
buffer.blit(player_image, player_rect)
# ---
#window.fill((0, 0, 0))
window.blit(buffer, (0,0), area=area)
pygame.display.flip()
clock.tick(FPS) # keep speed 60 FPS (Frames Per Second)
# - end -
pygame.quit()

Related

How to move a sprite in pygame left and right without key pressing like moving alone like animation [duplicate]

I learned how to print image in pygame, but I don't know how to make a dynamic position(It can change the image position by itself). What did I miss? Here's my attempt.
import pygame
screen_size = [360,600]
screen = pygame.display.set_mode(screen_size)
background = pygame.image.load("rocketship.png")
keep_alive = True
while keep_alive:
planet_x = 140
o = planet_x
move_direction = 'right'
if move_direction == 'right':
while planet_x == 140 and planet_x < 300:
planet_x = planet_x + 5
if planet_x == 300:
planet_x = planet_x - 5
while planet_x == 0:
if planet_x == 0:
planet_x+=5
screen.blit(background, [planet_x, 950])
pygame.display.update()
You don't need nested loops to animate objects. You have one loop, the application loop. Use it! You need to redraw the entire scene in each frame. Change the position of the object slightly in each frame. Since the object is drawn at a different position in each frame, the object appears to move smoothly.
Define the path the object should move along by a list of points and move the object from one point to another.
Minimal example
import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
corner_points = [(100, 100), (300, 300), (300, 100), (100, 300)]
pos = corner_points[0]
speed = 2
def move(pos, speed, points):
direction = pygame.math.Vector2(points[0]) - pos
if direction.length() <= speed:
pos = points[0]
points.append(points[0])
points.pop(0)
else:
direction.scale_to_length(speed)
new_pos = pygame.math.Vector2(pos) + direction
pos = (new_pos.x, new_pos.y)
return pos
image = pygame.image.load('bird.png').convert_alpha()
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pos = move(pos, speed, corner_points)
image_rect = image.get_rect(center = pos)
window.fill(0)
pygame.draw.lines(window, "gray", True, corner_points)
window.blit(image, image_rect)
pygame.display.update()
pygame.quit()
exit()

pygame.MOUSEBUTTONDOWN only working every few times [duplicate]

This question already has an answer here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 5 months ago.
I'm trying to create a game in pygame where you are a rectangle trying to shoot a bullet towards another rectangle, when you click a mousebutton. I'm using this with the pygame.MOUSEBUTTONDOWN, as you can see here:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and ammunition > 0:
bullets.append(Bullet(*bullet_pos))
ammunition -= 1
**I'll include more code for reference later.
However, when I click the mouse button, it only shoots a bullet every few times I click. I checked multiple times, and there doesn't seem to be a pattern of when it does/doesn't shoot. It shoots about every 4-5 times, but that's just an estimate.
Full code, for reference:
import pygame
import math
import random
import time
pygame.init()
# Setting all variables to use later \/
width, height = 798, 552
white = pygame.Color('white')
black = pygame.Color('black')
green = pygame.Color('green')
blue = pygame.Color('blue')
red = pygame.Color('red')
grey = pygame.Color('gray')
yellow = pygame.Color('yellow')
orange = pygame.Color('orange')
azure = pygame.Color('azure')
size_x = 100
size_y = 50
pos_x = 100
pos_y = 275
size_x_2 = 100
size_y_2 = 50
pos_x_2 = random.randint(0, 798)
pos_y_2 = random.randint(0, 552)
pos_x_3 = random.randint(0, 798)
pos_y_3 = random.randint(0, 552)
window = pygame.display.set_mode((width, height))
bullet_pos_y = random.randint(0, 552)
bullet_pos_x = 798
ammunition = 5
enemy_health = 1000
player_health = 50
font = pygame.font.SysFont('Times New Roman', 32)
shooting_x = 0
shooting_y = 0
# Setting All Variables to use later /\
class Bullet:
def __init__(self, x, y):
self.pos = (x, y)
self.dir = (shooting_x - x, shooting_y - y)
length = math.hypot(*self.dir)
if length == 0.0:
self.dir = (0, -1)
else:
self.dir = (self.dir[0]/length, self.dir[1]/length)
angle = math.degrees(math.atan2(-self.dir[1], self.dir[0]))
self.bullet = pygame.Surface((27.5, 17.5)).convert_alpha()
self.bullet.fill((red))
self.bullet = pygame.transform.rotate(self.bullet, angle)
self.speed = 1
def update(self):
self.pos = (self.pos[0] + self.dir[0] * self.speed, self.pos[1] + self.dir[1] * self.speed)
def draw(self, surf):
bullet_rect = self.bullet.get_rect(center = self.pos)
surf.blit(self.bullet, bullet_rect)
bullets = []
keys = pygame.key.get_pressed()
# EVERYTHING BELOW THIS IS IN THE GAME LOOP, EVERYTHING ABOVE ISN'T
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(black)
# Drawing Everything
character = pygame.draw.rect(window, white, (pos_x, pos_y, size_x, size_y))
enemy = pygame.draw.rect(window, blue, (shooting_x, shooting_y, size_x, size_y))
coin = pygame.draw.circle(window, yellow, [pos_x_2, pos_y_2], 15)
# Setting Text
enemy_health_text = font.render(str(enemy_health), True, white, blue)
enemy_health_textRect = enemy_health_text.get_rect()
enemy_health_textRect.center = (enemy.center)
player_health_text = font.render(str(player_health), True, black, white)
player_health_textRect = enemy_health_text.get_rect()
player_health_textRect.center = (character.center[0] + 9, character.center[1])
ammunition_text = font.render("ammunition remaining: " + str(ammunition), True, azure, black)
ammunition_textRect = ammunition_text.get_rect()
ammunition_textRect.center = (205, 25)
bullet_pos = character.center
enemy_pos = enemy.center
# Shooting a bullet
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and ammunition > 0:
bullets.append(Bullet(*bullet_pos))
ammunition -= 1
# Enemy Dealing Damage to Player
if enemy.colliderect(character):
player_health -= 1
white = pygame.Color('red')
if not enemy.colliderect(character):
player_health -= 0
white = pygame.Color('white')
mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()
pos_x, pos_y = pygame.mouse.get_pos()
# If Character collides with coin
if character.colliderect(coin):
pos_x_2 = random.randint(0, 798)
pos_y_2 = random.randint(100, 552)
num = random.randint(0, 20)
if num == 17:
yellow = pygame.Color('purple')
ammunition += 5
if num != 17:
yellow = pygame.Color('yellow')
ammunition += 2
elif enemy.colliderect(coin):
pos_x_2 = random.randint(0, 798)
pos_y_2 = random.randint(100, 552)
enemy_health += 3
# Setting the Enemy Movement
if shooting_x < pos_x_2:
shooting_x += 0.1
if shooting_x > pos_x_2:
shooting_x -= 0.1
if shooting_y < pos_y_2:
shooting_y += 0.1
if shooting_y > pos_y_2:
shooting_y -= 0.1
# Updating/Drawing Bullets
for bullet in bullets:
bullet.update()
''' WORK ON THIS '''
if not window.get_rect().collidepoint(bullet.pos):
bullets.remove(bullet)
for bullet in bullets:
bullet.draw(window)
# Making sure the player doesn't leave boundaries
if pos_y >= 552:
pos_y = 552
if pos_y <= 0:
pos_y = 0
if pos_x <= 0:
pos_x = 0
if pos_x >= 700:
pos_x = 700
# Drawing all text on screen
window.blit(ammunition_text, ammunition_textRect)
window.blit(enemy_health_text, enemy_health_textRect)
window.blit(player_health_text, player_health_textRect)
pygame.display.update()
The function pygame.event.get() returns an object with all events that happens. It clears all events afterwards so nothing will be executed twice when an event occurs. So you shouldn't call it twice without checking all needed events both times. Some events might get ignored when you don't call pygame.event.get() often because it has a limit of 128 events.
As a solution you can save the events in a variable (Some events might be delayed):
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
run = False
...
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and ammunition > 0:
bullets.append(Bullet(*bullet_pos))
ammunition -= 1
Or you only have one event loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN and ammunition > 0:
bullets.append(Bullet(*bullet_pos))
ammunition -= 1
...

Moving bullet in Pygame

I'm making a simple game in pygame, in which you're supposed to dodge or shoot the targets that descend through the screen. So far, I've created the ship and managed to set the movement of both the bullet and the ship, as for their key bindings. However, the bullet's x coordinate doesn't seem to change at all, even though I've defined in the init method in the bullet class that the bullet x coordinate is equal to the ship x coordinate, therefore, the bullet would always be leaving the ship's position. Instead, the bullet always leaves the middle of the screen. I can't find the issue. Any help would be very much appreciated
import pygame, sys
pygame.init()
clock = pygame.time.Clock()
screen_width = 600
screen_height = 800
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Space Race Game")
class ROCKET:
def __init__(self):
self.rocketImg = pygame.image.load("spaceship.png")
self.rocket_x = screen_width/2 - 32
self.rocket_y = screen_height/2 + 100
def draw_rocket(self):
screen.blit(self.rocketImg, (self.rocket_x, self.rocket_y))
def move_rocket(self):
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and self.rocket_x + 15 > 0:
self.rocket_x -= 5
if key[pygame.K_RIGHT] and self.rocket_x < screen_width - 40:
self.rocket_x += 5
class BULLET(ROCKET):
def __init__(self):
super().__init__()
self.bullet_width = 10
self.bullet_height = 20
self.bullet_x = self.rocket_x + 25
self.bullet_y = self.rocket_y
self.move = [0, 0]
self.bullet_speed = 5
self.bullet_rect = pygame.Rect(self.bullet_x, self.bullet_y, self.bullet_width, self.bullet_height)
def draw_bullet(self):
key = pygame.key.get_pressed()
if key[pygame.K_SPACE]:
self.bullet_x = self.rocket_x
self.move[1] = -1
self.bullet_y += self.move[1] * self.bullet_speed
self.bullet_rect.topleft = (self.bullet_x, self.bullet_y)
if self.bullet_y < self.rocket_y - 10:
pygame.draw.rect(screen, (0, 0, 0), self.bullet_rect)
if self.bullet_y < - 20:
self.bullet_y = self.rocket_y
self.move[1] = 0
rocket = ROCKET()
bullet = BULLET()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255))
rocket.draw_rocket()
rocket.move_rocket()
bullet.draw_bullet()
pygame.display.flip()
clock.tick(60)
You have to set the x-coordinate of the bullet by the current x-coordinate of the rocket.
Add an argument rocket to the method draw_bullet of the class BULLET. Make sure that you can only fire the bullet if the bullet has not yet been fired (self.move[1] == 0). Compute the center of the rocket and set the position of the bullet (rocket.rocket_x + self.rocketImg.get_width() // 2):
class BULLET(ROCKET):
# [...]
def draw_bullet(self, rocket):
key = pygame.key.get_pressed()
if key[pygame.K_SPACE] and self.move[1] == 0:
rocket_center_x = rocket.rocket_x + self.rocketImg.get_width() // 2
self.bullet_x = rocket_center_x - self.bullet_width // 2
self.move[1] = -1
# [...]
Passe the instance of ROCKET to the method draw_bullet:
while True:
# [...]
bullet.draw_bullet(rocket)
# [...]
If you want to fire multiple bullets, see the answers to the questions:
How can i shoot a bullet with space bar?
How do I stop more than 1 bullet firing at once?

Pygame jump animation not working - though walking is

Okay, so I was able to add walking animations to the right and the left on my main file, but when I basically copy/pasted/changed the names for adding jump, it doesn't work.
I went ahead and made a copy of my main file, just without the walking animations. I went ahead and tried just doing the jump animation, and even though I copied everything from the same tutorial as I used for the walking, it still doesn't work.
I've been trying to figure this out since last night from like 8 pm. Is there a different way for jump animations to work? See below for the code of THE COPY, so no walking animations. I get no errors, the player can walk left and right, and jump as well.
import pygame
import os
x = 90
y = 60
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x, y)
def player_jump_animation():
"""Adding collision block to each right jump animation"""
new_player = player_frames_jump[player_jump_index]
new_player_rect = new_player.get_rect(
center=(player_rect.centerx, player_rect.centery))
return new_player, new_player_rect
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
clock = pygame.time.Clock()
player_movement = 720
isJump = False
jumpCount = 10
bg_surface = pygame.image.load('assets/camp_bg.png').convert()
bg_surface = pygame.transform.scale2x(bg_surface)
player_idle = pygame.transform.scale2x(pygame.image.load(
'assets/IDLE_000.png').convert_alpha())
player_jump0 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_000.png').convert_alpha())
player_jump1 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_001.png').convert_alpha())
player_jump2 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_002.png').convert_alpha())
player_jump3 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_003.png').convert_alpha())
player_jump4 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_004.png').convert_alpha())
player_jump5 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_005.png').convert_alpha())
player_jump6 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_006.png').convert_alpha())
player_frames_jump = [player_jump0, player_jump1, player_jump2,
player_jump3, player_jump4, player_jump5, player_jump6]
player_jump_index = 3
player_surface = player_frames_jump[player_jump_index]
player_rect = player_surface.get_rect(center=(300, 512))
PLAYERJUMP = pygame.USEREVENT
pygame.time.set_timer(PLAYERJUMP, 120)
run = True
while run:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == PLAYERJUMP:
if player_jump_index < 6:
player_jump_index += 1
else:
player_jump_index = 0
# Setting jump animation
player_jump, player_rect = player_jump_animation()
if keys[pygame.K_LEFT] and player_rect.centerx > 0 + 35:
# If I speed up, player looks like sliding
player_rect.centerx -= 5
if keys[pygame.K_RIGHT] and player_rect.centerx < 1000 - 35:
# If I speed up, player looks like sliding
player_rect.centerx += 5
if not(isJump):
if keys[pygame.K_UP]:
isJump = True
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
player_movement -= (jumpCount ** 2) * 0.1 * neg
jumpCount -= 0.5
# This will execute when jump is finished
else:
# Resetting Variables
jumpCount = 10
isJump = False
pygame.display.update()
clock.tick(60)
screen.blit(bg_surface, (0, 0))
player_rect.centery = player_movement
screen.blit(player_idle, player_rect)
pygame.quit()
You have to draw the Surface referenced by player_jump, if the player is jumping:
while run:
# [...]
screen.blit(bg_surface, (0, 0))
player_rect.centery = player_movement
if isJump:
screen.blit(player_jump, player_rect)
else:
screen.blit(player_idle, player_rect)
# [...]

Problem with simple python game using a pygame libray

I'm new at Python and Pygame and I started making a simple game, something like a tennis game, but every time ball is under the rectangle jumping +-5 pixels and blocking. I think the problem is with pXY and bXY.
import sys, pygame
from pygame.locals import *
pygame.init()
pygame.display.set_mode((500,500)) # ustawiwanie wielkosci
pygame.display.set_caption(("little shit")) #ustawianie nazwy
okienko = pygame.display.get_surface() # pobieranie płaszczyzny
# obiekt
prostokat = pygame.Surface((80,20)) # tworzenie prostokąta / tulpa, szerokość / wysokość
prostokat.fill((128, 15, 220)) # zmiana koloru prostokąta / r:g:b
pXY = prostokat.get_rect() # pobranie wymiarów prostokąta
pXY.x = 225 # wartość x
pXY.y = 460 # wartość y
kolko = pygame.image.load("./ball.png")
bXY = kolko.get_rect()
bXY.x = 120 # POŁOŻENIE OBIEKTU
bXY.y = 200 # POŁOŻENIE OBIEKTU
bx,by = 5,5 # o ile sie przesuwamy
px = 3
bAB = kolko.get_rect()
bA = 25
bB = 25
kolko = pygame.transform.scale(kolko,(bA,bB))
pygame.display.flip() # wyświetlenie/odrysowanie całego okna
fps = pygame.time.Clock() # ile czasu minęło od wykonywania instrukcji
while True:
okienko.fill((128, 128, 128)) # zmiana koloru płaszczyzny na szary
pXY.x += px
if pXY.x > 420 or pXY.x < 0:
px *= -1
okienko.blit(prostokat, pXY)
bXY.x +=bx
if bXY.x > 475 or bXY.x < 0:
bx*= -1
bXY.y +=by
if bXY.y > 475 or bXY.y < 0:
by*= -1
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
okienko.blit(kolko, bXY)
pygame.display.update() # update okienka
fps.tick(30) # odswiezanie obrazu, 30 fps
for zdarzenie in pygame.event.get():
if zdarzenie.type == pygame.QUIT:
pygame.quit()
exit()
if zdarzenie.type == KEYDOWN:
if zdarzenie.key == K_LEFT:
px=-7
if zdarzenie.key == K_RIGHT:
px=7
while True: # pętla do zamykania okienka
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
When the ball is under the rectangle, jumping +- 5 pixels and blocking, the ball can't leave this area when is on the left
Your collision detection logic will not give physically accurate results. For example, no matter where the ball collides with the paddle it will always start moving downward at 5 pixels/frame. This means that the ball will pass through the paddle when it collides hits from above but it will 'bounce' if it hits from below. That is what causes the ball to behave the way it does. This line is where the velocity is set if the paddle and ball are colliding:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
A slightly better approach would be to reverse the direction of the ball if it collides with the paddle. But this still makes the ball only reverse direction in the y-axis no matter where on the paddle the ball collides (top, bottom, left, right). The code above can be changed to this code to get this effect:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by*=-1
This final chunk of code is cleaned up a bit and translated to English. It uses the second block of code from above to bounce the ball off the paddle:
import sys
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
pygame.display.set_caption('new caption')
paddle = pygame.Surface((80, 20))
paddle.fill((128, 15, 220))
paddle_rect = paddle.get_rect()
paddle_rect.x = 225
paddle_rect.y = 460
ball = pygame.Surface((25, 25))
ball.fill((255, 0, 0))
ball_rect = ball.get_rect()
ball_rect.x = 120
ball_rect.y = 200
ball_velocity_x = 5
ball_velocity_y = 5
paddle_velocity_x = 3
clock = pygame.time.Clock()
while True:
# event processing code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_velocity_x = -7
elif event.key == pygame.K_RIGHT:
paddle_velocity_x = 7
# update code
# update the position of the paddle and bounce it off the edges of the window
paddle_rect.x += paddle_velocity_x
if paddle_rect.x > 420 or paddle_rect.x < 0:
paddle_velocity_x *= -1
# update the position of the ball and bounce it off th eedges of the window
ball_rect.x += ball_velocity_x
ball_rect.y += ball_velocity_y
if ball_rect.x > 475 or ball_rect.x < 0:
ball_velocity_x *= -1
if ball_rect.y > 475 or ball_rect.y < 0:
ball_velocity_y *= -1
if paddle_rect.colliderect(ball_rect):
ball_velocity_y *= -1
# drawing code
window.fill((128, 128, 128))
window.blit(paddle, paddle_rect)
window.blit(ball, ball_rect)
pygame.display.update()
clock.tick(30)

Categories

Resources