Как сделать так, чтобы предыдущая строка исчезла в python? - PullRequest
1 голос
/ 08 мая 2020

Я создаю созвездие, которое начинается с точки (0,0). Предыдущая строка должна исчезнуть после двухсекундной задержки, а при щелчке левой кнопкой мыши в течение двухсекундной задержки должны появиться белые кружки. Я не знаю, почему у меня не работает таймер, и не знаю, как заставить линию исчезнуть. Также не появляются круги. Это мой код

from pygame import * 
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
WHITE = (255,255,255)
colors = (RED,GREEN,BLUE)
time.set_timer(USEREVENT, 2000)
mx = 0
my = 0

def drawScene(screen, button):
 if button == 1:
  draw.circle(screen,RED,(mx,my), 5)
  draw.line(screen,RED,(mx,my),(lx,ly),2)
  draw.circle(screen,RED,(lx,ly), 5)
  display.flip()
 if button == 3:
  draw.line(screen,random.choice(colors),(mx,my),(lx,ly),2)
  draw.circle(screen,random.choice(colors),(lx,ly), 5)
  display.flip()


running = True
myClock = time.Clock()
start = time.get_ticks()
# Game Loop
while running:
 lx = mx
 ly = my 
 for evnt in event.get():             # checks all events that happen
  if evnt.type == QUIT:
   running = False
  if evnt.type == MOUSEBUTTONDOWN:
   mx,my = evnt.pos
   button = evnt.button
   cx,cy = mouse.get_pos()
   draw.circle(screen,WHITE,(cx,cy),5)
  if evnt.type == USEREVENT:
   my_event = event.Event(USEREVENT)
   time.set_timer(my_event , 2000)   
 drawScene(screen, button)

 myClock.tick(60)                     # waits long enough to have 60 fps



quit()

Ответы [ 2 ]

1 голос
/ 08 мая 2020

Это не полное решение, но я дам вам общее представление о том, как начать

Создайте список раз и список строк:

lines = []

Получить текущее время в основном приложении l oop:

current_time = pygame.time.get_ticks()

При щелчке мышью вычислите время, когда линия должна исчезнуть (current_time + 2000), и вычислите случайный цвет.
Добавьте Словарь с начальной точкой, конечной точкой, временем, когда линия должна исчезнуть и цветом в список строк.
Если список строк пуст, то начальная точка строки составляет (0, 0), иначе начальная точка является конечной точкой последней строки в списке:

if event.type == pygame.MOUSEBUTTONDOWN:
    disappear_time = current_time + 2000
    line_color = random.choice(colors)
    prev_pt = (0, 0) if len(lines) == 0 else lines[-1]['end'] 
    lines.append({'start': prev_pt, 'end': event.pos, 'time': disappear_time, 'color': line_color})

Когда текущее время превышает время, которое хранится во времени, удалите точка и время образуют списки линий:

if len(times) > 0 and current_time > times[0]:
    del lines[0]

Нарисуйте линии и кружки в al oop:

screen.fill(BLACK)
for li in lines:
    pygame.draw.line(screen, li['color'], li['start'], li['end'], 2)
    pygame.draw.circle(screen, li['color'], li['start'], 5)
    pygame.draw.circle(screen, li['color'], li['end'], 5)

См. пример:

import pygame
import random

pygame.init()
size = width, height = 700, 700
screen = pygame.display.set_mode(size)

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
WHITE = (255,255,255)
colors = (RED,GREEN,BLUE)
lines = []

running = True
myClock = pygame.time.Clock()

while running:
    current_time = pygame.time.get_ticks()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            disappear_time = current_time + 2000
            line_color = random.choice(colors)
            prev_pt = (0, 0) if len(lines) == 0 else lines[-1]['end'] 
            lines.append({'start': prev_pt, 'end': event.pos, 'time': disappear_time, 'color': line_color})

    if len(lines) > 0 and current_time > lines[0]['time']:
        del lines[0]

    screen.fill(BLACK)
    for li in lines:
        pygame.draw.line(screen, li['color'], li['start'], li['end'], 2)
        pygame.draw.circle(screen, li['color'], li['start'], 5)
        pygame.draw.circle(screen, li['color'], li['end'], 5)
    pygame.display.flip()
    myClock.tick(60)

quit()
1 голос
/ 08 мая 2020

Надеюсь, это именно то, что вы хотели, и комментарии ясны.

from pygame import * 
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)

BLACK  = (0,       0,    0)
RED    = (255,     0,    0)
GREEN  = (0,     255,    0)
BLUE   = (0,       0,  255)
WHITE  = (255,   255,  255)
colors = (RED, GREEN, BLUE)
time.set_timer(USEREVENT, 2000)
mx = 0
my = 0

def drawScene(screen, button, prev_point, new_point):
  if button == 1:
    draw.circle(screen, RED,   prev_point, 5)
    draw.circle(screen, WHITE, new_point,  5)
    draw.line  (screen, RED,   prev_point, new_point, 2)
    display.flip()
  if button == 3:
    draw.line  (screen, random.choice(colors), prev_point, new_point,2)
    draw.circle(screen, random.choice(colors), new_point, 5)
    display.flip()


running = True
myClock = time.Clock()
prev_render = time.get_ticks() #time in ticks that last render occured
prev_point = (mx, my) #where previous line ended


#function for when to re draw the scene
#ternary if. if override == True, then return true. Else return if time since last update > 2secs
rerender = lambda time_since_update, override: (time_since_update>2000, True)[override]

# Game Loop
while running:
  override = False
  for evnt in event.get():             # checks all events that happen
    if evnt.type == QUIT:
      running = False

    if evnt.type == MOUSEBUTTONDOWN:
      override = True #force window to rerender
      new_point = evnt.pos #(mx, my)
      button = evnt.button

    #rerender window only if necessary. (personal preference)
    updated_at = time.get_ticks()
    dt = updated_at-prev_render #time difference
    if(rerender(dt, override)):
      screen.fill(BLACK)
      drawScene(screen, button, prev_point, new_point)
      prev_point = new_point
      prev_render = updated_at

    display.update()
    myClock.tick(60)                     # waits long enough to have 60 fps



quit()
...