今日は「クラスを使う」を学びます。
もくじ
今日書いたコード
結果:1つのニコちゃんが上から降ってきてバウンドを繰り返す。徐々にバウンドが小さくなる。
import pyxel
class Animation:
def __init__(self): #Animationクラスの初期化時に呼ばれる
pyxel.init(120, 120, title = "Day09")
self.nico_x = 60
self.nico_y = 10
self.nico_col_a = pyxel.rndi(2, 9)
self.nico_col_b = pyxel.rndi(10, 18)
self.nico_height = 10
self.nico_vy = 0
pyxel.run(self.update, self.draw)
def draw_nico(self, x, y, col_a, col_b): # ニコちゃんを描く関数
pyxel.circ(x, y, 5, col_a)
pyxel.line(x - 2, y - 2, x - 2, y - 1, col_b)
pyxel.line(x + 2, y - 2, x + 2, y - 1, col_b)
pyxel.line(x - 2, y + 2, x + 2, y + 2, col_b)
def update(self): #更新処理。ニコちゃんの座標を更新
self.nico_y += self.nico_vy
self.nico_vy += 0.1
nico_bouncy_y = pyxel.height - self.nico_height
if self.nico_y >= nico_bouncy_y:
self.nico_y = nico_bouncy_y
self.nico_vy = self.nico_vy * -0.95
def draw(self): #描画処理
pyxel.cls(1)
self.draw_nico(self.nico_x, self.nico_y, self.nico_col_a, self.nico_col_b)
Animation() #Animationクラスのインスタンスを作成。自動的に__init__が呼び出される

コードの要点
処理の流れ
classを定義(①~④をclassの中で定義)
①画面サイズ、ニコちゃんの座標と色
②ニコちゃんの絵柄
③ニコちゃんの座標更新
④背景とニコちゃんの描画処理
classの後にクラス名を書いて、字下げして関数を作っていく。クラスに追加した関数は必ず第一引数を
selfにする。__init__はクラスの中に定義できる特殊な関数で、クラス名()で呼び出される。
pyxel.run関数:pyxelアプリを開始し、フレーム更新時にゲームの更新処理と描画処理を行う関数を呼び出す
pyxel.run(update, draw)
updateは更新処理を行う関数、drawは描画処理を行う関数