Python3 : Collidepoint error in Memory game

标签 python python-3.x pygame

我正在编写一个名为“Memory”的游戏,其中包含随机顺序的 8 对图像(16 个图像)。游戏开始时,16个必须显示相同的背景图像。玩家单击任何图 block 后,图 block 会从背景图像翻转为前景图像。 目前,我无法使用碰撞点方法翻转瓷砖。请帮我。非常非常感谢!

import pygame
import random
import time

screen = pygame.display.set_mode((525, 435))

def main():
   pygame.init()
   pygame.display.set_mode((535, 435))
   pygame.display.set_caption('Memory')
   w_surface = pygame.display.get_surface() 
   game = Game(w_surface)
   game.play()
   pygame.quit()

class Game:

   def __init__(self, surface):
      self.surface = surface
      self.bg_color = pygame.Color('black')
      self.FPS = 10
      self.game_Clock = pygame.time.Clock()
      self.close_clicked = False
      self.continue_game = True
      Tile.set_surface(self.surface)
      self.grid_size = 4
      self.grid = []
      self.score = 0
      imgnames = ['./images/' + str(i) + '.jpg' for i in range(1,9)]
      self.images = [pygame.image.load(name) for name in imgnames]
      self.shuffle = self.images + self.images
      random.shuffle(self.shuffle)
      self.create_grid(self.grid_size)

   def create_grid(self, grid_size):
      for row_num in range(grid_size):
         new_row = self.create_row(row_num, grid_size)
         self.grid.append(new_row)     

   def create_row(self, row_num, size):
      tile_height = self.surface.get_height() // size
      tile_width = self.surface.get_width() // (size+1)
      one_row = [ ]
      for col_num in range(size):
         y = row_num * tile_height + 5
         x = col_num * tile_width + 5
         i = col_num*size + row_num
         one_tile = Tile(x, y, tile_width, tile_height, self.shuffle[i], self.surface)
         one_row.append(one_tile)
      return one_row

   def play(self):
      while not self.close_clicked:
         self.handle_events()
         self.draw()
         if self.continue_game:
            self.update()
            self.decide_continue()
         self.game_Clock.tick(self.FPS)

   def handle_events(self):
      events = pygame.event.get()
      for event in events:
         if event.type == pygame.QUIT:
            self.close_clicked = True
         elif event.type == pygame.MOUSEBUTTONUP:
            position = pygame.mouse.get_pos()
            if pygame.MOUSEBUTTONUP.collidepoint(one_tile):
               self.flip = True


   def draw(self):
      self.surface.fill(self.bg_color)
      self.draw_score()
      for row in self.grid:
         for tile in row:
            tile.draw()
      pygame.display.update()

   def update(self):
      self.score = pygame.time.get_ticks() // 1000

   def decide_continue(self):
      pass

   def draw_score(self):
      score_string = str(self.score)    
      score_font = pygame.font.SysFont('', 48)
      score_fg_color = pygame.Color('white')
      score_image = score_font.render(score_string, True, score_fg_color)
      self.surface.blit(score_image, (500,10))

class Tile:
   def __init__(self, pos_x, pos_y, tile_numx, tile_numy, image, surface):
      self.pos_x = pos_x
      self.pos_y = pos_y
      self.numx = tile_numx
      self.numy = tile_numy
      self.image = image
      self.surface = surface
      self.flip = False

   @classmethod
   def set_surface(cls, surface):
      cls.surface = surface   

   def draw(self):
      x = 0
      y = 0
      i = 0
      if self.flip == False:
         screen.blit(pygame.image.load('./images/bg.jpg'),(self.pos_x,self.pos_y))
      elif self.flip == True:
         screen.blit(self.image,(self.pos_x,self.pos_y))



main()

最佳答案

添加 pygame.Rect 类型的 .rect 属性到类Tile。矩形必须具有图 block 的位置和图像的大小。可以通过 get_rect() 创建从图像表面:

class Tile:
   def __init__(self, pos_x, pos_y, tile_numx, tile_numy, image, surface):
      self.pos_x = pos_x
      self.pos_y = pos_y
      self.numx = tile_numx
      self.numy = tile_numy 
      self.image = image
      self.rect = self.image.get_rect(topleft = (self.pos_x,self.pos_y))
      self.surface = surface
      self.flip = False

   # [...]

按下鼠标按钮时,迭代网格中的所有图 block 。使用collidepoint()验证鼠标是否位于包含图 block 覆盖区域的矩形 (tile.rect) 上:

class Game:

   # [...] 

   def handle_events(self):
      events = pygame.event.get()
      for event in events:
         if event.type == pygame.QUIT:
            self.close_clicked = True
         elif event.type == pygame.MOUSEBUTTONUP:

            # get mouse position
            position = event.pos
            # position = pygame.mouse.get_pos() # <--- this would do the same

            # for all tiles
            for row in self.grid:
               for tile in row:

                  # test if mouse is on the tile and flip it
                  if tile.rect.collidepoint(position):
                     tile.flip = True

关于Python3 : Collidepoint error in Memory game,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182627/

相关文章:

python - 在函数中创建类对象并保留它们

python - 如何在 PyGame 中集成折线图查看器?

python - 在不丢失键盘状态的情况下调整 pygame 窗口大小

python - "import tensorflow as tf"导入错误 : Could not find 'cudart64_90.dll'

python - 如何修复 'django.db.utils.OperationalError: near "无“: syntax error' db. sqlite3?

python-3.x - 如何让 discord bot 队列本地 mp3?

python - 在多核上运行 Python

python - Matplotlib slider 颜色变化

python - 无法将分类数据转换为数字 OneHotEncoder

python - 正则表达式:匹配所有内容,直到 `:` 或 `(`