Skip to content

Instantly share code, notes, and snippets.

@Colk-tech
Last active October 20, 2023 06:10
Show Gist options
  • Save Colk-tech/5ab89347577c37ec2dbcb7dca6c332cb to your computer and use it in GitHub Desktop.
Save Colk-tech/5ab89347577c37ec2dbcb7dca6c332cb to your computer and use it in GitHub Desktop.
Pygame samples
import pygame
def main() -> None:
pygame.init()
print("Checking number of joysticks...")
print(f"{pygame.joystick.get_count()} joystick(s) found.")
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
for joystick in joysticks:
print(f"Joystick ({joystick.get_id()}) is {joystick.get_name()}.")
if __name__ == "__main__":
main()
# Originally from
# How To Use Joysticks & Controllers in PyGame - NeuralNine
# https://www.youtube.com/watch?v=ax3E0pjXVKs
from typing import Optional
import pygame
class Player(object):
def __init__(self):
self.player = pygame.rect.Rect((300, 400, 50, 50))
self.color = pygame.Color("red")
def move(self, dx, dy):
self.player.move_ip(dx, dy)
def change_color(self, color):
self.color = pygame.Color(color)
def draw(self, game_screen):
pygame.draw.rect(game_screen, self.color, self.player)
def main(
argc: Optional[int] = None, argv: Optional[list[str]] = None
) -> None:
pygame.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
for joystick in joysticks:
joystick.init()
print(f"Joystick ({joystick.get_id()}) is {joystick.get_name()}.")
player = Player()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 600))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
if event.type == pygame.JOYBUTTONDOWN:
if pygame.joystick.Joystick(0).get_button(0):
player.change_color("blue")
if pygame.joystick.Joystick(0).get_button(1):
player.change_color("red")
if pygame.joystick.Joystick(0).get_button(2):
player.change_color("yellow")
if pygame.joystick.Joystick(0).get_button(3):
player.change_color("green")
if pygame.joystick.Joystick(0).get_button(8):
player.change_color("white")
if event.type == pygame.JOYAXISMOTION:
print(event)
x_speed = round(pygame.joystick.Joystick(0).get_axis(0))
y_speed = round(pygame.joystick.Joystick(0).get_axis(1))
player.move(x_speed, y_speed)
screen.fill((0, 0, 0))
player.draw(screen)
pygame.display.update()
clock.tick(180)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment