Member 13152640 Ответов: 1

Как исправить кнопку сброса в code skulptor (среда на основе Python)?


Привет, я до сих пор пытаюсь закодировать игру памяти, и она работает, за исключением кнопки сброса. Вот мой код до сих пор:
#Memory Game
import simplegui
import simplegui as sg
from random import shuffle
import time

#Canvas Details
CANVAS_SIZE = 900, 800
CARD_COLS = 5
CARD_ROWS = 4

CARD = CARD_COLS * CARD_ROWS #Number of cards

CARD_WIDTH = CANVAS_SIZE[0] / float( CARD_COLS )#Card size
CARD_HEIGHT = CANVAS_SIZE[1] / float( CARD_ROWS )

FONT_SIZE = 200 #Font size

# Global Variables
turns = 0
card_list = exposed_list = None
card_1 = card_2 = None #Compare two selected card
card_type = "Numbers"
high_score = 0
matches = 0

#New Game Function
def new_game():
    global card_list, exposed_list, turns, card_1, card_2
    card_1 = card_2 = None
    turns = 0
    label_turns.set_text("Number of Turns = " + str(turns))
    card_list = range(10) * 2
    shuffle(card_list)
    exposed_list = [False] * CARD

def mouseclick( pos ):
    global card_1, card_2, turns, matches
    card = pos[0] * CARD_COLS / CANVAS_SIZE[0] + pos[1] * CARD_ROWS / CANVAS_SIZE[1] * CARD_COLS
    matches = 0
    if not exposed_list[card]:
        exposed_list[card] = True
        if card_1 == None:
            card_1 = card
            turns += 1
            label_turns.set_text( "Number of Turns = " + str( turns ) )
        elif card_2 == None:
            card_2 = card
            if card_list[card_1] == card_list[card_2]:  # if equals, clean selected cards
                card_1 = card_2 = None
                matches += 1
        else:
            # hide cards
            exposed_list[card_1] = exposed_list[card_2] = False
            card_1 = card
            card_2 = None
            turns += 1
            label_turns.set_text( "Number of Turns = " + str( turns ) )
            
# draw playmat  
def draw( canvas ):
    global high_score, matches
    # draw exposed and hidden cards
    for i in range( CARD ):
        
        # card upper-left coords
        card_x = ( i % CARD_COLS ) * CARD_WIDTH
        card_y = ( i / CARD_COLS ) * CARD_HEIGHT
        
        # hidden card
        if not exposed_list[i]:
            canvas.draw_polygon( [ 
                                    ( card_x, card_y ),
                                    ( card_x + CARD_WIDTH, card_y ),
                                    ( card_x + CARD_WIDTH, card_y + CARD_HEIGHT ),
                                    ( card_x, card_y + CARD_HEIGHT ) 
                                 ],
                                 2, "red", "green" )
        # exposed card
        else:
            canvas.draw_polygon( [ 
                                ( card_x, card_y ),
                                ( card_x + CARD_WIDTH, card_y ),
                                ( card_x + CARD_WIDTH, card_y + CARD_HEIGHT ),
                                ( card_x, card_y + CARD_HEIGHT ) 
                            ],
                            2, "red", "black" )
            card_value = card_list[i]  
            text_width = frame.get_canvas_textwidth( str( card_value ), FONT_SIZE, "serif" )
            canvas.draw_text( str( card_value ),
                            ( 
                             card_x + ( CARD_WIDTH - text_width ) / 2, 
                             card_y + ( FONT_SIZE + CARD_HEIGHT ) / 2 * 5 / 6.
                            ),
                     FONT_SIZE, "white", "serif" )
    if matches == 10:
        if (turns > high_score):
            turns = high_score
        
# create frame and add buttons and labels
frame = sg.create_frame( "Memory Game", CANVAS_SIZE[0], CANVAS_SIZE[1], 180 )
frame.add_button( "Reset", new_game )
frame.add_label( "" )
label_turns = frame.add_label( "" )
frame.add_label("Best Score:")
frame.add_label(str(high_score) + " " + "turns")


# register event handlers
frame.set_mouseclick_handler( mouseclick )
frame.set_draw_handler( draw )


# start
new_game()
frame.start()


Я думаю, что проблема в том, что
frame.add_button( "Reset", new_game )

Спасибо и хорошего вам дня

Что я уже пробовал:

frame.add_button("Reset", new_game, (CARD_COLS, CARD_ROWS))

Это вызвало ошибку " ширина должна быть целым числом"
("Reset", new_game, str(CARD_COLS), str(CARD_ROWS))

Это вызвало ошибку " 5 приведенных аргументов, четыре необходимых"
frame.add_button("Reset", new_game(CARD_COLS, CARD_ROWS))

Это приводит к ошибке " обработчик должен быть функцией"

1 Ответов

Рейтинг:
1

Richard MacCutchan

Видеть Документация CodeSkulptor[^] для получения более подробной информации о frame.add_button метод.