我是一名业余程序员,试图用 python 和 pygame 制作游戏(我知道,不是最好的,但我知道如何比 Java 和 C++ 更好地使用它)。我遇到了一个有趣的问题:使用屏幕坐标在屏幕上定位特定的精灵,然后将该精灵移动到不同的位置。
例如,我有一个物品栏,我正在编写某种方式让玩家将物品从物品栏中放下,然后放回二维游戏场,以便玩家稍后可以捡起它。
由于项目的数量会有所不同,因此将它们的所有坐标添加到一个列表并尝试以这种方式管理它是效率低下的。试图将不断变化的项目列表连接到现场的对象变得太混乱了。
我已经附上了我到目前为止的代码,以防万一。我在网上查看过,但没有找到有关如何执行此操作的任何建议,我发现的唯一其他解决方案是以某种方式找到使用的对象spritecollide()
和一个不可见的精灵,但我需要帮助。
drop 功能是我现在正在研究的部分。pos()
是 2 个项目的列表,x
和y
是您在屏幕上单击的鼠标坐标。
创建库存的类:
import pygame
from testRect import *
class Inventory(pygame.sprite.Sprite):
# Define colors
white = (255,255,255)
dgreen = (0,154,0)#useables
dblue = (0,0,154)#throwables
dred = (154,0,0)#holdables
def __init__(self,surface,pos,grid,gridItems,handsUsed):
for row in range(4):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(4):
grid[row].append(0) # Append a cell
gridItems.append([])
for column in range(4):
gridItems[row].append(0) # Append a cell
self.update(surface,pos,grid,gridItems,handsUsed)
def update(self,surface,pos,grid,gridItems,handsUsed):
width=40
height=40
margin=2
#convert click location to grid squares
column=pos[0] // (width+margin)-20
row=pos[1] // (height+margin)-7
#make grid selection (toggle if selected or not)
if row >-1 and row <4 and column >-1 and column < 4:
if grid[row][column] == 0 and handsUsed < 2:
grid[row][column] = 1
handsUsed += 1
elif grid[row][column] == 1 and handsUsed > 0:
grid[row][column] = 0
handsUsed -= 1
# Draw the grid and determine type of object
for row in range(4):
for column in range(4):
color = self.white
if grid[row][column] == 1 and gridItems[row][column] == 1:
color = self.dgreen
elif grid[row][column] == 1 and gridItems[row][column] == 2:
color = self.dblue
elif grid[row][column] == 1 and gridItems[row][column] == 3:
color = self.dred
pygame.draw.rect(surface,color,[((margin+width)*column+margin)+840,((margin+height)*row+margin)+295,width,height])
return handsUsed#return the variable so that the master handsUsed var will also update
def drop(self,pos,handsUsed,grid,staticsprites):
moved = False
if pos[0] > 838 and pos[0] < 1011 and pos[1] > 491 and pos[1] < 538 and handsUsed > 0:
width=40
height=40
margin=2
row = 0
column = 0
while row < 4 and moved == False:
if grid[row][column] == 1:
#items selected will set their coordinates to a space near the player.
#Will check to see if spot is open in this priority (high to low): below, above, left, right
#finds the item to be moved
itemSelectRow = row * (((height + margin)-7))+299
itemSelectColumn = (column * ((width + margin)+20))+845
collideList = pygame.sprite.spritecollide(testRect, staticsprites, False)
if collideList != None:
#will move the item to the location since nothing is in the way
print collideList
moved = True
break
elif row < 4 and column < 3:
print "hi"
column += 1
elif row < 4 and column >= 3:
column = 0
row += 1
else:
break
return handsUsed#return the variable so that the master handsUsed var will also update