Last active
July 21, 2021 06:32
-
-
Save jessecogollo/498b03aa3d88e495f84ad28ed5b2af55 to your computer and use it in GitHub Desktop.
Ejercicio ahorcado en JavaScript
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
const readline = require('readline') | |
const R = require('ramda') | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
const question = (question) => { | |
return new Promise(function (resolve) { | |
rl.question(question, function(value) { | |
return resolve(value) | |
}) | |
}) | |
} | |
const check = (word, display, c) => { | |
// https://github.com/ramda/ramda/blob/v0.27.0/source/zip.js | |
const lsitOfpairWords = R.zip(word.split(''), display.split('')) | |
const newDisplay = lsitOfpairWords.reduce((acc, pair) => { | |
const [x, y] = pair | |
return `${acc}${x === c ? c : y}` | |
}, '') | |
return { | |
correct: word.includes(c), | |
newDisplay | |
} | |
} | |
const turn = async (word, display, n) => { | |
try { | |
if (n === 0) { | |
console.log('Perdiste...') | |
process.exit(0) | |
} else if (word === display) { | |
console.log('Ganaste !!!') | |
process.exit(0) | |
} else { | |
await mkguess(word, display, n) | |
} | |
} catch (error) { | |
console.error('error', error) | |
} | |
} | |
const mkguess = async (word, display, n) => { | |
console.log(`${display} ${Array.from({ length: n }, _ => '*').join('')}`) | |
const q = await question('Ingresa tu letra: ') | |
const { correct, newDisplay } = check(word, display, q) | |
const newN = correct ? n : n-1 | |
turn(word, newDisplay, newN) | |
} | |
async function ahorcado(n) { | |
try { | |
const list = ["medellinjs", "javascript", "haskell", "curiosidad", "medellin", "Colombia"] | |
const num = Math.floor(Math.random() * list.length) | |
const word = list[num] | |
turn(word, Array.from(word.split(''), x => '-').join(''), n) | |
} catch(error) { | |
console.log('error', error) | |
} | |
} | |
const parseN = parseInt(process.argv[2], 10) | |
const n = isNaN(parseN) ? 2 : parseN | |
ahorcado(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment