如何在Pygame中显示分数?

-1 投票
1 回答
1579 浏览
提问于 2025-04-17 13:16

我是一名新程序员,正在为我的计算机科学课程做一个记忆游戏。这个游戏的玩法是这样的:电脑会在随机的位置显示一些方框,然后用户需要猜测这些方框的位置并点击它们。

我基本上已经完成了,除了现在我想创建大约5个不同的难度等级。比如,第一关会显示2个方框,第二关会显示5个,依此类推。如果用户通过了所有关卡,他们就可以再玩一次。我知道这听起来很多,但我真的很想在这个项目上拿个A。

不过现在我遇到了麻烦,因为在我尝试关闭窗口时,游戏并没有完全正常工作,甚至连关闭都只完成了一半。我在想可能是我定义函数的方式有问题,但我不太确定。希望能得到一些帮助。

import pygame , sys
import random
import time

size=[500,500]
pygame.init()
screen=pygame.display.set_mode(size)


# Colours
LIME = (0,255,0) 
RED = (255, 0, 0)
BLACK = (0,0,0)
PINK = (255,102,178)
SALMON = (255,192,203)
WHITE = (255,255,255)
LIGHT_PINK = (255, 181, 197)
SKY_BLUE = (176, 226, 255)
screen.fill(BLACK)

# Width and Height of game box
width=50
height=50



# Margin between each cell
margin = 5

rows = 20
columns = 20


# Set title of screen
pygame.display.set_caption("Spatial Recall")

# Used to manage how fast the screen updates
clock=pygame.time.Clock()


coord=[]

# Create a 2 dimensional array. A two dimesional
# array is simply a list of lists.
def resetGrid():
    grid = []
    for row in range(rows):
        # Add an empty array that will hold each cell
        # in this row
        grid.append([])
        for column in range(columns):
            grid[row].append(0) # Append a cell  
    return grid

def displayAllPink(pygame):
    for row in range(rows):
        for column in range(columns):
            color = LIGHT_PINK
            pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
            pygame.display.flip()      

def displayOtherColor(pygame,grid):
    coord = []
    for i in range(random.randint(2,5)):
        x = random.randint(2, rows-1)
        y = random.randint(2, columns-1)                
        color = LIME    
        pygame.draw.rect(screen,color,[(margin+width)*y + margin,(margin+height)*x+margin,width,height])
        coord.append((x,y))  
        grid[x][y] = 1
        pygame.display.flip() 
    time.sleep(1)
    return coord

def runGame(gameCount,coord,pygame,grid):
    pygame.event.clear()
    pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount))
    pygame.time.set_timer(pygame.USEREVENT,1000)
    time = 0
    #clock.tick( 
            # -------- Main Program Loop -----------
    #Loop until the user clicks the close button.
    done = False
    while done==False:    
        event = pygame.event.wait() # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
            pygame.event.clear()
            print "Game ",gameCount, "ends"
        elif event.type == pygame.USEREVENT:
            time = time + 1
            pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount) + " Time: "+ str(time))
            if time == 100:
                done = True
                pygame.display.set_caption("Time out, moving to next level")
                pygame.event.clear()
                return False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # User clicks the mouse. Get the position
            pos = pygame.mouse.get_pos()
            # Change the x/y screen coordinates to grid coordinates
            column=pos[0] // (width+margin)
            row=pos[1] // (height+margin)
            if (row,column) in coord:
                print coord
                coord.remove((row,column))
                print coord
                color = LIME
                pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
                if coord == []:
                    done=True 
                    pygame.display.set_caption("Time out, moving to next level")
                    pygame.event.clear()
                    return True
            else:
                color = RED
                pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
            pygame.display.flip() 


def startTheGame(gameCount):
    grid = resetGrid()
    displayAllPink(pygame)
    coord = displayOtherColor(pygame,grid)
    displayAllPink(pygame)
    runGame(gameCount,coord,pygame,grid)

for i in range(2):
    startTheGame(i+1)
pygame.quit ()

1 个回答

2

目前你遇到的问题主要是因为:

  • 你的全局变量 rowscolumns 设置为20,但你的棋盘只有9个格子,所以大部分随机选出的 coords 都超出了棋盘的范围。

另外,你没有控制同一个 coord 被选两次的情况。

总的来说,我建议你使用更好的变量名称,特别是 displayOtherColor,它负责为每一层生成目标坐标。

至于你问的如何显示分数,我建议把它设置为标题,就像你已经在显示运行时间那样。

撰写回答