Я набрал код из книги Свигарта «Pygame» для игры «Puzzle Memory»: http://inventwithpython.com/pygame/chapter3.html.
2 задачи:
Когда я щелкаю по последнему блоку после сопоставления со всем остальным, игра останавливается и сразу же начинает играть музыку pygame.mixer вместо того, чтобы показывать этот последний блок или даже функцию gameWonAnimation (). Мне интересно, почему не отображается последнее окно или даже почему эта функция не работает
Мой объект шрифта не отображается на общем экране в анимации игры (на доске), но моя музыка воспроизводится с той же функцией. Может кто-нибудь помочь мне понять, что происходит в конце этого кода?
Я попытался отобразить шрифт и установить его в display.blit (), а также попытался переместить его непосредственно в основной игровой цикл вместо того, чтобы использовать его в функции. Я также непосредственно скопировал и вставил его код здесь: https://inventwithpython.com/memorypuzzle.py, но проблема той же самой последней коробки, которая не раскрывает себя, сохраняется. Отображаемый код является фрагментом моей собственной версии в целом.
def main():
## mouse_state
mousex = 0 ## used to store x coord of mouse event
mousey = 0 ## used to store y coord of mouse event
## board_state
main_board = getRandomizedBoard() ## returns a data struct representing board state
revealed_boxes = generateRevealedBoxesData(False) ## returns data struct representing which boxes are covered
first_select = None
display.fill(bg_color)
startGameAnimation(main_board)
## Game Loop
while True:
mouse_clicked = False
display.fill(bg_color) # draw window
drawBoard(main_board, revealed_boxes)
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP: ## mouse button clicked and let go which is registered as an event
mousex, mousey = event.pos
mouse_clicked = True
box_x, box_y = getBoxAtPixel(mousex, mousey)
if box_x != None and box_y != None:
# the mouse is currently over a box-- hovering
if not revealed_boxes[box_x][box_y]:
drawHighlightBox(box_x, box_y)
if not revealed_boxes[box_x][box_y] and mouse_clicked: ## actual click
revealBoxesAnimation(main_board, [(box_x, box_y)])
revealed_boxes[box_x][box_y] = True ## set the box as 'revealed'
if first_select == None: ## the current box was the first box clicked
first_select = (box_x, box_y)
else: ## current box is not the first box selected
# check if there is a match between the two icons
icon1_shape, icon1_color = getShapeAndColor(main_board, first_select[0], first_select[1])
icon2_shape, icon2_color = getShapeAndColor(main_board, box_x, box_y)
if icon1_shape != icon2_shape or icon1_color != icon2_color:
# icons don't match so re-cover both selections
pygame.time.wait(500) ## 1000 milliseconds = 1 sec
## cover the two selected boxes (first_select, and second box)
coverBoxesAnimation(main_board, [(first_select[0], first_select[1]), (box_x, box_y)])
revealed_boxes[first_select[0]][first_select[1]] = False
revealed_boxes[box_x][box_y] = False
elif hasWon(revealed_boxes): ## check if all pairs found
revealBoxesAnimation(main_board, revealed_boxes)
pygame.display.update()
gameWon(main_board)
gameWonAnimation(main_board)
pygame.time.wait(3000)
# reset the board
main_board = getRandomizedBoard()
revealed_boxes = generateRevealedBoxesData(False)
# show the fully unrevealed board for a second
drawBoard(main_board, revealed_boxes)
pygame.display.update()
pygame.time.wait(1000)
# replay the start game animation
startGameAnimation(main_board)
first_select = None # reset first_select variable
pygame.display.update()
pygame.time.Clock().tick(fps)
## my own created helper function
## display sign that user has won with text and victory music playing
def gameWon(board):
pygame.font.init()
font = pygame.font.SysFont('Comic Sans MS', 15)
text_surf = font.render('Congrats you won!', False, white)
# text_surf_rect = text_surf.get_rect()
display.blit(text_surf, ((ww-text_surf.get_width()/2), wh-text_surf.get_height()/2))
pygame.display.update()
time.sleep(2)
## load victory music
pygame.mixer.music.load('beethoven_symph6_pastoral.mp3')
pygame.mixer.music.play(-1, 0.0)
pygame.time.wait(10000)
pygame.mixer.music.stop()
def gameWonAnimation(board):
coveredBoxes = generateRevealedBoxesData(True)
color1= light_bg_color
color2 = bg_color
for i in range(5):
color1, color2 = color2, color1 # swap colors
display.fill(color1)
drawBoard(board, coveredBoxes)
pygame.display.update()
pygame.time.wait(300)
Объект шрифта должен быть визуализирован после победы в игре (музыка работает отлично), а также должны быть открыты все прямоугольники, указывающие на общую победу, и показывает игроку все выявленные значки / фигуры вместо нескольких. Обратите внимание, что копия, которую он включил, является доской 10x7, но вы можете напрямую изменить ее на 2x2, чтобы сделать тестирование быстрее и проще.