Last active
February 27, 2019 14:25
-
-
Save killreal17/0649c23f2145ef02837ce1ec28ff736c to your computer and use it in GitHub Desktop.
fifteen version 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const readline = require('readline') | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
function get_random_arbitrary(min, max) { | |
return parseInt(Math.random() * (max - min) + min, 10) | |
} | |
const swap = (from_x, from_y, to_x, to_y, matrix) => { | |
let value = matrix[from_y][from_x] | |
matrix[from_y][from_x] = matrix[to_y][to_x] | |
matrix[to_y][to_x] = value | |
return matrix | |
} | |
const print_matrix = (matrix, score) => { | |
process.stdout.write("\u001b[2J\u001b[0;0H") | |
for(const str_y of matrix){ | |
console.log(str_y); | |
} | |
console.log('\n score: ' + score + '\n'); | |
} | |
const check_matrix = matrix => { | |
for(const str_y of matrix){ | |
for(let i = 0; i < str_y.length - 1; i++){ | |
if(str_y[i] > str_y[i + 1]){ | |
return false | |
} | |
} | |
} | |
return true | |
} | |
let matrix = [[' 2', ' 1', ' 3', ' 4'], [' 5', ' 6', ' 7', ' 8'], [' 9', '10', '11', '12'], ['13', '14', '15', ' ']] | |
const coordinates = [3, 3] | |
let score = 0 | |
const move = (command, matrix) =>{ | |
if((command == 's' || command == 1) && coordinates[0] - 1 >= 0){ | |
matrix = swap(coordinates[1], coordinates[0], coordinates[1], coordinates[0] - 1, matrix) | |
coordinates[0]-- | |
score++ | |
} | |
if((command == 'w' || command == 2) && coordinates[0] + 1 <= 3){ | |
matrix = swap(coordinates[1], coordinates[0], coordinates[1], coordinates[0] + 1, matrix) | |
coordinates[0]++ | |
score++ | |
} | |
if((command == 'd' || command == 3) && coordinates[1] - 1 >= 0){ | |
matrix = swap(coordinates[1], coordinates[0], coordinates[1] - 1, coordinates[0], matrix) | |
coordinates[1]-- | |
score++ | |
} | |
if((command == 'a' || command == 4) && coordinates[1] + 1 <= 3){ | |
matrix = swap(coordinates[1], coordinates[0], coordinates[1] + 1, coordinates[0] , matrix) | |
coordinates[1]++ | |
score++ | |
} | |
return matrix | |
} | |
const mix_matrix = matrix => { | |
let a | |
for(let i = 0; i < 100; i++){ | |
a = get_random_arbitrary(1, 5) | |
matrix = move(a, matrix) | |
} | |
return matrix | |
} | |
matrix = mix_matrix(matrix) | |
score = 0 | |
print_matrix(matrix, score) | |
rl.on('line', (input) => { | |
if(input == 'exit'){ | |
rl.close() | |
}else{ | |
matrix = move(input, matrix) | |
} | |
print_matrix(matrix, score) | |
if(check_matrix(matrix)){ | |
console.log('you win'); | |
rl.close() | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment