IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Programmation multimédia/Jeux Python Discussion :

local variable 'player2' referenced before assignment ERROR


Sujet :

Programmation multimédia/Jeux Python

  1. #1
    Nouveau membre du Club
    Homme Profil pro
    Assistant aux utilisateurs
    Inscrit en
    Octobre 2017
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Assistant aux utilisateurs

    Informations forums :
    Inscription : Octobre 2017
    Messages : 50
    Points : 28
    Points
    28
    Par défaut local variable 'player2' referenced before assignment ERROR
    Bonjour à tous,
    J'essaie de créer un jeu de carte avec Arcade library et je rencontre quelques difficultés. Ligne 267, j'ai l'erreur suivante :
    Player.change_attribute(player2,1,2,0,0)
    UnboundLocalError: local variable 'player2' referenced before assignment
    ALors que j'ai assigné de plusiers manière player2, pour essayer de contrer l'erreur.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    """
    Solitaire clone.
    """
    import random
    import arcade
    import arcade.gui
     
    game_over = False
     
    # Screen title and size
    SCREEN_WIDTH = 1024
    SCREEN_HEIGHT = 768
    SCREEN_TITLE = "MushRoom"
     
    # Constants for sizing
    CARD_SCALE = 0.65
     
    # How big are the cards?
    CARD_WIDTH = 140 * CARD_SCALE
    CARD_HEIGHT = 190 * CARD_SCALE
     
    # How big is the mat we'll place the card on?
    MAT_PERCENT_OVERSIZE = 1.25
    MAT_HEIGHT = int(CARD_HEIGHT * MAT_PERCENT_OVERSIZE)
    MAT_WIDTH = int(CARD_WIDTH * MAT_PERCENT_OVERSIZE)
     
    # How much space do we leave as a gap between the mats?
    # Done as a percent of the mat size.
    VERTICAL_MARGIN_PERCENT = 0.10
    HORIZONTAL_MARGIN_PERCENT = 0.10
     
    # The Y of the bottom row (2 piles)
    BOTTOM_Y = MAT_HEIGHT / 2 + MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # The X of where to start putting things on the left side
    START_X = MAT_WIDTH / 2 + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT
     
    # The Y of the top row (4 piles)
    TOP_Y = SCREEN_HEIGHT - MAT_HEIGHT / 2 - MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # The Y of the middle row (7 piles)
    MIDDLE_Y = TOP_Y - MAT_HEIGHT - MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # How far apart each pile goes
    X_SPACING = MAT_WIDTH + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT
     
    # Card constants
    CARD_VALUES = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    CARD_SUITS = ["Clubs", "Hearts", "Spades", "Diamonds"]
     
    # If we fan out cards stacked on each other, how far apart to fan them?
    CARD_VERTICAL_OFFSET = CARD_HEIGHT * CARD_SCALE * 0.3
     
    # Face down image
    FACE_DOWN_IMAGE = ":resources:images/cards/cardBack_red2.png"
     
    # Constants that represent "what pile is what" for the game
    PILE_COUNT = 10
    BOTTOM_FACE_DOWN_PILE = 0
    BOTTOM_FACE_UP_PILE = 1
    PLAY_PILE_1 = 2
    PLAY_PILE_2 = 3
    PLAY_PILE_3 = 4
    PLAY_PILE_4 = 5
    PLAY_PILE_5 = 6
    PLAY_PILE_6 = 7
    PLAY_PILE_7 = 8
    PLAY_PILE_8 = 9
     
     
    class Player:
        def __init__(self, TireCarte, SeeOwnGame,SeeEnemyGame,JetteCarte,scale=1):
            self.TireCarte = TireCarte
            self.SeeOwnGame = SeeOwnGame
            self.SeeEnemyGame = SeeEnemyGame
            self.JetteCarte = JetteCarte
     
        def change_attribute(self, TireCarte=None, SeeOwnGame=None,SeeEnemyGame=None,JetteCarte=None):
            if TireCarte!=None:
                self.TireCarte = TireCarte
            if SeeOwnGame != None:
                self.SeeOwnGame = SeeOwnGame
            if SeeEnemyGame!=None:
                self.SeeEnemyGame = SeeEnemyGame
            if JetteCarte!=None:
                self.JetteCarte = JetteCarte
     
    player1= Player(0,0,0,0)
    player2= Player(0,0,0,0)
     
    class Card(arcade.Sprite):
        """ Card sprite """
     
        def __init__(self, suit, value, scale=1):
            """ Card constructor """
     
            # Attributes for suit and value
            self.suit = suit
            self.value = value
     
            # Image to use for the sprite when face up
            self.image_file_name = f":resources:images/cards/card{self.suit}{self.value}.png"
            self.is_face_up = False
            super().__init__(FACE_DOWN_IMAGE, scale, hit_box_algorithm="None")
     
        def face_down(self):
            """ Turn card face-down """
            self.texture = arcade.load_texture(FACE_DOWN_IMAGE)
            self.is_face_up = False
     
        def face_up(self):
            """ Turn card face-up """
            self.texture = arcade.load_texture(self.image_file_name)
            self.is_face_up = True
     
        @property
        def is_face_down(self):
            """ Is this card face down? """
            return not self.is_face_up
     
     
    class MyGame(arcade.Window):
        """ Main application class. """
        # List Of Power
     
     
        def __init__(self):
            super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
     
            # Sprite list with all the cards, no matter what pile they are in.
            self.card_list = None
     
            arcade.set_background_color(arcade.color.AMAZON)
     
            # List of cards we are dragging with the mouse
            self.held_cards = None
     
            # Original location of cards we are dragging with the mouse in case
            # they have to go back.
            self.held_cards_original_position = None
     
            # Sprite list with all the mats tha cards lay on.
            self.pile_mat_list = None
     
            # Create a list of lists, each holds a pile of cards.
            self.piles = None
     
            #Display sprite
            self.player = arcade.Sprite('assets/player1.png')
            self.player.center_x = 790
            self.player.center_y = 200
     
            self.mummy = arcade.Sprite('assets/player2.png')
            self.mummy.center_x = 790
            self.mummy.center_y = 560
     
            #Track turn
            self.turn = 1
     
     
        def setup(self):
            """ Set up the game here. Call this function to restart the game. """
     
            # List of cards we are dragging with the mouse
            self.held_cards = []
     
            # Original location of cards we are dragging with the mouse in case
            # they have to go back.
            self.held_cards_original_position = []
     
            # ---  Create the mats the cards go on.
     
            # Sprite list with all the mats tha cards lay on.
            self.pile_mat_list: arcade.SpriteList = arcade.SpriteList()
     
            # Create the mats for the bottom face down and face up piles
            pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
            pile.position = START_X, SCREEN_HEIGHT/2
            self.pile_mat_list.append(pile)
     
            pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
            pile.position = START_X + X_SPACING, SCREEN_HEIGHT/2
            self.pile_mat_list.append(pile)
     
            # Create the eight middle piles
            for i in range(8):
                pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
                if i==0:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 1 * X_SPACING, CARD_WIDTH
                if i==1:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 2 * X_SPACING, CARD_WIDTH
                if i==2:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 1 * X_SPACING, CARD_WIDTH *2.8
                if i==3:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 2 * X_SPACING, CARD_WIDTH*2.8
                if i == 4:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 1 * X_SPACING, SCREEN_HEIGHT - CARD_WIDTH
                if i == 5:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 2 * X_SPACING, SCREEN_HEIGHT - CARD_WIDTH
                if i == 6:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 1 * X_SPACING, SCREEN_HEIGHT - CARD_WIDTH*2.8
                if i == 7:
                    pile.position = START_X + SCREEN_WIDTH / 4 + 2 * X_SPACING, SCREEN_HEIGHT - CARD_WIDTH*2.8
     
                self.pile_mat_list.append(pile)
     
     
     
            # --- Create, shuffle, and deal the cards
     
            # Sprite list with all the cards, no matter what pile they are in.
            self.card_list = arcade.SpriteList()
     
            # Create every card
            for card_suit in CARD_SUITS:
                for card_value in CARD_VALUES:
                    card = Card(card_suit, card_value, CARD_SCALE)
                    card.position = START_X, SCREEN_HEIGHT/2
                    self.card_list.append(card)
     
            # Shuffle the cards
            for pos1 in range(len(self.card_list)):
                pos2 = random.randrange(len(self.card_list))
                self.card_list[pos1], self.card_list[pos2] = self.card_list[pos2], self.card_list[pos1]
     
            # Create a list of lists, each holds a pile of cards.
            self.piles = [[] for _ in range(PILE_COUNT)]
     
            # Put all the cards in the bottom face-down pile
            for card in self.card_list:
                self.piles[BOTTOM_FACE_DOWN_PILE].append(card)
     
            # - Pull from that pile into the middle piles, all face-down
            # Loop for each pile
            for pile_no in range(2, 10):
                # Deal proper number of cards for that pile
                # Pop the card off the deck we are dealing from
                card = self.piles[BOTTOM_FACE_DOWN_PILE].pop()
                # Put in the proper pile
                self.piles[pile_no].append(card)
                # Move card to same position as pile we just put it in
                card.position = self.pile_mat_list[pile_no].position
                # Put on top in draw order
                self.pull_to_top(card)
     
            #Track turn
            self.turn = 1
     
        def on_update(self, delta_time):
            #called auto every 60fps to update objects
            self.player.draw()
            self.mummy.draw()
     
        def on_draw(self, player1=None,player2=None):
            # called auto every 60fps to update objects
            """ Render the screen. """
            # Clear the screen
            arcade.start_render()
     
            #Setup les 2 premiers tours
            if self.turn == 1:
                player1 = Player(0, 0, 0, 0)
                player2 = Player(0, 0, 0, 0)
                Player.change_attribute(player1,1,2,0,0)
                Player.change_attribute(player2,0,0,0,0)
            elif self.turn == 2:
                Player.change_attribute(player2,1,2,0,0)
            elif self.turn % 2 == 0 and self.turn>2:
                Player.change_attribute(player2,1,2,0,0)
            else:
                Player.change_attribute(player1,1,2,0,0)
            # Draw the mats the cards go on to
            self.pile_mat_list.draw()
     
            # Draw the cards
            self.card_list.draw()
     
            #Draw Player
            self.player.draw()
            self.mummy.draw()
     
            # Draw our turn on the screen, scrolling it with the viewport
            if self.turn % 2 == 0:
                turn_text = f"Turn: {self.turn}"
                TireCarte_text = f"TireCarte: {player2.TireCarte}"
                SeeOwnGame_text = f"SeeOwngame: {player2.SeeOwnGame}"
                SeeEnemyGame_text = f"SeeEnemy: {player2.SeeEnemyGame}"
                arcade.draw_text(turn_text, 130, 80,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(TireCarte_text, 130, 120,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(SeeOwnGame_text, 130, 140,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(SeeEnemyGame_text, 130, 160,
                                 arcade.csscolor.WHITE, 18)
            else:
                turn_text = f"Turn: {self.turn}"
                TireCarte_text = f"TireCarte: {player1.TireCarte}"
                SeeOwnGame_text = f"SeeOwngame: {player1.SeeOwnGame}"
                SeeEnemyGame_text = f"SeeEnemy: {player1.SeeEnemyGame}"
                arcade.draw_text(turn_text, 130, 600,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(TireCarte_text, 130, 640,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(SeeOwnGame_text, 130, 660,
                                 arcade.csscolor.WHITE, 18)
                arcade.draw_text(SeeEnemyGame_text, 130, 680,
                                 arcade.csscolor.WHITE, 18)
     
        def pull_to_top(self, card):
            """ Pull card to top of rendering order (last to render, looks on-top) """
            # Find the index of the card
            index = self.card_list.index(card)
            # Loop and pull all the other cards down towards the zero end
            for i in range(index, len(self.card_list) - 1):
                self.card_list[i] = self.card_list[i + 1]
            # Put this card at the right-side/top/size of list
            self.card_list[len(self.card_list) - 1] = card
     
        def on_key_press(self, symbol: int, modifiers: int):
            """ User presses key """
            if symbol == arcade.key.R:
                # Restart
                self.setup()
     
        def on_mouse_press(self, x, y, button, key_modifiers):
            """ Called when the user presses a mouse button. """
     
            # Get list of cards we've clicked on
            cards = arcade.get_sprites_at_point((x, y), self.card_list)
                    # Have we clicked on a card?
            if len(cards) > 0:
                    # Might be a stack of cards, get the top one
                primary_card = cards[-1]
                    # Figure out what pile the card is in
                pile_index = self.get_pile_for_card(primary_card)
     
                    # Check turn and use power
                if pile_index == BOTTOM_FACE_DOWN_PILE:
                    if self.turn % 2 == 0:
                        if self.player2.TireCarte:
                                    # Flip three cards
                            for i in range(1):
                                        # If we ran out of cards, stop
                                if len(self.piles[BOTTOM_FACE_DOWN_PILE]) == 0:
                                    break
                                    # Get top card
                                card = self.piles[BOTTOM_FACE_DOWN_PILE][-1]
                                    # Flip face up
                                card.face_up()
                                    # Move card position to bottom-right face up pile
                                card.position = self.pile_mat_list[BOTTOM_FACE_UP_PILE].position
                                    # Remove card from face down pile
                                self.piles[BOTTOM_FACE_DOWN_PILE].remove(card)
                            # Move card to face up list
                                self.piles[BOTTOM_FACE_UP_PILE].append(card)
                            # Put on top draw-order wise
                                self.pull_to_top(card)
                                self.player2.TireCarte -=1
     
                elif 1<pile_index<6:
                    if self.turn % 2 == 0:
                        if player2.SeeOwnGame:
                            if primary_card.is_face_down:
                                    primary_card.face_up()
                                    x=player2.SeeOwnGame -1
                                    Player.change_attribute(player2,None,x,None,None)
                    else:
                        if player1.SeeOwnGame:
                            if primary_card.is_face_down:
                                    primary_card.face_up()
                                    x = player1.SeeOwnGame - 1
                                    Player.change_attribute(player1,None, x,None,None )
                                    player1.SeeOwnGame-=1
     
                elif 5< pile_index:
                    if self.turn % 2 == 0:
                        if self.player2.SeeEnemyGame:
                            if primary_card.is_face_down:
                                    primary_card.face_up()
                                    self.player2.SeeEnemyGame -= 1
                    else:
                        if self.player1.SeeEnemyGame:
                            if primary_card.is_face_down:
                                    primary_card.face_up()
                                    self.player1.SeeEnemyGame -= 1
     
     
            else:
               # Click on a mat instead of a card?
                mats = arcade.get_sprites_at_point((x, y), self.pile_mat_list)
                if len(mats) > 0:
                    mat = mats[0]
                    mat_index = self.pile_mat_list.index(mat)
     
                    # Is it our turned over flip mat? and no cards on it?
                    if mat_index == BOTTOM_FACE_DOWN_PILE and len(self.piles[BOTTOM_FACE_DOWN_PILE]) == 0:
                            # Flip the deck back over so we can restart
                            temp_list = self.piles[BOTTOM_FACE_UP_PILE].copy()
                            for card in reversed(temp_list):
                                card.face_down()
                                self.piles[BOTTOM_FACE_UP_PILE].remove(card)
                                self.piles[BOTTOM_FACE_DOWN_PILE].append(card)
                                card.position = self.pile_mat_list[BOTTOM_FACE_DOWN_PILE].position
     
        def remove_card_from_pile(self, card):
            """ Remove card from whatever pile it was in. """
            for pile in self.piles:
                if card in pile:
                    pile.remove(card)
                    break
     
        def get_pile_for_card(self, card):
            """ What pile is this card in? """
            for index, pile in enumerate(self.piles):
                if card in pile:
                    return index
     
        def move_card_to_new_pile(self, card, pile_index):
            """ Move the card to a new pile """
            self.remove_card_from_pile(card)
            self.piles[pile_index].append(card)
     
        def on_mouse_release(self, x: float, y: float, button: int,
                             modifiers: int):
            """ Called when the user presses a mouse button. """
            cards = arcade.get_sprites_at_point((x, y), self.card_list)
     
            # Have we clicked on a card?
            if len(cards) > 0:
     
                # Might be a stack of cards, get the top one
                primary_card = cards[-1]
                # Figure out what pile the card is in
                pile_index = self.get_pile_for_card(primary_card)
     
                if 1<pile_index<9:
                    if primary_card.is_face_up:
                        # Is the card face down? In one of those middle 7 piles? Then flip up
                        primary_card.face_down()
     
            # If we don't have any cards, who cares
            if len(self.held_cards) == 0:
                pass
     
     
     
            # We are no longer holding cards
            self.held_cards = []
     
            if self.turn % 2 ==0:
                print(self.player1)
                if self.player2(0, 0, 0, 0):
                        self.turn+=1
            else:
                print(player1.SeeOwnGame + player1.SeeEnemyGame+player1.TireCarte+player1.JetteCarte)
                if player1.SeeOwnGame + player1.SeeEnemyGame+player1.TireCarte+player1.JetteCarte ==0:
                        self.turn+=1
     
        def on_mouse_motion(self, x: float, y: float, dx: float, dy: float):
            """ User moves mouse """
     
            # If we are holding cards, move them with the mouse
            for card in self.held_cards:
                card.center_x += dx
                card.center_y += dy
     
     
     
     
    def main():
        """ Main method """
        window = MyGame()
        window.setup()
        arcade.run()
     
    if __name__ == "__main__":
        main()
    Merci d'avance de m'avoir lu.
    Mandra

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Salut,

    Lisez juste le message d'erreur: local variable 'player2' referenced before assignment.
    Vous obtiendrez le même en écrivant:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    def f():
         print(a)
         a = 1
    que a soit définit comme variable globale ou pas.

    Et à la base Python vous dit juste que pour accéder a une variable, il faut l'avoir créé avant... ou que si a est variable globale et qu'on y accède puis qu'on y assigne quelque chose, il faut la déclarer "global" à l'entrée de la fonction.

    Pour le reste, c'est une très bonne idée de récupérer du code sur Internet mais pour le modifier, il faut avoir un niveau quasi équivalent de celui qui l'a écrit sinon bonjour la galère.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Nouveau membre du Club
    Homme Profil pro
    Assistant aux utilisateurs
    Inscrit en
    Octobre 2017
    Messages
    50
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Assistant aux utilisateurs

    Informations forums :
    Inscription : Octobre 2017
    Messages : 50
    Points : 28
    Points
    28
    Par défaut
    Citation Envoyé par wiztricks Voir le message
    Salut,


    Et à la base Python vous dit juste que pour accéder a une variable, il faut l'avoir créé avant... ou que si a est variable globale et qu'on y accède puis qu'on y assigne quelque chose, il faut la déclarer "global" à l'entrée de la fonction.


    - W
    Comme il s'agit de récupérer l'attribut de la classe player2, pas de déclarer une nouvelle variable, ma syntaxe doit etre mauvaise, pouvez-vous me conseiller comment modifier depuis la classe Game l'attribut player1.SeeOwnGame appartenant à la classe Player ?

    Citation Envoyé par wiztricks Voir le message
    Salut,


    Et à la base Python vous dit juste que pour accéder a une variable, il faut l'avoir créé avant... ou que si a est variable globale et qu'on y accède puis qu'on y assigne quelque chose, il faut la déclarer "global" à l'entrée de la fonction.

    Pour le reste, c'est une très bonne idée de récupérer du code sur Internet mais pour le modifier, il faut avoir un niveau quasi équivalent de celui qui l'a écrit sinon bonjour la galère.

    - W
    C'est un moyen d'apprentissage et qui permet d'avoir de vrais résultats rapidement afin de rester motivé D'ailleurs j'ai déjà bien avancé dans le jeu mais j'avoue rester bloqué de nombreuses heures sans avancer.

    Merci d'avance.
    Mandra

  4. #4
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Salut,

    Citation Envoyé par Mandragore99 Voir le message
    C'est un moyen d'apprentissage et qui permet d'avoir de vrais résultats rapidement afin de rester motivé D'ailleurs j'ai déjà bien avancé dans le jeu mais j'avoue rester bloqué de nombreuses heures sans avancer.
    Chacun est libre de suivre son chemin.
    Pour le reste, votre vie n'est pas en danger...

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Candidat au Club
    Homme Profil pro
    Passionné
    Inscrit en
    Mai 2021
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Yonne (Bourgogne)

    Informations professionnelles :
    Activité : Passionné

    Informations forums :
    Inscription : Mai 2021
    Messages : 2
    Points : 3
    Points
    3
    Par défaut
    Salut,

    Je pense que tu peux t'aider de la documentation suivante pour résoudre ton problème :

    https://arcade.academy/tutorials/card_game/index.html#

    J'ai réalisé pas à pas le tutoriel et le code fonctionne :

    Code Python : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    """
    Solitaire clone.
    """
    import arcade
    import random
     
    # Screen title and size
    SCREEN_WIDTH = 1024
    SCREEN_HEIGHT = 768
    SCREEN_TITLE = "Drag and Drop Cards"
     
    # Constants for sizing
    CARD_SCALE = 0.6
     
    # How big are the cards?
    CARD_WIDTH = 140 * CARD_SCALE
    CARD_HEIGHT = 190 * CARD_SCALE
     
    # How big is the mat we'll place the card on?
    MAT_PERCENT_OVERSIZE = 1.25
    MAT_HEIGHT = int(CARD_HEIGHT * MAT_PERCENT_OVERSIZE)
    MAT_WIDTH = int(CARD_WIDTH * MAT_PERCENT_OVERSIZE)
     
    # How much space do we leave as a gap between the mats?
    # Done as a percent of the mat size.
    VERTICAL_MARGIN_PERCENT = 0.10
    HORIZONTAL_MARGIN_PERCENT = 0.10
     
    # The Y of the bottom row (2 piles)
    BOTTOM_Y = MAT_HEIGHT / 2 + MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # The X of where to start putting things on the left side
    START_X = MAT_WIDTH / 2 + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT
     
    # Card constants
    CARD_VALUES = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    CARD_SUITS = ["Clubs", "Hearts", "Spades", "Diamonds"]
     
    # The Y of the top row (4 piles)
    TOP_Y = SCREEN_HEIGHT - MAT_HEIGHT / 2 - MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # The Y of the middle row (7 piles)
    MIDDLE_Y = TOP_Y - MAT_HEIGHT - MAT_HEIGHT * VERTICAL_MARGIN_PERCENT
     
    # How far apart each pile goes
    X_SPACING = MAT_WIDTH + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT
     
    # If we fan out cards stacked on each other, how far apart to fan them?
    CARD_VERTICAL_OFFSET = CARD_HEIGHT * CARD_SCALE * 0.3
     
    # Constants that represent "what pile is what" for the game
    PILE_COUNT = 13
    BOTTOM_FACE_DOWN_PILE = 0
    BOTTOM_FACE_UP_PILE = 1
    PLAY_PILE_1 = 2
    PLAY_PILE_2 = 3
    PLAY_PILE_3 = 4
    PLAY_PILE_4 = 5
    PLAY_PILE_5 = 6
    PLAY_PILE_6 = 7
    PLAY_PILE_7 = 8
    TOP_PILE_1 = 9
    TOP_PILE_2 = 10
    TOP_PILE_3 = 11
    TOP_PILE_4 = 12
     
    # Face down image
    FACE_DOWN_IMAGE = ":resources:images/cards/cardBack_red2.png"
     
    class Card(arcade.Sprite):
        """ Card sprite """
     
        def __init__(self, suit, value, scale=1):
            """ Card constructor """
     
            # Attributes for suit and value
            self.suit = suit
            self.value = value
     
            # Image to use for the sprite when face up
            self.image_file_name = f":resources:images/cards/card{self.suit}{self.value}.png"
            self.is_face_up = False
            super().__init__(FACE_DOWN_IMAGE, scale, hit_box_algorithm="None")
     
        def face_down(self):
            """ Turn card face-down """
            self.texture = arcade.load_texture(FACE_DOWN_IMAGE)
            self.is_face_up = False
     
        def face_up(self):
            """ Turn card face-up """
            self.texture = arcade.load_texture(self.image_file_name)
            self.is_face_up = True
     
        @property
        def is_face_down(self):
            """ Is this card face down? """
            return not self.is_face_up
     
            # Call the parent
            super().__init__(self.image_file_name, scale, hit_box_algorithm="None")
     
            # Create a list of lists, each holds a pile of cards.
            self.piles = None
     
     
    class MyGame(arcade.Window):
        """ Main application class. """
     
        def __init__(self):
            super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
     
            # Sprite list with all the cards, no matter what pile they are in.
            self.card_list = None
     
            arcade.set_background_color(arcade.color.AMAZON)
     
            # List of cards we are dragging with the mouse
            self.held_cards = None
     
            # Original location of cards we are dragging with the mouse in case
            # they have to go back.
            self.held_cards_original_position = None
     
            # Sprite list with all the mats tha cards lay on.
            self.pile_mat_list = None
     
        def setup(self):
            """ Set up the game here. Call this function to restart the game. """
     
            # List of cards we are dragging with the mouse
            self.held_cards = []
     
            # Original location of cards we are dragging with the mouse in case
            # they have to go back.
            self.held_cards_original_position = []
     
            # ---  Create the mats the cards go on.
     
            # Sprite list with all the mats tha cards lay on.
            self.pile_mat_list: arcade.SpriteList = arcade.SpriteList()
     
            # Create the mats for the bottom face down and face up piles
            pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
            pile.position = START_X, BOTTOM_Y
            self.pile_mat_list.append(pile)
     
            pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
            pile.position = START_X + X_SPACING, BOTTOM_Y
            self.pile_mat_list.append(pile)
     
            # Create the seven middle piles
            for i in range(7):
                pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
                pile.position = START_X + i * X_SPACING, MIDDLE_Y
                self.pile_mat_list.append(pile)
     
            # Create the top "play" piles
            for i in range(4):
                pile = arcade.SpriteSolidColor(MAT_WIDTH, MAT_HEIGHT, arcade.csscolor.DARK_OLIVE_GREEN)
                pile.position = START_X + i * X_SPACING, TOP_Y
                self.pile_mat_list.append(pile)
     
            # Sprite list with all the cards, no matter what pile they are in.
            self.card_list = arcade.SpriteList()
     
            # Create every card
            for card_suit in CARD_SUITS:
                for card_value in CARD_VALUES:
                    card = Card(card_suit, card_value, CARD_SCALE)
                    card.position = START_X, BOTTOM_Y
                    self.card_list.append(card)
     
            # Shuffle the cards
            for pos1 in range(len(self.card_list)):
                pos2 = random.randrange(len(self.card_list))
                self.card_list[pos1], self.card_list[pos2] = self.card_list[pos2], self.card_list[pos1]
     
            # Create a list of lists, each holds a pile of cards.
            self.piles = [[] for _ in range(PILE_COUNT)]
     
            # Put all the cards in the bottom face-down pile
            for card in self.card_list:
                self.piles[BOTTOM_FACE_DOWN_PILE].append(card)
     
            # - Pull from that pile into the middle piles, all face-down
            # Loop for each pile
            for pile_no in range(PLAY_PILE_1, PLAY_PILE_7 + 1):
                # Deal proper number of cards for that pile
                for j in range(pile_no - PLAY_PILE_1 + 1):
                    # Pop the card off the deck we are dealing from
                    card = self.piles[BOTTOM_FACE_DOWN_PILE].pop()
                    # Put in the proper pile
                    self.piles[pile_no].append(card)
                    # Move card to same position as pile we just put it in
                    card.position = self.pile_mat_list[pile_no].position
                    # Put on top in draw order
                    self.pull_to_top(card)
     
            # Flip up the top cards
            for i in range(PLAY_PILE_1, PLAY_PILE_7 + 1):
                self.piles[i][-1].face_up()
     
            pass
     
        def pull_to_top(self, card):
            """ Pull card to top of rendering order (last to render, looks on-top) """
            # Find the index of the card
            index = self.card_list.index(card)
            # Loop and pull all the other cards down towards the zero end
            for i in range(index, len(self.card_list) - 1):
                self.card_list[i] = self.card_list[i + 1]
            # Put this card at the right-side/top/size of list
            self.card_list[len(self.card_list) - 1] = card
     
        def get_pile_for_card(self, card):
            """ What pile is this card in? """
            for index, pile in enumerate(self.piles):
                if card in pile:
                    return index
     
        def remove_card_from_pile(self, card):
            """ Remove card from whatever pile it was in. """
            for pile in self.piles:
                if card in pile:
                    pile.remove(card)
                    break
     
        def move_card_to_new_pile(self, card, pile_index):
            """ Move the card to a new pile """
            self.remove_card_from_pile(card)
            self.piles[pile_index].append(card)
     
     
        def on_draw(self):
            """ Render the screen. """
            # Clear the screen
            arcade.start_render()
     
            # Draw the mats the cards go on to
            self.pile_mat_list.draw()
     
            # Draw the cards
            self.card_list.draw()
     
        def on_mouse_press(self, x, y, button, key_modifiers):
            """ Called when the user presses a mouse button. """
     
            # Get list of cards we've clicked on
            cards = arcade.get_sprites_at_point((x, y), self.card_list)
     
            # Have we clicked on a card?
            if len(cards) > 0:
     
                # Might be a stack of cards, get the top one
                primary_card = cards[-1]
                # Figure out what pile the card is in
                pile_index = self.get_pile_for_card(primary_card)
     
                # Are we clicking on the bottom deck, to flip three cards?
                if pile_index == BOTTOM_FACE_DOWN_PILE:
                    # Flip three cards
                    for i in range(3):
                        # If we ran out of cards, stop
                        if len(self.piles[BOTTOM_FACE_DOWN_PILE]) == 0:
                            break
                        # Get top card
                        card = self.piles[BOTTOM_FACE_DOWN_PILE][-1]
                        # Flip face up
                        card.face_up()
                        # Move card position to bottom-right face up pile
                        card.position = self.pile_mat_list[BOTTOM_FACE_UP_PILE].position
                        # Remove card from face down pile
                        self.piles[BOTTOM_FACE_DOWN_PILE].remove(card)
                        # Move card to face up list
                        self.piles[BOTTOM_FACE_UP_PILE].append(card)
                        # Put on top draw-order wise
                        self.pull_to_top(card)
     
                elif primary_card.is_face_down:
                    # Is the card face down? In one of those middle 7 piles? Then flip up
                    primary_card.face_up()
                else:
     
                    # All other cases, grab the face-up card we are clicking on
                    self.held_cards = [primary_card]
                    # Save the position
                    self.held_cards_original_position = [self.held_cards[0].position]
                    # Put on top in drawing order
                    self.pull_to_top(self.held_cards[0])
     
                    # Is this a stack of cards? If so, grab the other cards too
                    card_index = self.piles[pile_index].index(primary_card)
                    for i in range(card_index + 1, len(self.piles[pile_index])):
                        card = self.piles[pile_index][i]
                        self.held_cards.append(card)
                        self.held_cards_original_position.append(card.position)
                        self.pull_to_top(card)
            else:
     
                # Click on a mat instead of a card?
                mats = arcade.get_sprites_at_point((x, y), self.pile_mat_list)
     
                if len(mats) > 0:
                    mat = mats[0]
                    mat_index = self.pile_mat_list.index(mat)
     
                    # Is it our turned over flip mat? and no cards on it?
                    if mat_index == BOTTOM_FACE_DOWN_PILE and len(self.piles[BOTTOM_FACE_DOWN_PILE]) == 0:
                        # Flip the deck back over so we can restart
                        temp_list = self.piles[BOTTOM_FACE_UP_PILE].copy()
                        for card in reversed(temp_list):
                            card.face_down()
                            self.piles[BOTTOM_FACE_UP_PILE].remove(card)
                            self.piles[BOTTOM_FACE_DOWN_PILE].append(card)
                            card.position = self.pile_mat_list[BOTTOM_FACE_DOWN_PILE].position                        
            pass
     
     
        def on_mouse_release(self, x: float, y: float, button: int,
                             modifiers: int):
            """ Called when the user presses a mouse button. """
     
            # If we don't have any cards, who cares
            if len(self.held_cards) == 0:
                return
     
            # Find the closest pile, in case we are in contact with more than one
            pile, distance = arcade.get_closest_sprite(self.held_cards[0], self.pile_mat_list)
            reset_position = True
     
            # See if we are in contact with the closest pile
            if arcade.check_for_collision(self.held_cards[0], pile):
     
                # What pile is it?
                pile_index = self.pile_mat_list.index(pile)
     
                #  Is it the same pile we came from?
                if pile_index == self.get_pile_for_card(self.held_cards[0]):
                    # If so, who cares. We'll just reset our position.
                    pass
     
                # Is it on a middle play pile?
                elif PLAY_PILE_1 <= pile_index <= PLAY_PILE_7:
                    # Are there already cards there?
                    if len(self.piles[pile_index]) > 0:
                        # Move cards to proper position
                        top_card = self.piles[pile_index][-1]
                        for i, dropped_card in enumerate(self.held_cards):
                            dropped_card.position = top_card.center_x, \
                                                    top_card.center_y - CARD_VERTICAL_OFFSET * (i + 1)
                    else:
                        # Are there no cards in the middle play pile?
                        for i, dropped_card in enumerate(self.held_cards):
                            # Move cards to proper position
                            dropped_card.position = pile.center_x, \
                                                    pile.center_y - CARD_VERTICAL_OFFSET * i
                    for card in self.held_cards:
                        # Cards are in the right position, but we need to move them to the right list
                        self.move_card_to_new_pile(card, pile_index)
     
                    # Success, don't reset position of cards
                    reset_position = False
     
                # Release on top play pile? And only one card held?
                elif TOP_PILE_1 <= pile_index <= TOP_PILE_4 and len(self.held_cards) == 1:
                    # Move position of card to pile
                    self.held_cards[0].position = pile.position
                    # Move card to card list
                    for card in self.held_cards:
                        self.move_card_to_new_pile(card, pile_index)
     
                    reset_position = False
     
            if reset_position:
                # Where-ever we were dropped, it wasn't valid. Reset the each card's position
                # to its original spot.
                for pile_index, card in enumerate(self.held_cards):
                    card.position = self.held_cards_original_position[pile_index]
     
            # We are no longer holding cards
            self.held_cards = []
            pass
     
        def on_mouse_motion(self, x: float, y: float, dx: float, dy: float):
            """ User moves mouse """
     
            # If we are holding cards, move them with the mouse
            for card in self.held_cards:
                card.center_x += dx
                card.center_y += dy
            pass
     
        def on_key_press(self, symbol: int, modifiers: int):
            """ User presses key """
            if symbol == arcade.key.R:
                # Restart
                self.setup()
     
     
    def main():
        """ Main method """
        window = MyGame()
        window.setup()
        arcade.run()
     
     
    if __name__ == "__main__":
        main()

    En espèrant que cela puisse t'aider pour fixer ton problème.

Discussions similaires

  1. Réponses: 3
    Dernier message: 06/03/2019, 01h58
  2. Réponses: 2
    Dernier message: 29/12/2015, 17h46
  3. local variable 'z' referenced before assignment
    Par djidji22 dans le forum Tkinter
    Réponses: 1
    Dernier message: 08/06/2012, 11h50
  4. Réponses: 6
    Dernier message: 10/08/2008, 16h42

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo