I’ve been messing around with Pygame to some extent. It’s a neat little Python library, designed for the easy creation of some simple games. It’s cross platform, so it runs anywhere Python does.

I haven’t done much; the tutorials on the website provide much more instruction than I could at the moment, but I’d like to post the short program I wrote just for my own amusement. The button merely makes an image appear on-screen and work as a “button.” I wrote a short Button class as well as the main script, and am pretty impressed with the results. It’s a very basic example, but maybe it’ll help someone out there having some trouble getting started.

#!/usr/bin/python
import pygame
from pygame.locals import *
import os
import sys
from Button import *

pygame.init()
window = pygame.display.set_mode((640,480))
screen = pygame.display.get_surface()
pygame.display.set_caption("My Game")
bgcolor = 255, 255, 255
clock = pygame.time.Clock()
button = Button("play.png","play_invert.png",50,50)
while True:
	for event in pygame.event.get() :
		if event.type == QUIT :
			sys.exit(0)
		elif event.type == MOUSEBUTTONDOWN :
			if button.isInside(event.pos) :
				button.switchStatus()
		elif event.type == MOUSEBUTTONUP and not button.getStatus() :
			button.switchStatus()
		else :
			print event
	time_passed = clock.tick(50)
	window.fill(bgcolor)
	button.draw(screen)
	pygame.display.flip()

That was the main script. It requires four things: pygame, Button.py (coming), and two images (the button up and the button pressed).

Those are the two images I used. This is Button.py:

import pygame
class Button :
	def __init__ (self, path, invertpath, x, y) :
		self.x = x
		self.y = y
		self.button = pygame.image.load(path)
		self.invert = pygame.image.load(invertpath)
		self.status = True
	def draw (self, screen) :
		screen.blit(self.button, (self.x, self.y))
	def isInside (self, pos) :
		if (pos[0] >= self.x) and (pos[0] <= self.x+self.button.get_width()) :
			if (pos[1] >= self.y) and (pos[1] <= self.y+self.button.get_height()) :
				return True
			else :
				return False
		else:
			return False
	def getStatus(self) :
		return self.status
	def switchStatus(self) :
		self.status = not self.status
		temp = self.button
		self.button = self.invert
		self.invert = temp

Of course I failed to comment it… figures. Most of this should be pretty obvious though.
Also: consider this code public domain. Use it, make money with it, I don’t care. Whatever. I shouldn’t have to say that, but I will just in case.