我正在尝试使用渐变来更改三角形的颜色,同时定期旋转它。这是我的代码。清除曲面时似乎存在问题,因为前一个输出未被清除,并且渐变流效果仅对第一个三角形可见。
import pygame, sys
import time
import random
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption('Drawing')
t = 0
i = 0
d = 0
# set up the colors
WHITE = (255,255,255)
GREEN = ((113, 201, 106),(98, 187, 91),(84, 174, 77),(69, 160, 63),(54, 147, 49),(40, 134, 35))
# draw on the surface object
DISPLAYSURF.fill(WHITE)
newSurf = pygame.transform.rotate(DISPLAYSURF, d)
pygame.draw.polygon(newSurf,GREEN[i],((250,70),(400,300),(100,300)))
t = 0.2
while True:
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(newSurf, (0,0,))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if i==5:
f = 0
d = -90
newSurf = pygame.transform.rotate(DISPLAYSURF, d)
time.sleep(0.4)
if i==0:
f = 1
if f==1:
i = i+1
else:
i = i-1
pygame.draw.polygon(newSurf,GREEN[i],((250,70),(400,300),(100,300)))
time.sleep(t)
由于输出是动画,我不能在这里发布。相反,我发布了几个屏幕截图 -
答案 0 :(得分:0)
你在循环中基本上做的是用白色填充画布,在newSurf
上绘制一个三角形,并在newSurf
上用不同颜色在完全相同的位置绘制一个新三角形。 / p>
经过一些迭代(当i == 5
而绿色是最黑的时候)你旋转newSurf
而不清除它并在其上绘制一个新的三角形,改变它的颜色几次并一次又一次地循环
你想要做的事情可能涉及多个方面,但我会考虑你想要在旋转时更改三角形颜色的事实:你需要在绘制三角形之前每帧旋转画布并清除它。
另一个问题是您在绘制它之前旋转newSurf
,使旋转变得毫无用处。您只能看到在后台移动的内容,因为您没有在绘图前清除newSurf
。
最后但并非最不重要的是,您的代码才有效,因为您每次将方形表面旋转90度。因此不会改变它的大小。如果您要选择其他值,则newSurf
会很快变得过大而无法记忆。
import pygame, sys
import time
import random
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption('Drawing')
i = 0
d = 20 # change it to your liking
step = 1
# set up the colors
WHITE = (255,255,255)
TRANSPARENT = WHITE + (0,)
GREEN = ((113, 201, 106),(98, 187, 91),(84, 174, 77),(69, 160, 63),(54, 147, 49),(40, 134, 35))
newSurf = DISPLAYSURF.copy()
newSurf.fill(TRANSPARENT)
while True:
DISPLAYSURF.fill(WHITE)
triangle = newSurf.copy() # reset the surface to draw triangle on
pygame.draw.polygon(triangle, GREEN[i],((250,70),(400,300),(100,300))) # draw the triangle on an unrotated surface
triangle = pygame.transform.rotate(DISPLAYSURF, d*i)
# since the rotation will likely enlarge the image, compute the position of the top-left corner relative to the rotated image
width, height = triangle.get_size()
width = (500-width)/2 # change 500 with DISPLAYSURF.get_size()[0] if you plan on changing the size
height = (500-height)/2 # change 500 with DISPLAYSURF.get_size()[1] if you plan on changing the size
DISPLAYSURF.blit(triangle, (width, height))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
i += step
if not (i % 5):
step = -step
time.sleep(0.2)
您还可以使用GREEN[i%5]
并更改
i += step
if not (i % 5):
step = -step
i += 1