1+ let pos = 0 ;
2+ const pacArray = [
3+ [ './images/PacMan1.png' , './images/PacMan2.png' ] ,
4+ [ './images/PacMan3.png' , './images/PacMan4.png' ] ,
5+ ] ;
6+ let direction = 0 ;
7+ const pacMen = [ ] ; // This array holds all the pacmen
8+
9+ // This function returns an object with random values
10+ function setToRandom ( scale ) {
11+ return {
12+ x : Math . random ( ) * scale ,
13+ y : Math . random ( ) * scale ,
14+ } ;
15+ }
16+
17+ // Factory to make a PacMan at a random position with random velocity
18+ function makePac ( ) {
19+ // returns an object with random values scaled {x: 33, y: 21}
20+ let velocity = setToRandom ( 10 ) ; // {x:?, y:?}
21+ let position = setToRandom ( 200 ) ;
22+
23+ // Add image to div id = game
24+ let game = document . getElementById ( 'game' ) ;
25+ let newimg = document . createElement ( 'img' ) ;
26+ newimg . style . position = 'absolute' ;
27+ newimg . src = './images/PacMan1.png' ;
28+ newimg . width = 100 ;
29+
30+ // TODO: set position here
31+ newimg . style . top = position . y ;
32+ newimg . style . left = position . x ;
33+ // TODO add new Child image to game
34+ game . appendChild ( newimg ) ;
35+
36+ // return details in an object
37+ return {
38+ position,
39+ velocity,
40+ newimg,
41+ } ;
42+ }
43+
44+ function update ( ) {
45+ // loop over pacmen array and move each one and move image in DOM
46+ pacMen . forEach ( ( item ) => {
47+ checkCollisions ( item ) ;
48+ item . position . x += item . velocity . x ;
49+ item . position . y += item . velocity . y ;
50+
51+ item . newimg . style . left = item . position . x ;
52+ item . newimg . style . top = item . position . y ;
53+ } ) ;
54+ setTimeout ( update , 20 ) ;
55+ }
56+
57+ function checkCollisions ( item ) {
58+ // TODO: detect collision with all walls and make pacman bounce
59+ if ( item . position . x + item . newimg . width > window . innerWidth )
60+ {
61+ item . velocity . x = - item . velocity . x ;
62+ }
63+ else if ( item . position . y + item . newimg . height > window . innerHeight )
64+ {
65+ item . velocity . y = - item . velocity . y ;
66+ }
67+ else if ( item . position . x <= 0 )
68+ {
69+ item . velocity . x = - item . velocity . x ;
70+ }
71+ else if ( item . position . y <= 0 )
72+ {
73+ item . velocity . y = - item . velocity . y ;
74+ }
75+ }
76+
77+
78+ function makeOne ( ) {
79+ pacMen . push ( makePac ( ) ) ; // add a new PacMan
80+ }
81+
82+ //don't change this line
83+ if ( typeof module !== 'undefined' ) {
84+ module . exports = { checkCollisions, update, pacMen } ;
85+ }
0 commit comments