Cells Are Skipped When I Move The Mouse Quickly
Here is a python script that creates a pygame window and fills in the cell that is clicked on. import pygame from math import floor, sqrt from sys import exit as _exit cellsize =
Solution 1:
Implement a function, that returns the index of a cell at a certain position:
defcellAtPos(pos):
c = (floor(pos[0] / cellsize[0]), floor(pos[1] / cellsize[1]))
return c[1] * mapSize[0] + c[0]
Store the mouse buttons and position in ever frame:
mousePreviousFrame = mouse
mousePosPreviousFrame = mousepos
With the mouse button is pressed and was pressed in the previous frame, calculate the vector the mouse moved:
if mouse[0] and mousePreviousFrame[0]:
direction = (mousepos[0] - mousePosPreviousFrame[0], mousepos[1] - mousePosPreviousFrame[1])
Fill the cells along the vector in a loop:
mag = hypot(*direction)
if mag != 0:
normdir = (direction[0] / mag, direction[1] / mag)
for i inrange(int(mag)):
current = mousePosPreviousFrame[0] + normdir[0] * i, mousePosPreviousFrame[1] + normdir[1] * i
cells[cellAtPos(current)] = True
Minimal example
import pygame
from math import floor, sqrt, hypot
from sys import exit as _exit
cellsize = (5, 5)
mapSize = (int(600 / cellsize[0]), int(600 / cellsize[1]))
cells = [Falsefor i inrange(mapSize[0] * mapSize[1])]
defcellAtPos(pos):
c = (floor(pos[0] / cellsize[0]), floor(pos[1] / cellsize[1]))
return c[1] * mapSize[0] + c[0]
pygame.init()
window = pygame.display.set_mode((600, 600))
mousePreviousFrame = pygame.mouse.get_pos()
run = Truewhile run:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
run = False
mouse = pygame.mouse.get_pressed()
mousepos = pygame.mouse.get_pos()
if mouse[0]:
cells[cellAtPos(mousepos)] = Trueif mouse[0] and mousePreviousFrame[0]:
direction = (mousepos[0] - mousePosPreviousFrame[0], mousepos[1] - mousePosPreviousFrame[1])
mag = hypot(*direction)
if mag != 0:
normdir = (direction[0] / mag, direction[1] / mag)
for i inrange(int(mag)):
current = mousePosPreviousFrame[0] + normdir[0] * i, mousePosPreviousFrame[1] + normdir[1] * i
cells[cellAtPos(current)] = True
mousePreviousFrame = mouse
mousePosPreviousFrame = mousepos
#draw
window.fill((255, 255, 255))
for x inrange(mapSize[0]):
for y inrange(mapSize[1]):
if (cells[y * mapSize[0] + x]):
pygame.draw.rect(window, (0, 0, 0), (x * cellsize[0], y * cellsize[1], cellsize[0], cellsize[1]))
pygame.display.flip()
pygame.quit()
_exit()
Post a Comment for "Cells Are Skipped When I Move The Mouse Quickly"