-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghostMoves.js
74 lines (64 loc) · 2.32 KB
/
ghostMoves.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { DIRECTIONS, GRID_SIZE, OBJECT_TYPE } from './setup';
// Primitive random movement.
export function randomMovement(position, direction, objectExist, pacman) {
let dir = direction;
let nextMovePos = position + dir.movement;
// Create an array from the diretions objects keys
const keys = Object.keys(DIRECTIONS);
let validMoves = []
keys.forEach(key => {
dir = DIRECTIONS[key];
let nextMovePos = position + dir.movement;
if(!(objectExist(nextMovePos, OBJECT_TYPE.WALL) || objectExist(nextMovePos, OBJECT_TYPE.GHOST))){
validMoves.push(nextMovePos)
}
});
let attempts = 10
nextMovePos = validMoves[Math.floor(Math.random() * validMoves.length)]
let isClose = isCloser(pacman.pos, position, nextMovePos)
while(
objectExist(nextMovePos, OBJECT_TYPE.WALL) ||
objectExist(nextMovePos, OBJECT_TYPE.GHOST)) {
nextMovePos = validMoves[Math.floor(Math.random() * validMoves.length)]
attempts--
}
return { nextMovePos, direction: dir };
}
export function huntMovement(position, direction, objectExist, pacman){
let dir = direction
const keys = Object.keys(DIRECTIONS);
let decision = false
if (!pacman.powerPill){
decision = true
}
let validMoves = []
let nextMovePos = position + dir.movement;
keys.forEach(key => {
dir = DIRECTIONS[key];
let nextMovePos = position + dir.movement;
if(!(objectExist(nextMovePos, OBJECT_TYPE.WALL) || objectExist(nextMovePos, OBJECT_TYPE.GHOST))){
validMoves.push(nextMovePos)
}
});
let attempts = 10
nextMovePos = validMoves[Math.floor(Math.random() * validMoves.length)]
let isClose = isCloser(pacman.pos, position, nextMovePos)
while(
(decision ? isClose : !isClose) && attempts) {
nextMovePos = validMoves[Math.floor(Math.random() * validMoves.length)]
isClose = isCloser(pacman.pos, position, nextMovePos)
attempts--
}
dir = nextMovePos - position
return { nextMovePos, direction: dir}
}
function isCloser(pacmanPos, position, nextMovePos) {
const [pointX, pointY] = getCoords(pacmanPos)
const [posX, posY] = getCoords(position)
const [nextX, nextY] = getCoords(nextMovePos)
return Math.abs(nextX - pointX) > Math.abs(posX - pointX) ||
Math.abs(nextY - pointY) > Math.abs(posY - pointY)
}
function getCoords(index) {
return [index % GRID_SIZE, Math.floor(index / GRID_SIZE)]
}