7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでゲームパッドを使う

Last updated at Posted at 2022-03-06

pythonでpygameライブラリを使ってゲームパッドを使えるようにします

Gamepad.py
実行するとこんな感じ
2022-03-05 (1).png

環境

Windows10
python v3.9
pygame v2.1.2

ゲームパッドの状態

pygameでのゲームパッドのイベントは次のように割り当たっています
gamepad.png

プログラムの説明

ゲームパッドの初期化

pygame.joystick.init()
joy = pygame.joystick.Joystick(0)

ゲームパッドの状態を入れるClassを作っておきます

class JoyStatus:
    def __init__(self):
        self.axLx = 0
        self.axLy = 0
        self.axRx = 0
        self.axRy = 0
        self.hatL = 0
        self.hatR = 0
        self.hatU = 0
        self.hatD = 0
        self.btn = [0,0,0,0,0,0,0,0,0,0,0,0]

JStat = JoyStatus()

ゲームパッドの状態をJStatにセットします

スティックのアナログ値
JStat.axLx = joy.get_axis(0)
JStat.axLy = joy.get_axis(1)
JStat.axRx = joy.get_axis(2)
JStat.axRy = joy.get_axis(3)
十字キーの値
if hat_input[0] < 0:
    JStat.hatL = 0;     JStat.hatR = 1
elif hat_input[0] > 0:
    JStat.hatL = 1;     JStat.hatR = 0
else:
    JStat.hatL = 1;     JStat.hatR = 1

if hat_input[1] < 0:
    JStat.hatD = 0;     JStat.hatU = 1
elif hat_input[1] > 0:
    JStat.hatD = 1;     JStat.hatU = 0
else:
    JStat.hatD = 1;     JStat.hatU = 1

ボタンの状態
for i in range(12):
    if joy.get_button(i) == 1:
        JStat.btn[i] = 0
    else:
        JStat.btn[i] = 1

ウィンドウの初期化

pygame.init()
screen = pygame.display.set_mode((350, 250))
pygame.display.set_caption('JOYSTICK')
pygame.display.flip()

ウィンドウにお絵描き

円: pygame.draw.circle
矩形: pygame.draw.rect

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?