我想在背景上保留一个图像让我们说一秒钟(或更多)然后它应该消失,我试图在一个函数内使用blit(image_draw)调用内部if语句,但图像出现的时间非常短时间,如果我改变函数image_draw内的图像的时间,我没有看到任何变化。
在代码中我有一条粗线连续向右和向左移动,每次触摸其中一个边框时,它会改变方向,当方向发生变化时会出现一个图像,我的问题是我怎么能控制背景图像的时间?函数image_draw没有帮助,这里是代码。
import pygame
import sys
import time
import math
from pygame.locals import *
def image_draw(IMAGE, RECT_FOR_IMAGE, IMAGE_TIME ):
while IMAGE_TIME > 0:
windowSurface.blit(IMAGE, RECT_FOR_IMAGE)
IMAGE_TIME -= 1
pygame.init()
windowSurface = pygame.display.set_mode((300, 600), 0, 32)
pygame.display.set_caption("line and image")
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
MYCOLOR= (200, 240, 50)
OTHER_LINE_COLOR = (180, 0, 0)
OUR_LINE_START_X = 50
OUR_LINE_START_Y = 400
OUR_LINE_END_X = 250
OUR_LINE_END_Y = 400
OTHER_LINE_START_X = 0
OTHER_LINE_START_Y = 415
OTHER_LINE_END_X = 300
OTHER_LINE_END_Y = 415
IMAGE = pygame.image.load("cherry.png")
LEFT_IMAGE = 250
TOP_IMAGE = 530
WIDTH_IMAGE = 40
HIGHT_IMAGE = 40
IMAGE_TIME = 10
RECT_FOR_IMAGE_1 = pygame.Rect(LEFT_IMAGE, TOP_IMAGE, WIDTH_IMAGE, HIGHT_IMAGE)
RECT_FOR_IMAGE_2 = pygame.Rect(LEFT_IMAGE - 200, TOP_IMAGE, WIDTH_IMAGE, HIGHT_IMAGE)
SOUND = pygame.mixer.Sound("pickup.wav")
MOVE_SPEED = 1
DIRECTION = "left"
while True:
windowSurface.fill(WHITE)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if DIRECTION == "right" :
OUR_LINE_START_X += MOVE_SPEED
OUR_LINE_END_X += MOVE_SPEED
elif DIRECTION == "left":
OUR_LINE_START_X -= MOVE_SPEED
OUR_LINE_END_X -= MOVE_SPEED
if OUR_LINE_START_X < 0:
DIRECTION = "right"
SOUND.play()
image_draw(IMAGE, RECT_FOR_IMAGE_1, IMAGE_TIME )
if OUR_LINE_END_X > 300:
DIRECTION = "left"
SOUND.play()
image_draw(IMAGE, RECT_FOR_IMAGE_2, IMAGE_TIME )
pygame.draw.line(windowSurface, MYCOLOR, (OUR_LINE_START_X, OUR_LINE_START_Y), (OUR_LINE_END_X, OUR_LINE_END_Y), 30)
pygame.draw.line(windowSurface, OTHER_LINE_COLOR, (OTHER_LINE_START_X, OTHER_LINE_START_Y), (OTHER_LINE_END_X, OTHER_LINE_END_Y), 3)
pygame.display.update()
time.sleep(0.02)
提前谢谢你。
答案 0 :(得分:3)
你的while循环是游戏框架循环。
使用image_draw进行绘制时,您将在一帧内从10倒数到0,然后再将图像bl成。另外,因为您从具有相同名称的函数中引用IMAGE_TIME变量,所以变量的范围仅在该函数内。
对正在发生的事情的直观描述:
Game Loop:
draw_image:
10 - 0
blit
next frame
要使其正常工作,您可以将IMAGE_TIME变量保留在image_draw方法签名之外,并使用全局IMAGE_TIME。从image_draw中删除while循环并让它在每一帧上修改全局,然后当你想再次绘制图像时需要重置它。
IMAGE_TIME = 10
def image_draw(IMAGE, RECT_FOR_IMAGE):
if IMAGE_TIME > 0:
windowSurface.blit(IMAGE, RECT_FOR_IMAGE)
IMAGE_TIME -= 1
# ... other code left out for brevity
if OUR_LINE_START_X < 0:
DIRECTION = "right"
SOUND.play()
if IMAGE_TIME == 0:
IMAGE_TIME = 10
image_draw(IMAGE, RECT_FOR_IMAGE_1)
if OUR_LINE_END_X > 300:
DIRECTION = "left"
SOUND.play()
if IMAGE_TIME == 0:
IMAGE_TIME = 10
image_draw(IMAGE, RECT_FOR_IMAGE_2)
值得指出的是,在pygame中控制帧率的适当方法是创建一个时钟对象并用所需的帧速率打勾:
clock = pygame.Clock()
while True:
# do your stuff here
clock.tick(60) # 60 frames per second
这意味着游戏循环每秒大约执行60次,因此您可以通过设置IMAGE_TIME = 60
轻松控制图像的显示为1秒。