Basic Game Engine Basic Player Class, Enemy, Shoot.
from ion import * from kandinsky import * from time import sleep from math import sin, cos, radians SW, SH = 320, 222 black = (0, 0, 0) red = (255, 0, 0) bg = (240, 240, 240) def F(x, y, w, h, c): fill_rect(int(x), int(y), int(w), int(h), c) level = [ [0, 200, SW, 22, black], # Ground [100, 160, 60, 10, black], # Platform [200, 130, 40, 10, black] # Another Platform ] class Player: def __init__(self): self.x = 50 self.y = 100 self.w = 12 self.h = 12 self.vx = 0 self.vy = 0 self.on_ground = False self.rocks = [] def update(self): if keydown(KEY_LEFT): self.vx = -2 elif keydown(KEY_RIGHT): self.vx = 2 else: self.vx = 0 if keydown(KEY_UP) and self.on_ground: self.vy = -5 self.vy += 0.2 # gravity self.x += self.vx self.y += self.vy self.on_ground = False for rect in level: if self.collide(rect): if self.vy > 0: self.y = rect[1] - self.h self.vy = 0 self.on_ground = True elif self.vy < 0: self.y = rect[1] + rect[3] self.vy = 0 self.shoot() for rock in self.rocks: rock.update() self.rocks = [r for r in self.rocks if not r.dead] def collide(self, r): return (self.x < r[0] + r[2] and self.x + self.w > r[0] and self.y < r[1] + r[3] and self.y + self.h > r[1]) def shoot(self): if keydown(KEY_OK): direction = 0 if keydown(KEY_UP): direction = 90 elif keydown(KEY_RIGHT): direction = 45 elif keydown(KEY_LEFT): direction = 135 else: direction = 60 speed = 4 vx = speed * cos(radians(direction)) vy = -speed * sin(radians(direction)) self.rocks.append(Rock(self.x + self.w // 2, self.y + self.h // 2, vx, vy)) def draw(self): F(self.x, self.y, self.w, self.h, red) for rock in self.rocks: rock.draw() class Rock: def __init__(self, x, y, vx, vy): self.x = x self.y = y self.vx = vx self.vy = vy self.r = 4 self.dead = False def update(self): self.vy += 0.2 self.x += self.vx self.y += self.vy if self.y > SH: self.dead = True def draw(self): F(self.x, self.y, self.r, self.r, (120, 80, 40)) class Enemy: def __init__(self): self.x = 100 self.y = 188 self.w = 12 self.h = 12 self.vx = 1 def update(self): self.x += self.vx if self.x < 100 or self.x > 160 - self.w: self.vx *= -1 def draw(self): F(self.x, self.y, self.w, self.h, (0, 0, 255)) def draw_level(): for rect in level: F(*rect) def main(): p = Player() e = Enemy() while True: F(0, 0, SW, SH, bg) draw_level() p.update() p.draw() e.update() e.draw() for r in p.rocks: if (r.x < e.x + e.w and r.x + r.r > e.x and r.y < e.y + e.h and r.y + r.r > e.y): r.dead = True sleep(0.02) main()