Avatar r50 a6ce93fe35b158fd29ba0e8681c918c22117160e9586a56eee4ffbc20df9bda1
Programmer

My game

Добавлено 25 мая 2022 в 15:13
import pygame
from random import randrange as rr

w = 1200
h = 800
fps = 30

#paddle settings
paddle_w = 330
paddle_h = 35
paddle_spedd = 15
paddle = pygame.Rect(w // 2 - paddle_w // 2, h - paddle_h - 10, paddle_w, paddle_h)
#ball
ball_r = 20
ball_speed = 6
ball_rect = int(ball_r * 2 ** 0.5)
ball = pygame.Rect(rr(ball_rect, w - ball_rect), h // 2, ball_rect, ball_rect)
dx, dy = 1, -1
#blocks
block_list = [pygame.Rect(10 + 120 * i, 10 + 70 * j, 100, 50)for i in range(10)for j in range(4)]
color_list = [(rr(30, 256), rr(30, 256), rr(30, 256))for i in range(10) for j in range(4)]



black = (0, 0 ,0)
white = (255, 255, 255)
blue = (0, 180, 255)
orange = (255, 150, 0)
red = (255, 0 ,0)

pygame.init()
sc = pygame.display.set_mode((w, h))
clock = pygame.time.Clock()


def detect_collision(dx, dy, ball, rect):
if dx > 0:
delta_x = ball.right - rect.left
else:
delta_x = ball.right - rect.left
if dy > 0:
delta_y = ball.bottom - rect.top
else:
delta_y = ball.bottom - rect.top

if abs(delta_x - delta_y) < 10:
dx, dy =-dx, -dy
elif delta_x > delta_y:
dy = -dy
elif delta_y > delta_x:
dx = -dx
return dx, dy

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
sc.fill(blue)
#drawing
[pygame.draw.rect(sc, color_list[color], block) for color, block in enumerate(block_list)]
pygame.draw.rect(sc, (orange), paddle)
pygame.draw.circle(sc, (red), ball.center, ball_r)
#ball movement
ball.x += ball_speed * dx
ball.y += ball_speed * dy
#walls for ball
if ball.centerx < ball_r or ball.centerx > w - ball_r:
dx = -dx
#third wall
if ball.centery < ball_r:
dy = -dy
#collusion paddle
if ball.colliderect(paddle) and dy > 0:
dx, dy = detect_collision(dx, dy, ball, paddle)
#collusion blocks
hit_index = ball.collidelist(block_list)
if hit_index != -1:
hit_rect = block_list.pop(hit_index)
hit_color = color_list.pop(hit_index)
dx, dy = detect_collision(dx, dy, ball, hit_rect)
#effect
hit_rect.inflate_ip(ball.w * 3, ball.h * 3)
pygame.draw.rect(sc, hit_color, hit_rect)
fps += 5
#game over
if ball.bottom > h:
game = False
exit()
#control
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and paddle.left > 0:
paddle.left -= paddle_spedd
if key[pygame.K_RIGHT] and paddle.right < w:
paddle.right += paddle_spedd


pygame.display.flip()
clock.tick(fps)

C6321aa363