实施排行榜系统;我采用的方法是使用sqlite3,在该方法中,我从数据库中提取了所有记录,然后将它们从数组中“解开”,然后将其blit到表面。我在拖拉它们时遇到了麻烦,我不知道如何像排行榜那样将它们全部显示在屏幕上。 代码:
def lbButton(self, action='leaderboard'):
self.leaderboardMenu = True
if self.x + self.buttonWidth > self.mousePos[0] > self.x and self.y + self.buttonHeight > self.mousePos[1] > self.y:
if self.mouseClick[0] == 1:
if action == 'leaderboard':
image = pg.image.load('leaderboardImg.jpg')
while self.leaderboardMenu:
for event in pg.event.get():
if event.type == QUIT:
self.quitButton()
if event.type == KEYDOWN:
if event.key == pg.K_SPACE:
self.leaderboardMenu = False
self.surface.blit(image, (0, 0))
#tempName = ''
#tempScore = ''
getData = c.execute("SELECT * FROM names where name = name ORDER BY score DESC") # get so highest score is first
getData = getData.fetchall() # fetch all
for _ in getData:
getData = [_ for y in getData for y in _] # fetchall returns data in form: [(name, score), (name, score)],
# so using this loop 'untangles' that array and makes it so i can get the name and score individually
names = getData[0][0]
scores = str(getData[0][1])
print(names)
namesFont = pg.font.SysFont('comicsansms', 20)
namesText = namesFont.render(names, 1, COLOUR_RED)
self.surface.blit(namesText, (400,400))
scoresFont = pg.font.SysFont('comicsansms', 20)
scoresText = scoresFont.render(scores, 1, COLOUR_RED)
self.surface.blit(scoresText, (400, 400))
pg.display.update()
排行榜看起来像atm:https://i.imgur.com/hcmCVQP.png 如果我打印“名称”(连同数据库记录),则结果为:https://i.imgur.com/TEqyFJj.png(名称无限打印) 任何帮助,将不胜感激。谢谢 (其余的代码有效,只是将记录写到屏幕上就是问题。)
答案 0 :(得分:0)
因此,您将文本行彼此重叠,它们总是被绘制到坐标(400
,400
)上。
self.surface.blit(scoresText, (400, 400))
因此,通常在PyGame中编写多行文本时,代码必须将每行呈现为一个位图,确定其高度,然后使用它在屏幕上向下排列文本。考虑一下功能:
def getFontHeight( test_font ):
text_height = 0
test_bitmap = test_font.render( "WQ|^yg!`_", True, (0,0,0) )
text_height = test_bitmap.get_height()
return text_height
它使用同时包含ascenders和descenders的一段文本来获得 rough 粗略的想法,即所渲染的文本应该有多高。这很重要,因为___
的位图高度与XXX
不同,并且使用每个位图的行高会产生不均匀的结果。
一旦代码中有了为每行分配多少垂直空间的想法,就很容易在屏幕上分隔文本行:
names_font = pg.font.SysFont( 'comicsansms', 20 )
scores_font = pg.font.SysFont( 'comicsansms', 20 )
...
def renderLeaderboard( screen, leaderboard, position, name_font, scores_font, column2at=400, spacer=5 ):
names_font_height = getFontHeight( name_font )
scores_font_height = getFontHeight( scores_font )
line_height = max( names_font_height, scores_font_height )
name_column = position[0]
row = position[1]
score_column = name_column + column2at
for name, score in leaderboard:
name_text = name_font.render( name, True, NAME_COLOUR )
score_text= score_font.render( score, True, SCORE_COLOUR )
screen.blit( name_text, ( name_column, row ) )
screen.blit( score_text, ( score_column, row ) )
row += line_height + spacer
基本上,代码在列中写入名称和分数,然后通过font-height和间隔符增加垂直偏移(在屏幕下方),依次绘制每行。