やってみる

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

pyxelで荒ぶる矩形

 ((((;゚Д゚))))ガクガクブルブル

成果物

demo

コード

import pyxel, random
class App:
    def __init__(self):
        self.window = Window()
        self.rect = RageRect()
        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 RageRect:
    def __init__(self, x=0, y=0, width=64, height=64, color=8):
        self.x = x
        self.y = y
        self.w = width
        self.h = height
        self.c = color
    def update(self):
        self.mx= random.randint(-4, 4)
        self.my= random.randint(-4, 4)
    def draw(self):
        pyxel.rect((pyxel.width / 2) - (self.w / 2) + self.mx, 
                   (pyxel.height/ 2) - (self.h / 2) + self.my,
                   self.w, self.h, self.c)

App()

 クラス分けした。これができると気持ちいい。

要点

アニメーション

class RageRect:
    def update(self):
        self.mx= random.randint(-4, 4)
        self.my= random.randint(-4, 4)
    def draw(self):
        pyxel.rect((pyxel.width / 2) - (self.w / 2) + self.mx, 
                   (pyxel.height/ 2) - (self.h / 2) + self.my,
                   self.w, self.h, self.c)
  1. update()でランダムに荒ぶる座標量を算出する: mx,my
  2. draw()で矩形を描画する

 手順1の座標を反映させることで、ランダムに座標が変わり、荒ぶってくれる。

ランダム

 -4から4までの範囲にある整数値を返す。

random.randint(-4, 4)

中央

 矩形を画面の中央に配置する。

(pyxel.width / 2) - (self.w / 2)
(pyxel.height/ 2) - (self.h / 2)

所感

 ついに動いた。でも勝手に動くだけじゃなぁ。ゲームといえば操作でしょ。

 次回、キー入力に応答して移動させてみる。

前回まで

対象環境

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