绘画应用程序 - python

时间:2013-12-23 12:09:35

标签: python pygame

我正在尝试在pygame中制作画笔游戏。我已完成绘画,但我希望用户点击图像,这将改变画笔的画笔。如果用户单击蓝色图像,则画笔变为蓝色。到目前为止,我已经管理显示蓝色图像,我有一个默认的红色画笔。只有触摸蓝色图像的位置时,画笔颜色才会改变。我想在用户点击屏幕的任何其他区域时保留画笔颜色。

有什么建议吗?

这是我的代码:

import sys, pygame
from pygame.locals import *


pygame.init()

screen = pygame.display.set_mode((1000,600))

screen.fill((255,255,255))

brush = pygame.image.load("redbrush.png")
brush = pygame.transform.scale(brush,(45,45))

brush2 = pygame.image.load("bluebrush.png")
brush2 = pygame.transform.scale(brush2,(45,45))


pygame.display.update()

clock = pygame.time.Clock()

z = 0

while 1:
    screen.blit(brush2, (0,10))
    pygame.display.update()
    clock.tick(60)
    x,y = pygame.mouse.get_pos()


    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            pygame.quit()
            sys.exit() 
        elif event.type ==MOUSEBUTTONDOWN:
            z=1
        elif event.type ==MOUSEBUTTONUP:
            z=0
        if z==1:
            screen.blit(brush, (x -23.5,y-23.5))
            pygame.display.update()
            if brush2.get_rect().collidepoint(pygame.mouse.get_pos()):
                screen.blit(brush2, (x -23.5,y-23.5))
                pygame.display.update()

1 个答案:

答案 0 :(得分:1)

替换你的行:

if brush2.get_rect().collidepoint(pygame.mouse.get_pos()):
    screen.blit(brush2, (x -23.5,y-23.5))
    pygame.display.update()

使用:

if brush2.get_rect().collidepoint(pygame.mouse.get_pos()):
    (brush, brush2) = (brush2, brush) # swaps brush and brush2
    pygame.display.update()

已编辑:我看到了您的评论,这是您的代码的修改版本:

import sys, pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((1000,600))

screen.fill((255,255,255))

brush1 = pygame.image.load("redbrush.png")
brush1 = pygame.transform.scale(brush1,(45,45))
pos1 = (0, 32)

brush2 = pygame.image.load("bluebrush.png")
brush2 = pygame.transform.scale(brush2,(45,45))
brush2 = pygame.transform.scale(brush2,(45,45))
pos2 = (0, 64)

brush = brush1

pygame.display.update()

clock = pygame.time.Clock()

z = 0

while 1:
    screen.blit(brush1, pos1)
    screen.blit(brush2, pos2)
    pygame.display.update()
    clock.tick(60)
    x,y = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            pygame.quit()
            sys.exit() 
        elif event.type ==MOUSEBUTTONDOWN:
            z=1
        elif event.type ==MOUSEBUTTONUP:
            z=0
        if z==1:
            if brush1.get_rect(center=pos1).collidepoint(pygame.mouse.get_pos()):
                brush = brush1
            if brush2.get_rect(center=pos2).collidepoint(pygame.mouse.get_pos()):
                brush = brush2
            screen.blit(brush, (x -23.5,y-23.5))
            pygame.display.update()