【发布时间】:2017-12-21 04:57:21
【问题描述】:
我在这段代码中使用了 Pygame。这就像一个游戏,当用户点击鼠标按钮时,鼠标位置会出现一个激光图像,它会上升,并最终走出屏幕。当用户点击鼠标按钮时,我正在尝试对图像进行 blit。我使用的这段代码不起作用,我不知道为什么。我的问题从主 for 循环开始
import pygame
# Initialize Pygame
pygame.init()
#___GLOBAL CONSTANTS___
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode([screen_width, screen_height])
#Load Laser image of spaceship
laser_image = pygame.image.load('laserRed16.png').convert()
#Load sound music
sound = pygame.mixer.Sound('laser5.ogg')
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Get the current mouse position. This returns the position
# as a list of two numbers.
sound.play()
#Get the mouse position
mouse_position = pygame.mouse.get_pos()
mouse_x = mouse_position[0]
mouse_y = mouse_position[1]
# Set the laser image when the spaceship fires
for i in range(50):
screen.blit(laser_image,[mouse_x + laser_x_vector,mouse_y + laser_x_vector])
laser_x_vector += 2
laser_x_vector += 2
# Clear the screen
screen.fill(WHITE)
#Limit to 20 sec
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
【问题讨论】:
-
you
blit激光在fill之前,所以fill在flip将缓冲区发送到将在显示器上显示的视频卡之前移除激光。 -
您将遇到另一个问题 -
for移动激光的循环 - 它不会像您预期的那样工作,因为您在一帧中移动它 50 次(两次翻转之间),因此您可以在目标位置获得激光立刻。你必须在每个while not doneloop 中做一个动作——这意味着没有for。 -
如果你有事件
MOUSEBUTTONDOWN那么你的鼠标位置在event.pos -
@furas 我在“screen.blit(laser_image,[mouse_x + laser_x_vector,mouse_y + laser_x_vector])”之前删除了for循环,但它只给了我激光图像,而不是移动的激光图像跨度>
-
正如我所说的'你会有另一个问题':) 你必须在
while循环中移动激光,但没有for i循环。你必须在for even循环之后做,因为MOUSEBUTTONDOWN仅存在于单个循环/帧中 - 当按钮将状态从“未按下”更改为“按下”时,而不是当你按住它时