やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

pyxelでキーに応じて動く矩形

 十字キーで移動。

成果物

demo

コード

#!/usr/bin/env python3
# coding: utf8
import pyxel
class App:
    def __init__(self):
        self.window = Window()
        self.rect = MoveRect()
        pyxel.run(self.update, self.draw)
    def update(self):
        self.rect.update()
    def draw(self):
        self.window.draw()
        self.rect.draw()

class Window:
    def __init__(self, width=128, height=96, border_width=0):
        pyxel.init(width, height, border_width=border_width)
    def draw(self): pyxel.cls(0)

class MoveRect:
    def __init__(self, x=0, y=0, width=16, height=16, color=8):
        self.w = width
        self.h = height
        self.x = (pyxel.width / 2) - (self.w / 2)
        self.y = (pyxel.height/ 2) - (self.h / 2)
        self.c = color
    def update(self):
        if pyxel.btn(pyxel.KEY_LEFT) and self.x > 0: self.x -= 1
        if pyxel.btn(pyxel.KEY_RIGHT) and self.x < pyxel.width - self.w: self.x += 1
        if pyxel.btn(pyxel.KEY_UP) and self.y > 0: self.y -= 1
        if pyxel.btn(pyxel.KEY_DOWN) and self.y < pyxel.height - self.h: self.y += 1
    def draw(self):
        pyxel.rect(self.x, self.y, self.w, self.h, self.c)

App()

要点

キー入力判定

 pyxel.btn()関数。引数で指定されたキーが押下中ならtrueを返す。

pyxel.btn(pyxel.KEY_LEFT)
pyxel.btn(pyxel.KEY_RIGHT)
pyxel.btn(pyxel.KEY_UP)
pyxel.btn(pyxel.KEY_DOWN)

 キー定義は以下参照。

移動

 方向キーに応じて矩形の座標を加算・減算する。

self.x -= 1
self.x += 1
self.y -= 1
self.y += 1

 画面外に出て行かれたら見えなくなってしまう。画面の両端までを移動可能とする制限は以下。

self.x > 0
self.x < pyxel.width - self.w
self.y > 0
self.y < pyxel.height - self.h

所感

 やっと操作できた!

 ところで矩形じゃダサい。自分で描いたドット絵を使いたい。次回は画像の描画をやる。

前回まで

対象環境

$ uname -a
Linux raspberrypi 4.19.97-v7l+ #1294 SMP Thu Jan 30 13:21:14 GMT 2020 armv7l GNU/Linux