How can I add collision between images in python with pygame [duplicate] - python

This question already has answers here:
How do I detect collision in pygame?
(5 answers)
Pygame collision with masks
(1 answer)
Closed 4 months ago.
I'm making a game with pygame where the player has to kill some enemies and if they touch your character it dies, but I don't know how to add collision. I have tried with get_rect() but I can't make it work, because I don't really understand how it works and how I can link it with the images.
(slime is the playable character and bads and bads 2 the enemies)
from pygame import transform
from pygame.display import flip
import random
import pygame.freetype
from pygame.sprite import Sprite
from pygame.rect import Rect
pygame.init()
screen = pygame.display.set_mode((1200,800))
screen.fill("light blue")
clock = pygame.time.Clock()
pygame.display.set_caption("Game")
sky = pygame.Surface((1200,800))
sky.fill("light blue")
ground = pygame.image.load(r"img\suelo.png").convert_alpha()
nube1 = pygame.image.load(r"img\nubes.png").convert_alpha()
posx = -300
posy = 80
nube2 = pygame.image.load(r"img\nubes2.png").convert_alpha()
slime = pygame.image.load(r"img\slime2.png").convert_alpha()
rectx = 320
recty = 520
#enemy
bads = pygame.image.load(r"img\bads.png").convert_alpha()
rect1x = -500
rect1y = 520
bads2 = pygame.image.load(r"img\bads2.png").convert_alpha()
rect2x = 1300
rect2y = 520
jump = False
grav = 8
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(sky,(0,0))
screen.blit(ground,(-60,500))
screen.blit(nube1,(-300,80))
screen.blit(nube2,(250,10))
screen.blit(bads,(rect1x,rect1y))
screen.blit(bads2,(rect2x,rect2y))
screen.blit(slime,(rectx,recty))
step = 4.2
step2 = 2.5
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
pygame.quit()
exit()
if keys[pygame.K_a] and rectx > -200:
rectx -= step
slime = pygame.image.load(r"img\slime3.png")
if keys[pygame.K_d] and rectx < 890:
rectx += step
slime = pygame.image.load(r"img\slime2.png")
if jump == False:
if keys[pygame.K_SPACE]:
jump = True
else:
if grav >= -8:
recty -= grav * 3
grav -= 0.5
else:
grav = 8
jump = False
rect1x += step2
rect2x -= step2
if rect1x > 1090:
rect1x = random.randrange(-1000,-400)
if rect2x < -310:
rect2x = random.randrange(1100,1800)
pygame.display.update()
clock.tick(70)
thks :)

Related

How do I implement sliding window algorithm on an image?

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

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
...

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)
# [...]

rect.collisionrect not working between two rects [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'm having trouble getting my collision to work in my game, I am using two rects, one acting as a paddle and one as a ball. I am using the normal pygame statement, rect1.colliderect(rect2), but for some reason it is not working.
Here is the line of code for the rects collision
#collision of ball with paddle
if (paddle.colliderect(ball)):
ball_x = 10
ball_y = 10
Not sure what's wrong. Here is the full coding if you wanna run it.
#December 16, 2019
#Final Project - Breakout
#IMPORTING LIBRARIES-----
import pygame
import sys
import time
#INITIALIZING SCREEN SIZE-----
pygame.init()
screen_size = (700, 750)
screen = pygame.display.set_mode((screen_size),0)
pygame.display.set_caption("BREAKOUT")
#retrieve screen measurements
screen_w = screen.get_width()
screen_h = screen.get_height()
#retrieve position of center of screen
center_x = int(screen_w/2)
center_y = int(screen_h/2)
#COLOURS-----
WHITE = (255,255,255)
BLACK = (0, 0, 0)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
PURPLE = (154, 136, 180)
#BACKGROUND-----
screen.fill(BLACK)
pygame.display.update()
#SPEED-----
clock = pygame.time.Clock()
FPS = 60 #set frames per second
speed = [4,4]
paddle_speed = 6
#VARIABLES-----
#paddle
paddle_w = 100
paddle_h = 10
paddle_x = 500
paddle_y = 670
paddle_dx = 0
paddle_dy = 0
#ball
ball_w = 10
ball_h = 10
ball_x = center_x
ball_y = center_y
#RECTS-----
paddle = pygame.Rect(paddle_x, paddle_y, paddle_w, paddle_h)
ball = pygame.Rect(ball_x, ball_y, ball_w, ball_h)
#LOOPS-----
game = False
#loop for game
game = True
while game:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
game = False
pygame.quit()
sys.exit()
#moving paddle with keys
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_dx = -paddle_speed
elif event.key == pygame.K_RIGHT:
paddle_dx = paddle_speed
if event.type == pygame.KEYUP:
paddle_dx = 0
#constrain this loop to the specified FPS
clock.tick(FPS)
#PADDLE EVENTS-----
#store old paddle positions
old_paddle_x = paddle.x
old_paddle_y = paddle.y
#moving the paddle rect
paddle.move_ip(paddle_dx, paddle_dy)
#check to see if rect has left screen
if paddle.left < 0 or paddle.right > screen_w:
paddle.x = old_paddle_x
#BALL EVENTS-----
#moving ball
ball = ball.move(speed)
#collision left & right
if ball.left < 0 or ball.right > screen_w:
speed[0] = -speed[0]
#collision top
if ball.top < 0 or ball.bottom > screen_h:
speed[1] = -speed[1]
#collision of ball with paddle
if (paddle.colliderect(ball)):
ball_x = 10
ball_y = 10
#removes screen trail
screen.fill(BLACK)
#drawing paddle/ball inside rect
pygame.draw.rect(screen,PURPLE,paddle,0)
pygame.draw.rect(screen,WHITE,ball,0)
#updating the screen
pygame.display.update()
pygame.quit()
sys.exit()
The position of the ball is defined by the pygame.Rect object ball. ball_x and ball_y is just used to initialize ball.
You have to set ball.x = 10 and ball.y = 10 rather than ball_x = 10 and ball_y = 10:
if paddle.colliderect(ball):
ball.x = 10
ball.y = 10
To make the ball bounce of the paddle you have to invert speed[1] rather than changing the position of the ball by ball.x = 10 and ball.y = 10:
if paddle.colliderect(ball):
speed[1] = -speed[1]
I use this for rect collision :
if not (x1 >= x2 + w2 or x1 + w1 <= x2 or y1 >= y2 + h2 or y1 + h1 <= y2):
collision = True
else:
collision = False

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