十字キーで移動。
成果物
コード
#!/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
所感
やっと操作できた!
ところで矩形じゃダサい。自分で描いたドット絵を使いたい。次回は画像の描画をやる。
前回まで
- ラズパイ4Bにpyenvをインストールする(python 3.8.2)
- pyxelをインストールする(pyenv python3.8.2)
- pyxeleditorにおけるImageエディタの使い方
- pyxeleditorにおけるTileMapエディタの使い方
- pyxeleditorにおけるSoundエディタの使い方
- pyxeleditorにおけるMusicエディタの使い方
- pyxelのリソースにおける概念・制限まとめ
- pyxeleditorにおけるpyxresファイル形式まとめ
- pyxelのAPI調査
- pyxelで最小コード 窓を出す
- Pyxelで窓の境界線を消す
- 携帯ゲーム機の解像度
- pyxelで矩形を描画する
- pyxelで荒ぶる矩形
対象環境
- Raspbierry pi 4 Model B
- Raspbian buster 10.0 2019-09-26 ※
- bash 5.0.3(1)-release
- pyxel 1.3.1
$ uname -a Linux raspberrypi 4.19.97-v7l+ #1294 SMP Thu Jan 30 13:21:14 GMT 2020 armv7l GNU/Linux