python - 如何使用 Pygame 使这个演示绘图游戏更新更快地绘制圆圈?

标签 python pygame

我试图让我的绘图游戏在拖动鼠标的地方画一个圆圈,但圆圈的更新频率不足以创建一条平滑的线条。我该如何解决这个问题?

import pygame
from random import randint
width=800
height=600
pygame.init() #As necessary as import, initalizes pygame
global gameDisplay 
gameDisplay = pygame.display.set_mode((width,height))#Makes window
pygame.display.set_caption('Demo')#Titles window
clock = pygame.time.Clock()#Keeps time for pygame


gameDisplay.fill((0,0,255))

class Draw:
    def __init__(self):
        self.color = (255, 0, 0)

    def update(self, x, y):
        self.x = x
        self.y = y
        pygame.draw.circle(gameDisplay, self.color, (self.x, self.y), (5))


end = False
down = False
Line = Draw()
while not end:
    x, y = pygame.mouse.get_pos()
    #drawShape()
    #pygame.draw.rect(gameDisplay, (0,255,0), (10, 10, 4, 4))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            down = True

        if event.type == pygame.MOUSEBUTTONUP:
            down = False

        if down:
            Line.update(x, y)

        if event.type == pygame.QUIT:
            end = True
    lastx, lasty = pygame.mouse.get_pos()
    pygame.display.update()

    clock.tick(60)

pygame.quit()

这就是我的问题

最佳答案

我建议从上一个鼠标位置到当前鼠标位置画一条线。另外,在线条的开头和结尾处画一个点。这会导致一个回合的开始和结束。
跟踪鼠标的先前位置(lastxlasty)并在主应用程序循环而不是事件循环中绘制线条:

例如:

import pygame

width, height = 800, 600
pygame.init() #As necessary as import, initalizes pygame
gameDisplay = pygame.display.set_mode((width,height)) #Makes window
pygame.display.set_caption('Demo') #Titles window
clock = pygame.time.Clock() #Keeps time for pygame
gameDisplay.fill((0,0,255))

class Draw:
    def __init__(self):
        self.color = (255, 0, 0)

    def update(self, from_x, from_y, to_x, to_y):
        pygame.draw.circle(gameDisplay, self.color, (from_x, from_y), 5)
        pygame.draw.line(gameDisplay, self.color, (from_x, from_y), (to_x, to_y), 10)
        pygame.draw.circle(gameDisplay, self.color, (to_x, to_y), 5)

end = False
down = False
line = Draw()
while not end:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            lastx, lasty = event.pos
            down = True
        if event.type == pygame.MOUSEBUTTONUP:
            down = False
        if event.type == pygame.QUIT:
            end = True

    x, y = pygame.mouse.get_pos() 
    if down:
        line.update(lastx, lasty, x, y)
    lastx, lasty = x, y

    pygame.display.update()
    clock.tick(60)

pygame.quit()

关于python - 如何使用 Pygame 使这个演示绘图游戏更新更快地绘制圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60284620/

相关文章:

Python:类型错误:文本必须是 unicode 或字节

python - 在达到最大目标数量后,如何停止 pygame 中的事件循环?

python - 在屏幕中夹紧 Sprite

Python在While循环中继续缩进

python - Spyder、变量浏览器、xpt

python - unittest,在本地工作,但不在远程服务器上,没有名为 x.__main__ 的模块; 'x'是一个包,不能直接执行

python - 固定盒2D 工程图

python - 在 mongoengine 中归档旧数据

python - Pandas - 创建行以在列中输入

python - 有人可以帮助我为什么我的 pygame 代码中存在关于 `ball moving` 的错误吗?