iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0

明明今天是假日,但還是忙到只能寫一點點東西,看來我時間管理該好好加強...

首先我要先寫出點擊位置轉換方塊的功能

def getGemByPos(self, x, y):
    return self.all_gems[x][y]

def checkSelected(self, position):
    for x in range(NUMGRID):
        for y in range(NUMGRID):
            if self.getGemByPos(x, y).rect.collidepoint(*position):
                # 檢查點擊位置是否在方塊內
                a = self.getGemByPos(x, y)
                return [x, y]
    return None

接著對兩個方塊進行位置交換,目前不會判斷交換後是否有連三以及消除

def swapGem(self, gem1_pos, gem2_pos):
    gem1 = self.getGemByPos(*gem1_pos)
    gem2 = self.getGemByPos(*gem2_pos)

    gem1.target_x = gem2.rect.left
    gem1.target_y = gem2.rect.top
    gem2.target_x = gem1.rect.left
    gem2.target_y = gem1.rect.top
    gem1.rect.x = gem1.target_x
    gem1.rect.y = gem1.target_y
    gem2.rect.x = gem2.target_x
    gem2.rect.y = gem2.target_y
    self.all_gems[gem2_pos[0]][gem2_pos[1]] = gem1
    self.all_gems[gem1_pos[0]][gem1_pos[1]] = gem2

到這邊方法寫完了,接著就在event引用方法

for event in pygame.event.get():
    # 不知為何絕對要有這行才跑得動
    if event.type == pygame.QUIT: sys.exit()
    elif event.type == pygame.MOUSEBUTTONDOWN:
        # 判斷左鍵按壓
        if pygame.mouse.get_pressed()[0] == True:
            press_pos = pygame.mouse.get_pos()
            left_mouse_pressed = True
            print(press_pos)
            gem1_pos = self.checkSelected(press_pos)

    elif event.type == pygame.MOUSEBUTTONUP:
        # 判斷左鍵釋放
        if left_mouse_pressed == True:
            left_mouse_pressed == False
            release_pos = pygame.mouse.get_pos()
            print(release_pos)
            gem2_pos = self.checkSelected(release_pos)
            if gem1_pos != None and gem2_pos != None:
                # 判斷在鄰近方塊
                margin = gem1_pos[0] - gem2_pos[0] + gem1_pos[1] - gem2_pos[1]
                if abs(margin) == 1:
                    self.swapGem(gem1_pos, gem2_pos)

到這邊方塊已經可以交換了,明天來判斷版面上連3以上的方塊消除規則


上一篇
Day4 來把拼圖弄出來
下一篇
Day6 讓方塊掉下來
系列文
最近迷上了三消遊戲 那就來寫一個自動消珠程式吧30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言