Skip to content

Instantly share code, notes, and snippets.

@catupper
Created January 6, 2012 15:31
Show Gist options
  • Select an option

  • Save catupper/1571068 to your computer and use it in GitHub Desktop.

Select an option

Save catupper/1571068 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
pygame.init()
N=15 ## w
M=15 ## h
Square_size=700/(max(N,M))
screen = pygame.display.set_mode( (700,700) )
pygame.display.set_caption("On Off")
Sprite=pygame.sprite.Sprite
class swit(Sprite):
def __init__ (self,x,y):
Sprite.__init__(self)
self.color=(0,0,0)
self.image=pygame.Surface((Square_size-2,Square_size-2))
self.image.fill(self.color)
self.rect=pygame.Rect(x*Square_size+1,y*Square_size+1,(x+1)*Square_size-2,(y+1)*Square_size-2)
self.mode=0
def update(self):
if(self.mode==0):self.color=(100,0,0)
if(self.mode==1):self.color=(255,0,0)
if(self.mode>=2):self.color=(self.color[0],120,120)
self.image.fill(self.color)
def draw(self,screen):
screen.blit(self.image,self.rect)
def main():
sysfont = pygame.font.SysFont(None, 80)
clock=pygame.time.Clock()
squares=[[swit(a,b) for a in range(N)]for b in range(M)]
mouse_pressed=False
Clear=False
while 1:
clock.tick(60)
pygame.display.flip()
mouse_press=pygame.mouse.get_pressed()[0]
if mouse_press and not mouse_pressed :
y,x = pygame.mouse.get_pos()
x/=Square_size
y/=Square_size
if(0<=x<M and 0<=y<N):
squares[x][y].mode^=1
if(x>0):squares[x-1][y].mode^=1
if(x<M-1):squares[x+1][y].mode^=1
if(y>0):squares[x][y-1].mode^=1
if(y<N-1):squares[x][y+1].mode^=1
mouse_pressed=mouse_press
for x in range(M):
for y in range(N):
if squares[x][y].mode>=2:
squares[x][y].mode-=2
y,x = pygame.mouse.get_pos()
y/=Square_size
x/=Square_size
if(0<=x<M and 0<=y<N and not mouse_press):
squares[x][y].mode+=2
if(x>0):squares[x-1][y].mode+=2
if(x<M-1):squares[x+1][y].mode+=2
if(y>0):squares[x][y-1].mode+=2
if(y<N-1):squares[x][y+1].mode+=2
Clear=True
for x in range(M):
for y in range(N):
squares[x][y].update()
squares[x][y].draw(screen)
Clear= Clear and squares[x][y].mode==1
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN and event.key == K_ESCAPE:
exit()
while(Clear):
pygame.display.update()
pygame.display.flip()
screen.blit(sysfont.render("Clear!",False,(80,12,50)),(100,100))
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
for x in range(M):
for y in range(N):
squares[x][y].mode=0
Clear=False
screen.fill((0,0,255))
pygame.display.update()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment