Есть ли способ сделать функцию для всего кода, относящегося к рисованию прыгающего мяча в Pygame? - PullRequest
2 голосов
/ 16 февраля 2020

Мяч отскакивает, и я могу нарисовать его, но я хочу нарисовать несколько и заставить их начинать в произвольных местах без необходимости вводить каждый сценарий. Есть ли способ написать функцию для этого?

import pygame
import sys
import random

pygame.init()

screenSize = (800,600)
screen = pygame.display.set_mode(screenSize)
pygame.display.set_caption("Jacob Cardoso Basic Drawing")

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
x = random.randint(50,750)
y = random.randint(50,550)
dx = random.randint(1, 3)
dy = random.randint(-1, 3)

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False
    x = x + dx
    y = y + dy

    if (y <= 50) or (y >= 550):
        dy = -dy
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
    if (x <= 50) or (x >= 750):
        dx = -dx   
        COLOUR = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    screen.fill(WHITE)
    pygame.draw.circle (screen, COLOUR, (x,y), 50, 0)
    pygame.display.update()

pygame.quit()
sys.exit()

1 Ответ

0 голосов
/ 16 февраля 2020

Создать Класс для шаров. Координаты, направление движения и цвет становятся атрибутами экземпляра . Переместите код, который обрабатывает движение, в метод update. Выполните рисование мяча методом draw.

class Ball:
    def __init__(self):
        self.x = random.randint(50,750)
        self.y = random.randint(50,550)
        self.dx = random.randint(1, 3)
        self.dy = random.randint(-1, 3)
        self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def update(self):
        self.x = self.x + self.dx
        self.y = self.y + self.dy
        bounce = False
        if (self.y <= 50) or (self.y >= 550):
            self.dy = -self.dy
            bounce = True
        if (self.x <= 50) or (self.x >= 750):
            self.dx = -self.dx  
            bounce = True
        if bounce: 
            self.color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))

    def draw(self, surf):
        pygame.draw.circle(surf, self.color, (self.x, self.y), 50, 0)

Создайте количество (max_balls) экземпляров мяча в al oop и добавьте их в список (balls), до применения л oop. Обновите положение шариков и нарисуйте их в петлях for в приложении l oop:

# crate the balls
max_balls = 5
balls = []
for _ in range(max_balls):
    balls.append(Ball())

screen.fill(WHITE)
go = True
while go:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            go = False

    # update the ball positions
    for ball in balls:
        ball.update()

    screen.fill(WHITE)
    # draw the balls
    for ball in balls:
        ball.draw(screen)
    pygame.display.update()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...