Pygame中的写意画

时间:2018-04-27 17:13:39

标签: pygame

我正在尝试使用Pygame进行一些实验。我正在尝试编写一段简单的代码,以便能够使用鼠标在屏幕上绘图。 这是我写的代码:

import pygame
import pygame.time
import graphics

def init_surface():
    DISPLAY_SURFACE = pygame.display.set_mode((640,480), pygame.DOUBLEBUF)
    return graphics.ViewportSurface(DISPLAY_SURFACE)

def init_mouse_pointer():
    mouse_pointer_color = pygame.Color(255, 64, 64)
    mouse_pointer = graphics.MousePointer(5, mouse_pointer_color, graphics.Point(0,0))
    return mouse_pointer, mouse_pointer_color

def main():
    pygame.init()

    window_surface = init_surface()

    center_point = graphics.Point(0,0)

    mouse_pointer, mouse_pointer_color = init_mouse_pointer()

    color = pygame.Color(255, 255, 255)
    clock = pygame.time.Clock()

    while True:
        # Event handling
        for event in pygame.event.get():
            if event.type == pygame.NOEVENT:
                continue
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        # Update mouse status  
        mouse_position = pygame.mouse.get_pos()     
        mouse_position_viewport = window_surface.convert_coordinate_from_display_to_viewport(graphics.Point(mouse_position[0], mouse_position[1]))
        mouse_pointer.set_position(mouse_position_viewport)

        # Update screen
        window_surface.draw_point(center_point, color)
        mouse_pointer.draw(window_surface)
        window_surface.flip()
        clock.tick(180)

if __name__ == '__main__':
    main()

问题在于移动鼠标我没有连续线而是虚线,如下图所示:

enter image description here 由于这个原因线路不连续?我的代码中有什么问题吗?我不明白问题出在哪里。你有什么想法?

1 个答案:

答案 0 :(得分:0)

像skrx说的那样,鼠标移动速度太快了。这种情况发生了很多次,我也遇到过这个问题。用点连接点的解决方案。看看这个:

surface = pygame.display.set_mode((640, 480))
dots = []

while True:
    mouse_pos = pygame.mouse.get_pos()
    dots.append(mouse_pos)
    pygame.draw.lines(surface, (255, 255, 255), False, dots)  # use this, much more efficient then drawing every line between the points
    # keep closed as False

这样做是为每个循环添加一组新的点,并且pygame.draw.lines它连接所有循环。希望这会有所帮助。