非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

Pythonで2Dゲームを作る(2) キー操作で図形を動かす

   

前回に続きPythonによる2DゲームライブラリPygameについてです。

前回は図形を描画しただけですが、今回はキーボードで図形を動かす方法を紹介します。

[ad#top-1]

今回ベースとなる画面

今回キー操作で動かす図形は以下の通り赤い長方形です。これを[←]で左に、[→]で右に動かしていきます。

 

ソースコードはこちら。

import pygame

BLACK = (0, 0, 0)
RED = (255, 0, 0)

pygame.init()
screen = pygame.display.set_mode((640, 480))
myclock = pygame.time.Clock()

flag=0
x=250
while flag==0:
  for event in pygame.event.get():
    if event.type==pygame.QUIT: flag=1
  #赤い四角を描画
  screen.fill(BLACK)
  rect = pygame.Rect(x, 200, 100, 30)
  pygame.draw.rect(screen, RED,rect)
  pygame.display.flip()
  myclock.tick(60)

pygame.quit()
 

 

以下の行で長方形の位置とサイズを設定していますが、変数xを変えてあげれば図形の位置は変化します。

rect = pygame.Rect(x, 200, 100, 30)

 

キーイベントを取得し図形を動かす

whileループ内に3行を追加してキー操作でxの値を変化させています。

import pygame

BLACK = (0, 0, 0)
RED = (255, 0, 0)

pygame.init()
screen = pygame.display.set_mode((640, 480))
myclock = pygame.time.Clock()

flag=0
x=250
while flag==0:
  for event in pygame.event.get():
    if event.type==pygame.QUIT: flag=1
  #以下の3行を追加
  press = pygame.key.get_pressed()
  if(press[pygame.K_LEFT] and x>0): x-=5
  if(press[pygame.K_RIGHT] and x<540): x+=5
  #赤い四角を描画
  screen.fill(BLACK)
  rect = pygame.Rect(x, 200, 100, 30)
  pygame.draw.rect(screen, RED, rect)
  pygame.display.flip()
  myclock.tick(60)

pygame.quit()
 

 

以下が図形を動かしている動画です。[←]で左に、[→]で右に動かしています。

 

以下が追加した2行。1行目で押下したキーを取得し、[←]でxをマイナス5、[→]でxをプラス5にしているのがわかります。条件文でx&gt;0x&lt;540としているのは、画面左端と右端で図形を止めるため(はみ出さないため)です。

press = pygame.key.get_pressed()
if(press[pygame.K_LEFT] and x>0): x-=5
if(press[pygame.K_RIGHT] and x<540): x+=5

 

[ad#ad-1]

スポンサーリンク

 - Python