Apr 21, 2011

SDL Perl をいじってみた

まったりと SDL::Manual を読みながら、新しくなった SDL Perl をいじってみました。

ゲームっぽい何かのテスト画面

chr_01.png

自キャラ画像

とりあえず、ムーヴハンドラやイベントハンドラを仕込んで自キャラを動かしてみるところまで。敵キャラやアイテムや衝突判定は次回へ持ち越しです。

#!/usr/local/bin/perl

use strict;
use warnings;
use SDL;
use SDL::Events;
use SDLx::App;
use SDLx::Rect;
use SDLx::Sprite;

# ウィンドウ全体の準備
my $app = SDLx::App->new(
                         width        => 512,
                         height       => 384,
                         title        => 'test',
                         dt           => 0.02,
                         exit_on_quit => 1,
                        );

# キャラクタを入れる器の準備
my $rect = { 
            chr => SDLx::Rect->new( $app->w / 2 - 16, $app->h / 5 * 4, 32, 32 ),
            v_x => 0,
           };

# キャラクタを入れる
my $chr = SDLx::Sprite->new(
                            image => 'chr_01.png', # 画像置き場へのパス
                            rect  => $rect->{chr},
                            );

# 表示
$app->add_show_handler(
    sub {
        $app->draw_rect( [ 0, 0, $app->w, $app->h - 45 ], 0x007bbbff ); # 空
        $app->draw_rect( [ 0, $app->h - 45, $app->w, 45 ], 0xc3d825ff ); # 地面
        $chr->draw( $app ); # キャラ
        # CPU使用率が 100% に振りきれるようならディレイを挟んでも良いかも?
        #$app->delay( 10 );
        $app->update;
    }
);

# 動き
$app->add_move_handler(
    sub {
        my ( $step, $app ) = @_;
        my $v_x = $rect->{v_x};
        $rect->{chr}->x( $rect->{chr}->x + ( $v_x * $step ) );

        # 左の移動限度
        if ( $rect->{chr}->left <= 0 ) {
            $rect->{chr}->left( 0 );
        }

        # 右の移動限度
        elsif ( $rect->{chr}->right >= $app->w ) {
            $rect->{chr}->right( $app->w );
        }
    }
);

# 操作
$app->add_event_handler(
    sub {
        my ( $event, $app ) = @_;

        # キーを押し込んだ場合
        if ( $event->type == SDL_KEYDOWN ) {

            # ←キーを押し込んで左へ
            if ( $event->key_sym == SDLK_LEFT ) {
                $rect->{v_x} = -2;
            }
            # →キーを押し込んで右へ
            elsif ( $event->key_sym == SDLK_RIGHT ) {
                $rect->{v_x} = 2;
            }
            # qキーまたは ESCキーを押して終了
            elsif ( 
                       $event->key_sym == SDLK_q 
                    or $event->key_sym == SDLK_ESCAPE
            ) {
                $app->stop();
            }
        }
        # キーを離した場合
        elsif ( $event->type == SDL_KEYUP ) {

            # ←キーや→キーを離したら自キャラが止まる
            if (
                    $event->key_sym == SDLK_LEFT
                 or $event->key_sym == SDLK_RIGHT
            ) {
                $rect->{v_x} = 0;
            }
        }
    }
);

# ループ開始
$app->run;

CPU の使用率が 100% に振り切れるのは、古い PC だから仕方ないとして、むむむ、自キャラの左右の移動速度があからさまに違うのは何故!?左右の移動速度に差が出るようには書いてない筈なんだけど…。

まだまだ問題山積みです。

Posted at 22:40 in perl | Comments/Trackbacks ()
Comments/Trackbacks
TrackBack ping me at
http://pochi.usamimi.info/blog/perl/SDL_Perl_game01.
Post a comment

writeback message: