Попытка сделать слизистые бомбы и очистить экран с помощью пробела - PullRequest
2 голосов
/ 04 марта 2020
import pygame

pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
isRunning = True
r = 255
g = 255
b = 255
color = (r, g, b)
gridDraw = 0
mouse_pressed = []

def grid():
    x = 50
    y = 50
    for a in range(10):
        for c in range(10):
            pygame.draw.circle(screen, color, (x, y), 10)
            x += 45
        y += 45
        x = 50

def slime(mPos):
    x = 50
    y = 50
    green = (0,255,0)
    for a in range(10):
        for c in range(10):
            if (mPos[0] <= x+10 and mPos[0] >= x-10) and\
               (mPos[1] <= y+10 and mPos[1] >= y-10):
                pygame.draw.circle(screen, green, (x, y), 10)
                if x + 45 <= 455:
                    pygame.draw.circle(screen, green, (x+45, y), 10)
                if x - 45 >= 45:
                    pygame.draw.circle(screen, green, (x-45, y), 10)
                if y + 45 <= 455:
                    pygame.draw.circle(screen, green, (x, y+45), 10)
                if y - 45 >= 45:
                    pygame.draw.circle(screen, green, (x, y-45), 10)
            x += 45
        y += 45
        x = 50

def bomb(mouse):
    for a in mouse:
        slime(a)
        pygame.draw.circle(screen, (0,200,150), a, 8)

while isRunning:
    event = pygame.event.get()
    for e in event:
        if e.type == pygame.QUIT:
            isRunning = False
        elif e.type == pygame.KEYDOWN:
            if e.type == pygame.K_ESCAPE:
                isRunning = False
        if e.type == pygame.MOUSEBUTTONDOWN:
            mpos = pygame.mouse.get_pos()
            mouse_pressed.append(mpos)
            gridDraw = 0

    if gridDraw == 0:
        grid()
        gridDraw += 1
        bomb(mouse_pressed)




    pygame.display.update()
pygame.quit()

Итак, большую часть первой части задания я выполнил, за исключением того, что я все еще могу нажимать на черные пробелы и не могу понять, как этого не делать. Я думал, что получил правильные ограничения, но, видимо, нет. Я подумываю о том, чтобы щелкнуть правой кнопкой мыши среднюю или большую бомбу, это было бы идеально?

Это моя лаборатория для класса , я наконец смог завершить установку небольших бомб, но я не поставил после того, как я нажму кнопку «Очистка экрана», я все еще могу нажать на черные пробелы.

Ответы [ 2 ]

1 голос
/ 04 марта 2020

Прежде всего вы должны рисовать круги непрерывно в приложении l oop, а не в событии l oop.

Получить текущую позицию музы по pygame.mouse.get_pos и состояние кнопок мыши по pygame.mouse.get_pressed:

mpos = pygame.mouse.get_pos()
mpressed = pygame.mouse.get_pressed()

Оценить, нажата ли левая кнопка мыши (mpressed[0]) и расстояние мыши до центр круга меньше радиуса круга (pygame.math.Vector2.distance_to):

if mpressed[0] and pygame.math.Vector2(x, y).distance_to(mpos) < 10:
    # [...]

См. полный пример:

import pygame

screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
isRunning = True
x, y = 50, 50
r, g, b = 255, 255, 255

while isRunning:
    #Time
    deltaTime = clock.tick() / 1000
    event = pygame.event.get()
    #USER Events
    for e in event:
        if e.type == pygame.QUIT:
            isRunning = False

    mpos = pygame.mouse.get_pos()
    mpressed = pygame.mouse.get_pressed()

    #Draws a grid
    for a in range(50):
        x = a * 50
        for c in range(50):
            y = c * 50
            color = (r, g, b)
            if mpressed[0] and pygame.math.Vector2(x, y).distance_to(mpos) < 10:
                color = (0, g, 0)
            pygame.draw.circle(screen, color, (x, y), 10)

    pygame.display.update()
pygame.quit()
0 голосов
/ 04 марта 2020

Я использовал предыдущий ответ для положения мыши и добавил board_state, чтобы круг остался в желаемом цвете.

 import pygame
 import numpy as np
 import time

 def set_color(board_state):
     if not board_state:
         return 255, 255, 255
     else:
         return 255, 0, 0


 screen = pygame.display.set_mode((500,500))
 clock = pygame.time.Clock()
 isRunning = True
 board_state = np.zeros((50, 50), dtype=np.bool)
 pressed = True

 while isRunning:
     deltaTime = clock.tick() / 1000
     event = pygame.event.get()
     for e in event:
         if e.type == pygame.QUIT:
             isRunning = False

     mpos = pygame.mouse.get_pos()
     mpressed = pygame.mouse.get_pressed()
     for a in range(board_state.shape[0]):
         x = a * 50
         for c in range(board_state.shape[1]):
             y = c * 50
             if mpressed[0] and pygame.math.Vector2(x, y).distance_to(mpos) < 10:
                 board_state[a, c] = not board_state[a, c]
                 print("Kick", a, c, board_state[a, c])
                 pressed = True
             pygame.draw.circle(screen, set_color(board_state[a, c]), (x, y), 10)

     if pressed:
         pygame.display.update()
         time.sleep(0.2)
         pressed = False
 pygame.quit()

Вы можете изменить цвет в функции set_color, и я добавил time.sleep, который необходимо отрегулировать по длине удара, потому что у меня возникли проблемы с обнаружением одного клика с помощью трекпада.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...