Skip to content

Instantly share code, notes, and snippets.

@Mekire
Created September 5, 2015 23:10
Show Gist options
  • Save Mekire/7ada8e35fa2f24a00fd2 to your computer and use it in GitHub Desktop.
Save Mekire/7ada8e35fa2f24a00fd2 to your computer and use it in GitHub Desktop.
import sys
import math
import pygame as pg
class Block(pg.sprite.Sprite):
def __init__(self, pos, speed, next_move):
super(Block, self).__init__()
self.image = pg.Surface((50,50)).convert()
self.image.fill(pg.Color("red"))
self.rect = self.image.get_rect(center=pos)
self.exact_position = list(self.rect.center)
self.speed = speed #Pixels per second
self.target = None
self.vec = None
self.distance = None
self.next_move = next_move
def update(self, dt):
if self.target:
travelled = math.hypot(self.vec[0]*dt, self.vec[1]*dt)
self.distance -= travelled
if self.distance <= 0:
self.rect.center = self.exact_position = self.target
self.target = None
if self.next_move:
target = (550, self.next_move.rect.centery)
self.next_move.get_new_instruction(target)
else:
self.exact_position[0] += self.vec[0]*dt
self.exact_position[1] += self.vec[1]*dt
self.rect.center = self.exact_position
def draw(self, surface):
surface.blit(self.image, self.rect)
def get_new_instruction(self, target):
x = target[0]-self.exact_position[0]
y = target[1]-self.exact_position[1]
self.distance = math.hypot(x, y)
try:
self.vec = self.speed*x/self.distance, self.speed*y/self.distance
self.target = list(target)
except ZeroDivisionError:
pass
class Control(object):
def __init__(self):
pg.init()
pg.display.set_caption("Move To Target")
self.screen = pg.display.set_mode((500,500))
self.screen_rect = self.screen.get_rect()
self.clock = pg.time.Clock()
self.fps = 60.0
self.done = False
previous = None
blocks = []
for i in range(4):
pos = self.screen_rect.centerx, self.screen_rect.bottom-100-i*100
previous = Block(pos, 500, previous)
blocks.append(previous)
self.click_block = blocks[-1]
self.blocks = pg.sprite.Group(blocks)
def event_loop(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.done = True
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
if self.click_block.rect.collidepoint(event.pos):
target = 550, self.click_block.rect.centery
self.click_block.get_new_instruction(target)
def update(self, dt):
self.blocks.update(dt)
def draw(self):
self.screen.fill((30,40,50))
self.blocks.draw(self.screen)
def main_loop(self):
while not self.done:
dt = self.clock.tick(self.fps)/1000.0
self.event_loop()
self.update(dt)
self.draw()
pg.display.update()
def main():
app = Control()
app.main_loop()
pg.quit()
sys.exit()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment