问题描述
我试图在 pygame 中制作一些 minecraft 2d 克隆,我希望它在我左键单击时在光标位置闪烁图像,但是当我测试游戏并左键单击时,图像会出现并很快消失。
代码如下:
import pygame
# Setup
pygame.init()
screen = pygame.display.set_mode((1080,720))
pygame.display.set_caption('2d minecraft')
clock = pygame.time.Clock()
logo = pygame.image.load("logo.png")
pygame.display.set_icon(logo)
# Variables
running = True
dirt = pygame.image.load("logo.png")
# Program
while running:
# Customization
screen.fill((110,150,200))
# Update display
pygame.display.update()
# Events
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
screen.blit(dirt,(pygame.mouse.get_pos()))
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
clock.tick(30)
解决方法
您必须在应用程序循环中绘制图像。单击鼠标时将位置添加到列表中。在应用程序循环中的列表中的所有位置绘制图像:
import pygame
pygame.init()
screen = pygame.display.set_mode((1080,720))
pygame.display.set_caption('2d minecraft')
clock = pygame.time.Clock()
logo = pygame.image.load("logo.png")
pygame.display.set_icon(logo)
#Variables
running = True
dirt = pygame.image.load("logo.png")
# list of positions
positions = []
#Program
while running:
#Events
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
# add position to list
positions.append(event.pos)
if event.type == pygame.QUIT:
running = False
screen.fill((110,150,200))
# draw images at positions
for pos in positions:
screen.blit(dirt,pos)
pygame.display.flip()
clock.tick(30)
,
事件 pygame.MOUSEBUTTONUP
仅在您按下鼠标按钮时发生。
这可用于例如处理按钮上的点击,但如果您想在按下鼠标时对图像进行 blit,则首选使用 pygame.mouse.get_pressed()
。
此函数返回与鼠标按钮对应的值列表。如果按下相应的按钮,则列表中的每个值都设置为 True,否则设置为 False。
使用此代码在鼠标位置显示一个红色矩形:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480))
red_rect = pygame.Surface((50,50))
red_rect.fill((255,0))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if pygame.mouse.get_pressed()[0]: # first value of the list is the left click (check if left click pressed
screen.blit(red_rect,pygame.mouse.get_pos())