import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let P = (x, y, z) => new THREE.Vector3(x, y, z)
Array.prototype.pick = function() { return this.splice(Math.floor(Math.random()*this.length), 1)[0] }
HTMLElement.prototype.addNewChild = function(tag, properties) {
let child = document.createElement(tag)
for (let key in properties) {
child[key] = properties[key]
}
this.appendChild(child)
}
/* Contants */
const ROWS = 24
const SKYLINE = 20
const COLUMNS = 10
const DELAY = {
LOCK: 500,
FALL: 1000,
}
const FACING = {
NORTH: 0,
EAST: 1,
SOUTH: 2,
WEST: 3,
}
const TRANSLATION = {
NONE: P( 0, 0, 0),
LEFT: P(-1, 0, 0),
RIGHT: P( 1, 0, 0),
DOWN: P( 0, -1, 0),
}
const ROTATION = {
CW: 1, // ClockWise
CCW: -1, // CounterClockWise
}
const T_SPIN = {
NONE: "",
MINI: "PETITE
PIROUETTE",
T_SPIN: "PIROUETTE"
}
// score = AWARDED_LINE_CLEARS[tSpin][nbClearedLines]
const AWARDED_LINE_CLEARS = {
[T_SPIN.NONE]: [0, 1, 3, 5, 8],
[T_SPIN.MINI]: [1, 2],
[T_SPIN.T_SPIN]: [4, 8, 12, 16]
}
const KEY_NAMES = {
["ArrowLeft"]: "←",
["ArrowRight"]: "→",
["ArrowUp"]: "↑",
["ArrowDown"]: "↓",
[" "]: "Espace",
["Escape"]: "Échap",
["Enter"]: "Entrée",
["←"]: "ArrowLeft",
["→"]: "ArrowRight",
["↑"]: "ArrowUp",
["↓"]: "ArrowDown",
["Espace"]: " ",
["Échap"]: "Escape",
["Entrée"]: "Enter",
}
const CLEARED_LINES_NAMES = [
"",
"SOLO",
"DUO",
"TRIO",
"TETRA",
]
const GLOBAL_ROTATION = 0.0025
const DARK_TEXTURE_ROTATION = 0.0015
const DARK_MOVE_FORWARD = -0.0007
const DARK_OPACITY = 0.3
const COLORFULL_TEXTURE_ROTATION = 0.0015
const COLORFULL_MOVE_FORWARD = -0.002
const COLORFULL_OPACITY = 0.3
/* Classes */
class Scheduler {
constructor() {
this.intervalTasks = new Map()
this.timeoutTasks = new Map()
}
setInterval(func, delay, ...args) {
this.intervalTasks.set(func, window.setInterval(func, delay, ...args))
}
setTimeout(func, delay, ...args) {
this.timeoutTasks.set(func, window.setTimeout(func, delay, ...args))
}
clearInterval(func) {
if (this.intervalTasks.has(func))
window.clearInterval(this.intervalTasks.get(func))
this.intervalTasks.delete(func)
}
clearTimeout(func) {
if (this.timeoutTasks.has(func))
window.clearTimeout(this.timeoutTasks.get(func))
this.timeoutTasks.delete(func)
}
}
class Matrix extends THREE.Group {
init() {
this.cells = Array(ROWS).fill().map(() => Array(COLUMNS))
}
cellIsEmpty(p) {
return 0 <= p.x && p.x < COLUMNS &&
0 <= p.y && p.y < ROWS &&
!this.cells[p.y][p.x]
}
lock(piece) {
let minoes = Array.from(piece.children)
minoes.forEach(mino => {
mino.position.add(piece.position)
mino.material = piece.material
this.add(mino)
if (this.cellIsEmpty(mino.position)) {
this.cells[mino.position.y][mino.position.x] = mino
}
})
return minoes.some(mino => mino.position.y < SKYLINE)
}
clearLines() {
let nbClearedLines = 0
for (let y=ROWS-1; y>=0; y--) {
let row = this.cells[y]
if (row.filter(mino => mino).length == COLUMNS) {
nbClearedLines++
row.forEach(mino => this.remove(mino))
this.cells.splice(y, 1)
this.cells.push(Array(COLUMNS))
}
}
if (nbClearedLines) {
this.cells.forEach((rows, y) => {
rows.forEach((mino, x) => {
mino.position.set(x, y, 0)
})
})
}
return nbClearedLines
}
}
class NextQueue extends THREE.Group {
init() {
this.pieces = this.positions.map((position) => {
let piece = new Tetromino.random()
piece.position.copy(position)
this.add(piece)
return piece
})
}
shift() {
let fistPiece = this.pieces.shift()
let lastPiece = new Tetromino.random()
this.add(lastPiece)
this.pieces.push(lastPiece)
this.positions.forEach((position, i) => {
this.pieces[i].position.copy(position)
})
return fistPiece
}
}
NextQueue.prototype.positions = [P(0, 0, 0), P(0, -4, 0), P(0, -8, 0), P(0, -12, 0), P(0, -16, 0)]
class Mino extends THREE.Mesh {
constructor() {
super(Mino.prototype.geometry)
scene.add(this)
}
}
const minoFaceShape = new THREE.Shape()
minoFaceShape.moveTo(.1, .1)
minoFaceShape.lineTo(.1, .9)
minoFaceShape.lineTo(.9, .9)
minoFaceShape.lineTo(.9, .1)
minoFaceShape.lineTo(.1, .1)
const minoExtrudeSettings = {
steps: 1,
depth: .8,
bevelEnabled: true,
bevelThickness: .1,
bevelSize: .1,
bevelOffset: 0,
bevelSegments: 1
}
Mino.prototype.geometry = new THREE.ExtrudeGeometry(minoFaceShape, minoExtrudeSettings)
class Tetromino extends THREE.Group {
static randomBag = []
static get random() {
if (!this.randomBag.length) this.randomBag = [I, J, L, O, S, T, Z]
return this.randomBag.pick()
}
constructor() {
super()
this.rotatedLast = false
this.rotationPoint4Used = false
this.holdEnabled = true
for (let i=0; i<4; i++) {
this.add(new Mino())
}
this.facing = 0
this.locked = false
}
set facing(facing) {
this._facing = facing
this.minoesPosition[this.facing].forEach(
(position, i) => this.children[i].position.copy(position)
)
}
get facing() {
return this._facing
}
set locked(locked) {
this._locked = locked
if (locked) {
this.children.forEach(mino => mino.material = this.lockedMaterial)
} else {
this.children.forEach(mino => mino.material = this.material)
}
}
get locked() {
return this._locked
}
canMove(translation, facing=this.facing) {
let testPosition = this.position.clone().add(translation)
return this.minoesPosition[facing].every(minoPosition => matrix.cellIsEmpty(minoPosition.clone().add(testPosition)))
}
move(translation, testFacing) {
if (this.canMove(translation, testFacing)) {
scheduler.clearTimeout(lockDown)
this.position.add(translation)
if (!testFacing) {
this.rotatedLast = false
ghost.copy(this)
}
if (this.canMove(TRANSLATION.DOWN)) {
this.locked = false
scene.add(ghost)
} else {
this.locked = true
scene.remove(ghost)
scheduler.setTimeout(lockDown, stats.lockDelay)
}
return true
} else if (translation == TRANSLATION.DOWN) {
this.locked = true
if (!scheduler.timeoutTasks.has(lockDown))
scheduler.setTimeout(lockDown, stats.lockDelay)
}
}
rotate(rotation) {
let testFacing = (this.facing + rotation + 4) % 4
return this.srs[this.facing][rotation].some((translation, rotationPoint) => {
if (this.move(translation, testFacing)) {
//rotateSound.play()
this.facing = testFacing
this.rotatedLast = true
if (rotationPoint == 4) this.rotationPoint4Used = true
//favicon.href = this.favicon_href
ghost.copy(this)
return true
}
})
}
get tSpin() {
return T_SPIN.NONE
}
}
// Super Rotation System
// freedom of movement = srs[piece.facing][rotation]
Tetromino.prototype.srs = [
{ [ROTATION.CW]: [P(0, 0, 0), P(-1, 0, 0), P(-1, 1, 0), P(0, -2, 0), P(-1, -2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P( 1, 0, 0), P( 1, 1, 0), P(0, -2, 0), P( 1, -2, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P( 1, 0, 0), P( 1, -1, 0), P(0, 2, 0), P( 1, 2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P( 1, 0, 0), P( 1, -1, 0), P(0, 2, 0), P( 1, 2, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P( 1, 0, 0), P( 1, 1, 0), P(0, -2, 0), P( 1, -2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P(-1, 0, 0), P(-1, 1, 0), P(0, -2, 0), P(-1, -2, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P(-1, 0, 0), P(-1, -1, 0), P(0, 2, 0), P(-1, 2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P(-1, 0, 0), P(-1, -1, 0), P(0, 2, 0), P(-1, 2, 0)] },
]
const minoRenderTarget = new THREE.WebGLCubeRenderTarget(256)
minoRenderTarget.texture.type = THREE.HalfFloatType
const minoCamera = new THREE.CubeCamera(1, 1000, minoRenderTarget)
minoCamera.position.set(5, 10, 0)
Tetromino.prototype.lockedMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
class I extends Tetromino {}
I.prototype.minoesPosition = [
[P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0), P(2, 0, 0)],
[P( 1, 1, 0), P(1, 0, 0), P(1, -1, 0), P(1, -2, 0)],
[P(-1, -1, 0), P(0, -1, 0), P(1, -1, 0), P(2, -1, 0)],
[P( 0, 1, 0), P(0, 0, 0), P(0, -1, 0), P(0, -2, 0)],
]
I.prototype.srs = [
{ [ROTATION.CW]: [P(0, 0, 0), P(-2, 0, 0), P( 1, 0, 0), P(-2, -1, 0), P( 1, 2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P(-1, 0, 0), P( 2, 0, 0), P(-1, 2, 0), P( 2, -1, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P(-1, 0, 0), P( 2, 0, 0), P(-1, 2, 0), P( 2, -1, 0)], [ROTATION.CCW]: [P(0, 0, 0), P( 2, 0, 0), P(-1, 0, 0), P( 2, 1, 0), P(-1, -2, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P( 2, 0, 0), P(-1, 0, 0), P( 2, 1, 0), P(-1, -2, 0)], [ROTATION.CCW]: [P(0, 0, 0), P( 1, 0, 0), P(-2, 0, 0), P( 1, -2, 0), P(-2, 1, 0)] },
{ [ROTATION.CW]: [P(0, 0, 0), P( 1, 0, 0), P(-2, 0, 0), P( 1, -2, 0), P(-2, 1, 0)], [ROTATION.CCW]: [P(0, 0, 0), P(-2, 0, 0), P( 1, 0, 0), P(-2, -1, 0), P( 1, 2, 0)] },
]
I.prototype.material = new THREE.MeshBasicMaterial({
color: 0xafeff9,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
I.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xafeff9,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class J extends Tetromino {}
J.prototype.minoesPosition = [
[P(-1, 1, 0), P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0)],
[P( 0, 1, 0), P( 1, 1, 0), P(0, 0, 0), P(0, -1, 0)],
[P( 1, -1, 0), P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0)],
[P( 0, 1, 0), P(-1, -1, 0), P(0, 0, 0), P(0, -1, 0)],
]
J.prototype.material = new THREE.MeshBasicMaterial({
color: 0xb8b4ff,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
J.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xb8b4ff,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class L extends Tetromino {}
L.prototype.minoesPosition = [
[P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0), P( 1, 1, 0)],
[P(0, 1, 0), P(0, 0, 0), P(0, -1, 0), P( 1, -1, 0)],
[P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0), P(-1, -1, 0)],
[P(0, 1, 0), P(0, 0, 0), P(0, -1, 0), P(-1, 1, 0)],
]
L.prototype.material = new THREE.MeshBasicMaterial({
color: 0xfdd0b7,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
L.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xfdd0b7,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class O extends Tetromino {}
O.prototype.minoesPosition = [
[P(0, 0, 0), P(1, 0, 0), P(0, 1, 0), P(1, 1, 0)]
]
O.prototype.srs = [
{[ROTATION.CW]: [], [ROTATION.CCW]: []}
]
O.prototype.material = new THREE.MeshBasicMaterial({
color: 0xffedac,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
O.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xffedac,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class S extends Tetromino {}
S.prototype.minoesPosition = [
[P(-1, 0, 0), P(0, 0, 0), P( 0, 1, 0), P(1, 1, 0)],
[P( 0, 1, 0), P(0, 0, 0), P( 1, 0, 0), P(1, -1, 0)],
[P(-1, -1, 0), P(0, 0, 0), P( 1, 0, 0), P(0, -1, 0)],
[P(-1, 1, 0), P(0, 0, 0), P(-1, 0, 0), P(0, -1, 0)],
]
S.prototype.material = new THREE.MeshBasicMaterial({
color: 0xC8FBA8,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
S.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xC8FBA8,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class T extends Tetromino {
get tSpin() {
if (this.rotatedLast) {
let [a, b, c, d] = this.tSlots[piece.facing]
.map(p => !matrix.cellIsEmpty(p.clone().add(this.position)))
if (a && b && (c || d))
return T_SPIN.T_SPIN
else if (c && d && (a || b))
return this.rotationPoint4Used ? T_SPIN.T_SPIN : T_SPIN.MINI
}
return T_SPIN.NONE
}
}
T.prototype.minoesPosition = [
[P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0), P( 0, 1, 0)],
[P( 0, 1, 0), P(0, 0, 0), P(1, 0, 0), P( 0, -1, 0)],
[P(-1, 0, 0), P(0, 0, 0), P(1, 0, 0), P( 0, -1, 0)],
[P( 0, 1, 0), P(0, 0, 0), P(0, -1, 0), P(-1, 0, 0)],
]
T.prototype.tSlots = [
[P(-1, 1, 0), P( 1, 1, 0), P( 1, -1, 0), P(-1, -1, 0)],
[P( 1, 1, 0), P( 1, -1, 0), P(-1, -1, 0), P(-1, 1, 0)],
[P( 1, -1, 0), P(-1, -1, 0), P(-1, 1, 0), P( 1, 1, 0)],
[P(-1, -1, 0), P(-1, 1, 0), P( 1, 1, 0), P( 1, -1, 0)],
]
T.prototype.material = new THREE.MeshBasicMaterial({
color: 0xedb2ff,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
T.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xedb2ff,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class Z extends Tetromino {}
Z.prototype.minoesPosition = [
[P(-1, 1, 0), P( 0, 1, 0), P(0, 0, 0), P( 1, 0, 0)],
[P( 1, 1, 0), P( 1, 0, 0), P(0, 0, 0), P( 0, -1, 0)],
[P(-1, 0, 0), P( 0, 0, 0), P(0, -1, 0), P( 1, -1, 0)],
[P( 0, 1, 0), P(-1, 0, 0), P(0, 0, 0), P(-1, -1, 0)]
]
Z.prototype.material = new THREE.MeshBasicMaterial({
color: 0xffb8c5,
reflectivity: .6,
envMap: minoRenderTarget.texture
})
Z.prototype.ghostMaterial = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
color: 0xffb8c5,
reflectivity: .6,
envMap: minoRenderTarget.texture,
transparent: true,
opacity: 0.3
})
class Ghost extends Tetromino {
copy(piece) {
this.position.copy(piece.position)
this.facing = piece.facing
this.minoesPosition = piece.minoesPosition
piece.children.forEach((mino, i) => {
this.children[i].position.copy(mino.position)
this.children[i].material = piece.ghostMaterial
})
while (this.canMove(TRANSLATION.DOWN)) this.position.y--
}
}
Ghost.prototype.minoesPosition = [
[P(0, 0, 0, 0), P(0, 0, 0, 0), P(0, 0, 0, 0), P(0, 0, 0, 0)],
]
class Settings {
constructor() {
this.form = settingsForm
this.load()
this.modal = new bootstrap.Modal('#settingsModal')
settingsModal.addEventListener('shown.bs.modal', () => {
resumeButton.focus()
})
}
load() {
for (let element of settingsForm.elements) {
if (element.name) {
if (localStorage[element.name]) element.value = localStorage[element.name]
}
}
}
save() {
for (let element of settingsForm.elements) {
if (element.name) {
localStorage[element.name] = element.value
}
}
}
init() {
this.form.onsubmit = newGame
levelInput.name = "startLevel"
levelInput.disabled = false
titleHeader.innerHTML = "teTra"
resumeButton.innerHTML = "Jouer"
}
show() {
resumeButton.disabled = false
settings.form.classList.remove('was-validated')
settings.modal.show()
settings.form.reportValidity()
}
getInputs() {
for (let input of this.form.querySelectorAll("input[type='text']")) {
this[input.name] = KEY_NAMES[input.value] || input.value
}
for (let input of this.form.querySelectorAll("input[type='number'], input[type='range']")) {
this[input.name] = input.valueAsNumber
}
for (let input of this.form.querySelectorAll("input[type='checkbox']")) {
this[input.name] = input.checked == true
}
this.keyBind = {}
for (let actionName in playerActions) {
this.keyBind[settings[actionName]] = playerActions[actionName]
}
}
}
function changeKey(input) {
prevValue = input.value
input.value = ""
input.onkeydown = function (event) {
event.preventDefault()
input.value = KEY_NAMES[event.key] || event.key
input.blur()
}
input.onblur = function (event) {
if (input.value == "") input.value = prevValue
input.onkeydown = null
input.onblur = null
}
}
class Stats {
constructor() {
this.modal = new bootstrap.Modal('#statsModal')
this.load()
}
load() {
this.highScore = Number(localStorage["highScore"]) || 0
}
init() {
this.score = 0
this.goal = 0
this.combo = 0
this.b2b = 0
this.startTime = new Date()
this.lockDelay = DELAY.LOCK
this.totalClearedLines = 0
this.nbQuatris = 0
this.nbTSpin = 0
this.maxCombo = 0
this.maxB2B = 0
}
set score(score) {
this._score = score
if (score > this.highScore) {
this.highScore = score
}
}
get score() {
return this._score
}
set level(level) {
this._level = level
this.goal += level * 5
if (level <= 20){
this.fallPeriod = 1000 * Math.pow(0.8 - ((level - 1) * 0.007), level - 1)
}
if (level > 15)
this.lockDelay = 500 * Math.pow(0.9, level - 15)
levelInput.value = level
messagesSpan.addNewChild("div", { className: "show-level-animation", innerHTML: `