pythonで15パズル

2020年4月23日木曜日

python

t f B! P L

15パズル作った

使ったゲームエンジン

pyxel
https://github.com/kitao/pyxel/blob/master/README.ja.md

コード

import random
import pyxel


class Board:
    def __init__(self):
        self.tile_size = 16
        self.board = [[1, 2, 3, 4],
                      [5, 6, 7, 8],
                      [9, 10, 11, 12],
                      [13, 14, 15, 16]]

    def draw(self):
        for y, line in enumerate(self.board):
            for x, tile_num in enumerate(line):
                if tile_num != 16:
                    self.draw_tile(x, y)

    def draw_tile(self, x, y):
        size = self.tile_size
        pyxel.rectb(x*size, y*size, size, size, 7)
        pyxel.text(x*size+5, y*size+6, str(self.board[y][x]), 7)


class App:
    def __init__(self):
        pyxel.init(64, 80)
        pyxel.mouse(True)
        self.board = Board()
        self.clearstr = ''
        for _ in range(1000):
            rand_x = random.randint(0, 3)
            rand_y = random.randint(0, 3)
            self.click_tile(rand_x, rand_y)
        pyxel.run(self.update, self.draw)

    def update(self):
        if sum(self.board.board, []) == list(range(1, 17)):
            self.clearstr = 'clear'
            return

        if pyxel.btnp(pyxel.MOUSE_LEFT_BUTTON):
            if not (0 <= pyxel.mouse_x <= self.board.tile_size * 4 and
                    0 <= pyxel.mouse_y <= self.board.tile_size * 4):
                return
            target_tile_x = pyxel.mouse_x // self.board.tile_size
            target_tile_y = pyxel.mouse_y // self.board.tile_size
            self.click_tile(target_tile_x, target_tile_y)

    def click_tile(self, x, y):
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        board = self.board.board
        for dx, dy in directions:
            if (0 <= x + dx <= 3 and 0 <= y + dy <= 3 and
                    board[y+dy][x+dx] == 16):
                tmp = board[y+dy][x+dx]
                board[y+dy][x+dx] = board[y][x]
                board[y][x] = tmp

    def draw(self):
        pyxel.cls(0)
        self.board.draw()
        pyxel.text(0, 70, self.clearstr, 7)


App()

おわり

QooQ