Skip to content

Instantly share code, notes, and snippets.

@drFabio
Last active December 27, 2017 13:26
Show Gist options
  • Save drFabio/527fe8d8b333bb40c22d051f2aaa9102 to your computer and use it in GitHub Desktop.
Save drFabio/527fe8d8b333bb40c22d051f2aaa9102 to your computer and use it in GitHub Desktop.
_onInterval () {
const now = Date.now()
this.setState((oldState) => {
let { score, level, lastLeft, obstacleIndex } = oldState
const { right, up, down } = this._controls
this._resetControls()
let obstacleSpeed = INITIAL_OBSTACLE_STEP + INITIAL_OBSTACLE_STEP * (0.2) * level
if (right) {
obstacleSpeed *= 1 * 6 * Math.min(right, 2)
}
let top = oldState.top + FALL_STEP
if (up) {
top -= JUMP_STEP * up
}
if (down) {
top += DROP_STEP * down
}
if (now - this._lastNewObstacles >= NEW_OBSTACLES_TIME) {
this._lastNewObstacles = now
const numOfObstacles = oldState.obstacles.length
if (numOfObstacles) {
lastLeft = oldState.obstacles[numOfObstacles - 1].left - INITIAL_OBSTACLE_STEP
if (lastLeft <= INITIAL_LEFT + PLAYER_WIDTH + OBSTACLE_MIN_DISTANCE) {
lastLeft = INITIAL_LEFT + PLAYER_WIDTH * 3
}
} else {
lastLeft = INITIAL_OBSTACLE_STEP
}
for (let i = 0; i < 2; i++) {
const newObstacle = this._createObstacle(lastLeft, obstacleIndex++, level)
if (obstacleIndex % OBSTACLES_PER_INDEX === 0) {
// level++
}
lastLeft = newObstacle.left
oldState.obstacles.push(newObstacle)
}
}
if (this._checkIfHit(top)) {
if (top >= (this._wrapper.offsetHeight - PLAYER_HEIGHT)) {
top = this._wrapper.offsetHeight - PLAYER_HEIGHT
} else if (top <= 0) {
top = 0
}
return { ...this._gameOver(), top }
}
const obstacles = []
let hasCollidedWithObstacle = false
oldState.obstacles.forEach((o) => {
if (o.left >= OBSTACLE_WIDTH * -1) {
const newLeft = o.left - obstacleSpeed
if (INITIAL_LEFT >= (newLeft + OBSTACLE_WIDTH)) {
o.scored = true
score += POINTS_PER_OBSTACLE
}
if (!hasCollidedWithObstacle) {
hasCollidedWithObstacle = this._checkColision(INITIAL_LEFT, top, o, newLeft)
}
o.left = newLeft
obstacles.push(o)
} else if (!o.scored) {
score += POINTS_PER_OBSTACLE
}
})
if (hasCollidedWithObstacle) {
return { ...this._gameOver(), top, obstacles, score, obstacleIndex: 0 }
}
return { top, obstacles, score, level, lastLeft, obstacleIndex }
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment