import pygame,sys,threading,math
from pygame.locals import *
from rgb_color import *
pygame.init()
pygame.init()
class MainWindow:
def __init__ (self, x,y, color):
self.screen = pygame.display.set_mode((x,y))
self.running = True
self.color = color
self.clock = pygame.time.Clock()
def run (self):
screen = self.screen; blit = screen.blit
x = 0
while self.running:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
dude.following = True
if event.type == MOUSEBUTTONUP:
if not pygame.mouse.get_pressed()[0]:
dude.following = False
if event.type == KEYDOWN:
if event.key == K_RIGHT: dude.moving = "right"
if event.key == K_LEFT: dude.moving = "left"
if event.key == K_DOWN: dude.moving = "down"
if event.key == K_UP: dude.moving = "up"
if event.type == KEYUP:
if event.key == K_RIGHT: dude.moving = False
if event.key == K_LEFT: dude.moving = False
if event.key == K_DOWN: dude.moving = False
if event.key == K_UP: dude.moving = False
if event.type == QUIT:
self.running = False
pygame.quit(); sys.exit(); break
self.gameActions()
self.updateSurface(screen, blit)
def gameActions (self):
""" This is where to place all major game functions. """
self.time_passed = self.clock.tick(40)/1000.0
if dude.moving: dude.move()
if dude.following: dude.follow()
def updateSurface (self, screen, blit):
screen.fill(self.color)
blit(dude.img, (dude.xPos,dude.yPos))
pygame.display.update()
class Dude:
def __init__ (self, speed):
self.img = pygame.image.load("littleman.png").convert_alpha()
self.xPos = 375 # TODO: Get w/h and center dynamically
self.yPos = 275 #
self.speed = speed # Pixels/second
self.moving = False
self.following = False
def move (self):
pixels = self.getSpeed()
if self.moving == "right": self.xPos += pixels
if self.moving == "left": self.xPos -= pixels
if self.moving == "up": self.yPos -= pixels
if self.moving == "down": self.yPos += pixels
def follow (self):
mouse_pos = pygame.mouse.get_pos()
diff = (self.xPos-mouse_pos[0], self.yPos-mouse_pos[1])
vector = math.sqrt(diff[0]**2 + diff[1]**2)
distance = (self.xPos/vector, self.yPos/vector)
if (self.xPos, self.yPos) == mouse_pos:
return
if mouse_pos[0] >= self.xPos:
self.xPos += distance[0]
else:
self.xPos -= distance[0]
if mouse_pos[1] >= self.yPos:
self.yPos += distance[1]
else:
self.yPos -= distance[1]
def getSpeed (self):
""" Returns: (float) pixels to move for current frame. """
return (game.time_passed * self.speed)
if __name__ == "__main__":
game = MainWindow(800,600,WHITE)
dude = Dude(100)
game.run()