【发布时间】:2017-03-26 09:42:01
【问题描述】:
我正在使用 Pygame 制作一个简单的基于图块的游戏。
目前,它显示一个 10x10 的随机选择图块网格。那部分工作得很好,但我在突出显示时遇到了问题。
当您将鼠标悬停在一个图块上时,它应该加载一个大约一半不透明度的灰色图块。它加载,但不透明度无法正常工作。如果将鼠标放在瓷砖上,它会正确加载不透明度和所有内容。但是如果你在瓷砖周围移动鼠标,它就会变成正常的,没有不透明度。
我认为它正在发生,因为每次发生事件时它都会加载突出显示的磁贴,但我不知道如何修复它。
我正在使用一个名为 Tilemap 的类来生成和绘制 tilemap。我认为是 draw() 函数中的某些东西导致了这一切。
import pygame
import sys
import random
from pygame.locals import *
running = True
class Tilemap:
tilemap = []
ht = None # ht = highlight texture
def __init__(self, height, width, tilesize, textures):
self.height = height # How many tiles high it is
self.width = width # How many tiles wide it is
self.tilesize = tilesize # How many pixels each tile is
self.textures = textures # The textures
self.size = (self.width*self.tilesize,self.height*self.tilesize)
def generate_random(self):
# Generate a random tilemap
self.tilemap = [[random.randint(0, len(
self.textures)-1) for e in range(self.width)] for e in range(
self.height)]
def draw(self, display, mouse=None):
mouse = mouse
# Draw the map
for row in range(self.width):
for column in range(self.height):
texture = self.textures[self.tilemap[row][column]]
# Highlight a tile (this is where the problem is)
if self.ht != None:
if mouse[0] >= (column*self.tilesize) and mouse[0] <= (
column*self.tilesize)+self.tilesize:
if mouse[1] >= (row*self.tilesize) and mouse[1] <= (
row*self.tilesize)+self.tilesize:
texture = self.ht
display.blit(texture,
(column*self.tilesize, row*self.tilesize))
tilemap = Tilemap(10,10,40,
# Load the textures
{0: pygame.image.load("tile1.png"),
1: pygame.image.load("tile2.png")
}
)
tilemap.generate_random() # Generate a random tilemap
pygame.init()
DISPLAYSURF = pygame.display.set_mode((tilemap.size))
# Load the highlighter
tilemap.ht = pygame.image.load("highlight.png").convert_alpha()
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Draw the tilemap
tilemap.draw(DISPLAYSURF, pygame.mouse.get_pos())
pygame.display.update()
如果您需要更多解释,请随时询问!
【问题讨论】: