簡體   English   中英

如何修改我的代碼,以便列表中的圖像顯示在行和圖塊中?

[英]How can I modify my code so that images from a list appear in rows and tiles?

我正在做的是創建一個記憶瓷磚游戲,它需要一個包含 8 個圖像的列表,每個圖像一次出現兩次。 這是我的代碼中有問題的部分。

self.images_1_2_8 = ['image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image8.bmp','image7.bmp','image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image7.bmp','image8.bmp']

  self.collect_images = []
  for select_images in self.images_1_2_8:       
     image = pygame.image.load(select_images)

     #width = image.get_width()
     #height = image.get_height()
     random.shuffle(self.self.images_1_2_8)

  for row_index in range(0, self.board_size):
     row = []
     for col_index in range(0,self.board_size):
        width = image.get_width()
        height = image.get_height()            
        x = width * col_index
        y = height * row_index
        tile = Tile(x,y, self.select_images_1_2_8[image_index], self.surface)         row.append(tile)
     self.board.append(row)

我不斷收到的錯誤消息是:builtins.TypeError: 'pygame.Surface' object is not subscriptable

我發現這意味着getitem () 屬性沒有將我的圖像作為列表讀取? 我想這就是它的意思。 如果我刪除列表 [row_index*self.board_size+col_index],圖像就會出現(列表中只有一張圖像,它填充了所有 16 個索引)。

我知道這是一個簡單的修復,但我是 python 的新手,我已經在這工作了幾個星期......如果有人能夠提供幫助,請提前致謝!

看代碼,應該從選擇collect_images而不是image這僅僅是最后一個加載的(單一)圖像(不是列表)。 代碼就在那里,只需要調整一下。

self.images_1_2_8 = ['image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image8.bmp','image7.bmp','image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image7.bmp','image8.bmp']

  self.collect_images = []
  for select_images in self.images_1_2_8:       
     image = pygame.image.load(select_images)
     self.collect_images.append(image)           # <-- make the list in collect_images
     #width = image.get_width()
     #height = image.get_height()
     random.shuffle(self.collect_images)         # <-- shuffle loaded images


  for row_index in range(0, self.board_size):
     row = []
     for col_index in range(0,self.board_size):
        width = image.get_width()
        height = image.get_height()            
        x = width * col_index
        y = height * row_index
        tile = Tile(x,y, collect_images[image_index], self.surface)  # <-- use the image-list
        row.append(tile)
     self.board.append(row)

沒有用於更新image_index代碼。 請確保這是從 0 增加到列表中的最大圖像數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM