# Space 0.0.0 # Copyright 2001 Lja MultiMedia # May be used under the GNU GPL """space.py : A clone of the classic Space War""" import pygame, pygame.draw, random, sys YELLOW = (255, 255, 0) BLACK = (0, 0, 0) ORANGE = (255, 128, 0) def quit(s): print s.pos sys.exit() class particle(object): def __init__(self, pos, v, color, size, mass): self.pos = pos self.v = v self.color = color self.size = size self.mass = mass def move(self, sun): x = sun.pos[1] - self.pos[1] y = sun.pos[0] - self.pos[0] r2 = x * x + y * y f = sun.mass * self.mass / r2 t = abs(x) + abs(y) fx = x / t * f fy = y / t * f self.v[1] += fx self.v[0] += fy self.pos[0] += self.v[0] self.pos[1] += self.v[1] def draw(self, surface): return pygame.draw.circle(surface, self.color, self.pos, self.size, 0) def erase(self, surface, color): return pygame.draw.circle(surface, color, self.pos, self.size+1, 0) def main(): pygame.init() screen = pygame.display.set_mode((1024, 768), pygame.FULLSCREEN) sun = particle([512, 384], [0, 0], YELLOW, 8, 10000) ship = particle([200.0, 200.0], [4, 0], ORANGE, 2, 1) particles = [ship, sun] screen.fill(BLACK) while 1: r = [] r.append(ship.erase(screen, BLACK)) ship.move(sun) r.append(sun.draw(screen)) r.append(ship.draw(screen)) pygame.display.update(r) if (246 < ship.pos[0] < 254 and 246 < ship.pos[1] < 254) or \ ship.pos[0] < -1000 or ship.pos[1] < -1000 or \ ship.pos[0] >= 1250 or ship.pos[1] >= 1250: quit(ship) for e in pygame.event.get(pygame.KEYUP): if e.key == pygame.K_q: quit(ship) elif e.key == pygame.K_LEFT: ship.v[0] -= 1 elif e.key == pygame.K_RIGHT: ship.v[0] += 1 elif e.key == pygame.K_UP: ship.v[1] -= 1 elif e.key == pygame.K_DOWN: ship.v[1] += 1 if __name__ == "__main__": main()