so://phie

game-engine

A lightweight JavaScript game engine
git clone git://soophie.de/game-engine

blob: 0bb8aa85f54d540b4e67a9f192378881257c0e67 (1503 bytes)[doc][blame][raw]

1import { scaleCanvas } from './canvas.js';

2

3export class Game {

4 constructor(width, height, { fps } = {}) {

5 this.width = width || 900;

6 this.height = height || 600;

7 this.fps = 1000 / (fps || 60);

8 this.then = Date.now();

9 this.canvas = document.createElement('canvas');

10 scaleCanvas(this.canvas, this.width, this.height);

11 this.g = this.canvas.getContext('2d');

12 }

13 start() {

14 requestAnimationFrame(this.loop.bind(this));

15 this.update();

16 this.g.save();

17 this.render(this.g),

18 this.g.restore();

19 }

20 loop() {

21 requestAnimationFrame(this.loop.bind(this));

22 this.now = Date.now();

23 this.elapsed = this.now - this.then;

24 if(this.elapsed > this.fps) {

25 this.then = this.now - (this.elapsed % this.fps);

26 this.update();

27 this.g.save();

28 this.render(this.g),

29 this.g.restore();

30 }

31 }

32 update() {

33 // empty

34 }

35 render() {

36 this.g.clearRect(0, 0, this.width, this.height);

37 }

38}

39

40export class Group {

41 constructor() {

42 this.items = [];

43 }

44 update() {

45 for(let item of this.items) {

46 item.update();

47 }

48 }

49 render(g) {

50 for(let item of this.items) {

51 g.save();

52 item.render(g);

53 g.restore();

54 }

55 }

56 add(item) {

57 this.items.push(item);

58 }

59 get() {

60 return this.items;

61 }

62}

63

64export class Surface {

65 constructor(x, y, width, height) {

66 this.rect = new Rect(x, y, width, height);

67 }

68 update() {

69 // empty

70 }

71 render() {

72 // empty

73 }

74}

75

76export class Rect {

77 constructor(x, y, width, height) {

78 this.x = x;

79 this.y = y;

80 this.width = width;

81 this.height = height;

82 }