diff --git a/03-projeto-mario-kart/node_modules/.package-lock.json b/03-projeto-mario-kart/node_modules/.package-lock.json new file mode 100644 index 0000000..31b3048 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/.package-lock.json @@ -0,0 +1,38 @@ +{ + "name": "aula", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/prompt-sync": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/prompt-sync/-/prompt-sync-4.2.0.tgz", + "integrity": "sha512-BuEzzc5zptP5LsgV5MZETjDaKSWfchl5U9Luiu8SKp7iZWD5tZalOxvNcZRwv+d2phNFr8xlbxmFNcRKfJOzJw==", + "license": "MIT", + "dependencies": { + "strip-ansi": "^5.0.0" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/03-projeto-mario-kart/node_modules/ansi-regex/index.js b/03-projeto-mario-kart/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..9e37ec3 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/ansi-regex/index.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; diff --git a/03-projeto-mario-kart/node_modules/ansi-regex/license b/03-projeto-mario-kart/node_modules/ansi-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/03-projeto-mario-kart/node_modules/ansi-regex/package.json b/03-projeto-mario-kart/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..66a43e1 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/ansi-regex/package.json @@ -0,0 +1,53 @@ +{ + "name": "ansi-regex", + "version": "4.1.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "^0.25.0", + "xo": "^0.23.0" + } +} diff --git a/03-projeto-mario-kart/node_modules/ansi-regex/readme.md b/03-projeto-mario-kart/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..d19c446 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/ansi-regex/readme.md @@ -0,0 +1,87 @@ +# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + + +## API + +### ansiRegex([options]) + +Returns a regex for matching ANSI escape codes. + +#### options + +##### onlyFirst + +Type: `boolean`
+Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/03-projeto-mario-kart/node_modules/prompt-sync/LICENSE b/03-projeto-mario-kart/node_modules/prompt-sync/LICENSE new file mode 100644 index 0000000..3f5ab36 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/prompt-sync/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 Paolo Fragomeni & David Mark Clements + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/03-projeto-mario-kart/node_modules/prompt-sync/README.md b/03-projeto-mario-kart/node_modules/prompt-sync/README.md new file mode 100644 index 0000000..2e72e71 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/prompt-sync/README.md @@ -0,0 +1,118 @@ +# SYNOPSIS +A sync prompt for node. very simple. no C++ bindings and no bash scripts. + +Works on Linux, OS X and Windows. + +# BASIC MODE +```js + +var prompt = require('prompt-sync')(); +// +// get input from the user. +// +var n = prompt('How many more times? '); +``` +# WITH HISTORY + +History is an optional extra, to use simply install the history plugin. + +```sh +npm install --save prompt-sync-history +``` + +```js +var prompt = require('prompt-sync')({ + history: require('prompt-sync-history')() //open history file +}); +//get some user input +var input = prompt() +prompt.history.save() //save history back to file +``` + +See the [prompt-sync-history](http://npm.im/prompt-sync-history) module +for options, or fork it for customized behaviour. + +# API + +## `require('prompt-sync')(config) => prompt` + +Returns an instance of the `prompt` function. +Takes `config` option with the following possible properties + +`sigint`: Default is `false`. A ^C may be pressed during the input process to abort the text entry. If sigint it `false`, prompt returns `null`. If sigint is `true` the ^C will be handled in the traditional way: as a SIGINT signal causing process to exit with code 130. + +`eot`: Default is `false`. A ^D pressed as the first character of an input line causes prompt-sync to echo `exit` and exit the process with code 0. + +`autocomplete`: A completer function that will be called when user enters TAB to allow for autocomplete. It takes a string as an argument an returns an array of strings that are possible matches for completion. An empty array is returned if there are no matches. + +`history`: Takes an object that supplies a "history interface", see [prompt-sync-history](http://npm.im/prompt-sync-history) for an example. + +## `prompt(ask, value, opts)` + +`ask` is the label of the prompt, `value` is the default value +in absence of a response. + +The `opts` argument can also be in the first or second parameter position. + +Opts can have the following properties + +`echo`: Default is `'*'`. If set the password will be masked with the specified character. For hidden input, set echo to `''` (or use `prompt.hide`). + +`autocomplete`: Overrides the instance `autocomplete` function to allow for custom +autocompletion of a particular prompt. + +`value`: Same as the `value` parameter, the default value for the prompt. If `opts` +is in the third position, this property will *not* overwrite the `value` parameter. + +`ask`: Sames as the `value` parameter. The prompt label. If `opts` is not in the first position, the `ask` parameter will *not* be overridden by this property. + +## `prompt.hide(ask)` + +Convenience method for creating a standard hidden password prompt, +this is the same as `prompt(ask, {echo: ''})` + + +# LINE EDITING +Line editing is enabled in the non-hidden mode. (use up/down arrows for history and backspace and left/right arrows for editing) + +History is not set when using hidden mode. + +# EXAMPLES + +```js + //basic: + console.log(require('prompt-sync')()('tell me something about yourself: ')) + + var prompt = require('prompt-sync')({ + history: require('prompt-sync-history')(), + autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']), + sigint: false + }); + + var value = 'frank'; + var name = prompt('enter name: ', value); + console.log('enter echo * password'); + var pw = prompt({echo: '*'}); + var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'}) + var pwc = prompt.hide('enter another hidden password: ') + var autocompleteTest = prompt('custom autocomplete: ', { + autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456']) + }); + + prompt.history.save(); + + console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc); + console.log('autocomplete2: ', autocompleteTest); + + function complete(commands) { + return function (str) { + var i; + var ret = []; + for (i=0; i< commands.length; i++) { + if (commands[i].indexOf(str) == 0) + ret.push(commands[i]); + } + return ret; + }; + }; +``` diff --git a/03-projeto-mario-kart/node_modules/prompt-sync/index.js b/03-projeto-mario-kart/node_modules/prompt-sync/index.js new file mode 100644 index 0000000..076d9f8 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/prompt-sync/index.js @@ -0,0 +1,243 @@ +'use strict' + +var fs = require('fs'); +var stripAnsi = require('strip-ansi'); +var term = 13; // carriage return + +/** + * create -- sync function for reading user input from stdin + * @param {Object} config { + * sigint: {Boolean} exit on ^C + * autocomplete: {StringArray} function({String}) + * history: {String} a history control object (see `prompt-sync-history`) + * } + * @returns {Function} prompt function + */ + + // for ANSI escape codes reference see https://en.wikipedia.org/wiki/ANSI_escape_code + +function create(config) { + + config = config || {}; + var sigint = config.sigint; + var eot = config.eot; + var autocomplete = config.autocomplete = + config.autocomplete || function(){return []}; + var history = config.history; + prompt.history = history || {save: function(){}}; + prompt.hide = function (ask) { return prompt(ask, {echo: ''}) }; + + return prompt; + + + /** + * prompt -- sync function for reading user input from stdin + * @param {String} ask opening question/statement to prompt for + * @param {String} value initial value for the prompt + * @param {Object} opts { + * echo: set to a character to be echoed, default is '*'. Use '' for no echo + * value: {String} initial value for the prompt + * ask: {String} opening question/statement to prompt for, does not override ask param + * autocomplete: {StringArray} function({String}) + * } + * + * @returns {string} Returns the string input or (if sigint === false) + * null if user terminates with a ^C + */ + + + function prompt(ask, value, opts) { + var insert = 0, savedinsert = 0, res, i, savedstr; + opts = opts || {}; + + if (Object(ask) === ask) { + opts = ask; + ask = opts.ask; + } else if (Object(value) === value) { + opts = value; + value = opts.value; + } + ask = ask || ''; + var echo = opts.echo; + var masked = 'echo' in opts; + autocomplete = opts.autocomplete || autocomplete; + + var fd = (process.platform === 'win32') ? + process.stdin.fd : + fs.openSync('/dev/tty', 'rs'); + + var wasRaw = process.stdin.isRaw; + if (!wasRaw) { process.stdin.setRawMode && process.stdin.setRawMode(true); } + + var buf = Buffer.alloc(3); + var str = '', character, read; + + savedstr = ''; + + if (ask) { + process.stdout.write(ask); + } + + var cycle = 0; + var prevComplete; + + while (true) { + read = fs.readSync(fd, buf, 0, 3); + if (read > 1) { // received a control sequence + switch(buf.toString()) { + case '\u001b[A': //up arrow + if (masked) break; + if (!history) break; + if (history.atStart()) break; + + if (history.atEnd()) { + savedstr = str; + savedinsert = insert; + } + str = history.prev(); + insert = str.length; + process.stdout.write('\u001b[2K\u001b[0G' + ask + str); + break; + case '\u001b[B': //down arrow + if (masked) break; + if (!history) break; + if (history.pastEnd()) break; + + if (history.atPenultimate()) { + str = savedstr; + insert = savedinsert; + history.next(); + } else { + str = history.next(); + insert = str.length; + } + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G'); + break; + case '\u001b[D': //left arrow + if (masked) break; + var before = insert; + insert = (--insert < 0) ? 0 : insert; + if (before - insert) + process.stdout.write('\u001b[1D'); + break; + case '\u001b[C': //right arrow + if (masked) break; + insert = (++insert > str.length) ? str.length : insert; + process.stdout.write('\u001b[' + (insert+ask.length+1) + 'G'); + break; + default: + if (buf.toString()) { + str = str + buf.toString(); + str = str.replace(/\0/g, ''); + insert = str.length; + promptPrint(masked, ask, echo, str, insert); + process.stdout.write('\u001b[' + (insert+ask.length+1) + 'G'); + buf = Buffer.alloc(3); + } + } + continue; // any other 3 character sequence is ignored + } + + // if it is not a control character seq, assume only one character is read + character = buf[read-1]; + + // catch a ^C and return null + if (character == 3){ + process.stdout.write('^C\n'); + fs.closeSync(fd); + + if (sigint) process.exit(130); + + process.stdin.setRawMode && process.stdin.setRawMode(wasRaw); + + return null; + } + + // catch a ^D and exit + if (character == 4) { + if (str.length == 0 && eot) { + process.stdout.write('exit\n'); + process.exit(0); + } + } + + // catch the terminating character + if (character == term) { + fs.closeSync(fd); + if (!history) break; + if (!masked && str.length) history.push(str); + history.reset(); + break; + } + + // catch a TAB and implement autocomplete + if (character == 9) { // TAB + res = autocomplete(str); + + if (str == res[0]) { + res = autocomplete(''); + } else { + prevComplete = res.length; + } + + if (res.length == 0) { + process.stdout.write('\t'); + continue; + } + + var item = res[cycle++] || res[cycle = 0, cycle++]; + + if (item) { + process.stdout.write('\r\u001b[K' + ask + item); + str = item; + insert = item.length; + } + } + + if (character == 127 || (process.platform == 'win32' && character == 8)) { //backspace + if (!insert) continue; + str = str.slice(0, insert-1) + str.slice(insert); + insert--; + process.stdout.write('\u001b[2D'); + } else { + if ((character < 32 ) || (character > 126)) + continue; + str = str.slice(0, insert) + String.fromCharCode(character) + str.slice(insert); + insert++; + }; + + promptPrint(masked, ask, echo, str, insert); + + } + + process.stdout.write('\n') + + process.stdin.setRawMode && process.stdin.setRawMode(wasRaw); + + return str || value || ''; + }; + + + function promptPrint(masked, ask, echo, str, insert) { + if (masked) { + process.stdout.write('\u001b[2K\u001b[0G' + ask + Array(str.length+1).join(echo)); + } else { + process.stdout.write('\u001b[s'); + if (insert == str.length) { + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str); + } else { + if (ask) { + process.stdout.write('\u001b[2K\u001b[0G'+ ask + str); + } else { + process.stdout.write('\u001b[2K\u001b[0G'+ str + '\u001b[' + (str.length - insert) + 'D'); + } + } + + // Reposition the cursor to the right of the insertion point + var askLength = stripAnsi(ask).length; + process.stdout.write(`\u001b[${askLength+1+(echo==''? 0:insert)}G`); + } + } +}; + +module.exports = create; diff --git a/03-projeto-mario-kart/node_modules/prompt-sync/package.json b/03-projeto-mario-kart/node_modules/prompt-sync/package.json new file mode 100644 index 0000000..b842943 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/prompt-sync/package.json @@ -0,0 +1,40 @@ +{ + "name": "prompt-sync", + "version": "4.2.0", + "description": "a synchronous prompt for node.js", + "main": "index.js", + "scripts": { + "test": "node test" + }, + "repository": { + "type": "git", + "url": "https://github.com/heapwolf/prompt-sync.git" + }, + "keywords": [ + "prompt", + "sync", + "blocking", + "readline", + "input", + "getline", + "repl", + "history" + ], + "contributors": [ + { + "name": "Paolo Fragomeni", + "email": "paolo@async.ly" + }, + { + "name": "David Mark Clements", + "email": "david.clements@nearform.com" + } + ], + "license": "MIT", + "devDependencies": { + "prompt-sync-history": "^1.0.1" + }, + "dependencies": { + "strip-ansi": "^5.0.0" + } +} diff --git a/03-projeto-mario-kart/node_modules/prompt-sync/test.js b/03-projeto-mario-kart/node_modules/prompt-sync/test.js new file mode 100644 index 0000000..fc0df02 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/prompt-sync/test.js @@ -0,0 +1,38 @@ +//basic: +console.log(require('./')()('tell me something about yourself: ')) + +// ANSI escape codes colored text test +require('./')()('\u001B[31mcolored text: \u001B[39m'); + +var prompt = require('./')({ + history: require('prompt-sync-history')(), + autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']), + sigint: false +}); + +var value = 'frank'; +var name = prompt('enter name: ', value); +console.log('enter echo * password'); +var pw = prompt({echo: '*'}); +var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'}) +var pwc = prompt.hide('enter another hidden password: ') +var autocompleteTest = prompt('custom autocomplete: ', { + autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456']) +}); + +prompt.history.save(); + +console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc); +console.log('autocomplete2: ', autocompleteTest); + +function complete(commands) { + return function (str) { + var i; + var ret = []; + for (i=0; i< commands.length; i++) { + if (commands[i].indexOf(str) == 0) + ret.push(commands[i]); + } + return ret; + }; +}; diff --git a/03-projeto-mario-kart/node_modules/strip-ansi/index.d.ts b/03-projeto-mario-kart/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..44e954d --- /dev/null +++ b/03-projeto-mario-kart/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,15 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +export default function stripAnsi(string: string): string; diff --git a/03-projeto-mario-kart/node_modules/strip-ansi/index.js b/03-projeto-mario-kart/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9788c96 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/strip-ansi/index.js @@ -0,0 +1,7 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +module.exports = stripAnsi; +module.exports.default = stripAnsi; diff --git a/03-projeto-mario-kart/node_modules/strip-ansi/license b/03-projeto-mario-kart/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/03-projeto-mario-kart/node_modules/strip-ansi/package.json b/03-projeto-mario-kart/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..7494fd7 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "5.2.0", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/03-projeto-mario-kart/node_modules/strip-ansi/readme.md b/03-projeto-mario-kart/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..8681fe8 --- /dev/null +++ b/03-projeto-mario-kart/node_modules/strip-ansi/readme.md @@ -0,0 +1,61 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + +--- + +
+ + Get professional support for 'strip-ansi' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/03-projeto-mario-kart/package-lock.json b/03-projeto-mario-kart/package-lock.json new file mode 100644 index 0000000..36351de --- /dev/null +++ b/03-projeto-mario-kart/package-lock.json @@ -0,0 +1,46 @@ +{ + "name": "aula", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "aula", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "prompt-sync": "^4.2.0" + } + }, + "node_modules/ansi-regex": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/prompt-sync": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/prompt-sync/-/prompt-sync-4.2.0.tgz", + "integrity": "sha512-BuEzzc5zptP5LsgV5MZETjDaKSWfchl5U9Luiu8SKp7iZWD5tZalOxvNcZRwv+d2phNFr8xlbxmFNcRKfJOzJw==", + "license": "MIT", + "dependencies": { + "strip-ansi": "^5.0.0" + } + }, + "node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/03-projeto-mario-kart/package.json b/03-projeto-mario-kart/package.json index d1f5e62..6224cc1 100644 --- a/03-projeto-mario-kart/package.json +++ b/03-projeto-mario-kart/package.json @@ -8,5 +8,8 @@ }, "keywords": [], "author": "", - "license": "ISC" + "license": "ISC", + "dependencies": { + "prompt-sync": "^4.2.0" + } } diff --git a/03-projeto-mario-kart/readme.md b/03-projeto-mario-kart/readme.md index fd63bb9..cd2eeb4 100644 --- a/03-projeto-mario-kart/readme.md +++ b/03-projeto-mario-kart/readme.md @@ -97,7 +97,36 @@ -Condição de vitória: + Condição de vitória: + +

💪 Tarefa a ser realizada:

+ +

Modificar a regra de pontuação do bloco CONFRONTO da seguinte forma:

+ + +

🤺 Modificações realizadas:

+ +

O código original disponível no diretório gitHub foi utilizado como ponto de partida visto que é o mesmo código apresentado nas video aulas.

+ +

As seguintes modifiacações foram realizadas:

+ + + + diff --git a/03-projeto-mario-kart/src/index.js b/03-projeto-mario-kart/src/index.js index e47c78a..66c952b 100644 --- a/03-projeto-mario-kart/src/index.js +++ b/03-projeto-mario-kart/src/index.js @@ -1,174 +1,644 @@ +// Modified by Fabio Toledo Bonemer De Salvi + +// Objects const player1 = { - NOME: "Mario", - VELOCIDADE: 4, - MANOBRABILIDADE: 3, - PODER: 3, - PONTOS: 0, + NOME: "Mario", + VELOCIDADE: 4, + MANOBRABILIDADE: 3, + PODER: 3, + PONTOS: 0, }; const player2 = { - NOME: "Luigi", - VELOCIDADE: 3, - MANOBRABILIDADE: 4, - PODER: 4, - PONTOS: 0, + NOME: "Luigi", + VELOCIDADE: 3, + MANOBRABILIDADE: 4, + PODER: 4, + PONTOS: 0, }; -async function rollDice() { - return Math.floor(Math.random() * 6) + 1; +// Implementing all players +// Array of objects +const players = [ + player1, + {NOME: "Peach", VELOCIDADE: 3, MANOBRABILIDADE: 4, PODER: 2, PONTOS: 0}, + {NOME: "Yoshi", VELOCIDADE: 2, MANOBRABILIDADE: 4, PODER: 3, PONTOS: 0}, + {NOME: "Bowser", VELOCIDADE: 5, MANOBRABILIDADE: 2, PODER: 5, PONTOS: 0}, + player2, + {NOME: "Kong", VELOCIDADE: 2, MANOBRABILIDADE: 2, PODER: 5, PONTOS: 0}, +] + + +// Async functions +async function rollDice(){ + return Math.floor(Math.random() * 6) + 1; } -async function getRandomBlock() { - let random = Math.random(); - let result; - - switch (true) { - case random < 0.33: - result = "RETA"; - break; - case random < 0.66: - result = "CURVA"; - break; - default: - result = "CONFRONTO"; - } - - return result; +// Switch Case +async function getRandomBlock(){ + let random = Math.random() + let result + + // Switch case + switch (true) { + case random < 0.33: + result = "RETA"; + break; + case random < 0.66: + result = "CURVA"; + break; + default: + result = "CONFRONTO"; + } + + return result; +} + +// Functions Chains +async function playRaceEngine(playersForRace){ + // For + // const -> não pode ser modificado + // let -> pode ser modificado + for(let round = 1; round <= 5; round++) { + console.log(`🏁 Rodada ${round}`); + + // Sortear bloco + let block = await getRandomBlock() + // Definindo o bloco para teste + //block = "CONFRONTO"; + console.log(`Bloco: ${block}`); + + //Definindo os pontos iniciais para teste + /* + for(let index=0; index < playersForRace.length; index++) { + playersForRace[index].PONTOS = Math.floor(Math.random() * 0); + } + */ + + // rolar os dados + //let diceResult1 = await rollDice(); + //let diceResult2 = await rollDice(); + let diceResult = []; + for (let index = 0; index < playersForRace.length; index++) { + diceResult.push(await rollDice()); + //console.log(`DiceResult Jogador ${index+1} = ${diceResult[diceResult.length-1]}`); + } + + // teste de habilidade + //let totalTestSkill1 = 0; + //let totalTestSkill2 = 0; + let totalTestSkill = []; + + // Testando Blocos - if + if(block == "RETA"){ + //totalTestSkill1 = diceResult1 + character1.VELOCIDADE; + //totalTestSkill2 = diceResult2 + character2.VELOCIDADE; + for (let index = 0; index < playersForRace.length; index++) { + totalTestSkill.push(diceResult[index] + playersForRace[index].VELOCIDADE); + } + + /* + await logRollResult( + character1.NOME, + "velocidade", + diceResult1, + character1.VELOCIDADE + ); + + await logRollResult( + character2.NOME, + "velocidade", + diceResult2, + character2.VELOCIDADE + ); + */ + for (let index = 0; index < playersForRace.length; index++) { + await logRollResult( + playersForRace[index].NOME, + "velocidade", + diceResult[index], + playersForRace[index].VELOCIDADE + ); + } + console.log(""); + + } + + if(block == "CURVA"){ + //totalTestSkill1 = diceResult1 + character1.MANOBRABILIDADE; + //totalTestSkill2 = diceResult2 + character2.MANOBRABILIDADE; + for (let index = 0; index < playersForRace.length; index++) { + totalTestSkill.push(diceResult[index] + playersForRace[index].MANOBRABILIDADE); + } + + /* + await logRollResult( + character1.NOME, + "manobrabilidade", + diceResult1, + character1.MANOBRABILIDADE + ); + + await logRollResult( + character2.NOME, + "manobrabilidade", + diceResult2, + character2.MANOBRABILIDADE + ); + */ + for (let index = 0; index < playersForRace.length; index++) { + await logRollResult( + playersForRace[index].NOME, + "manobrabilidade", + diceResult[index], + playersForRace[index].MANOBRABILIDADE + ); + } + console.log(""); + + } + + if(block == "CONFRONTO"){ + // Escopo de variáveis + //let powerResult1 = diceResult1 + character1.PODER; + //let powerResult2 = diceResult2 + character2.PODER; + let powerResult = []; + for (let index = 0; index < playersForRace.length; index++) { + powerResult.push(diceResult[index] + playersForRace[index].PODER); + //powerResult.push(10); + } + + //console.log(`${character1.NOME} confrontou com ${character2.NOME}! 🥊!`); + console.log(await getMsgConfronto(playersForRace)); + + /* + await logRollResult( + character1.NOME, + "poder", + diceResult1, + character1.PODER + ); + + await logRollResult( + character2.NOME, + "poder", + diceResult2, + character2.PODER + ); + */ + for (let index = 0; index < playersForRace.length; index++) { + await logRollResult( + playersForRace[index].NOME, + "poder", + diceResult[index], + playersForRace[index].PODER + ); + } + console.log(""); + + //continue; // skip the rest of the code + + // Diminuindo Ifs - If ternario + /*character2.PONTOS -= + powerResult1 > powerResult2 && character2.PONTOS > 0 ? 1 : 0;*/ + + // Condição Dupla - If Combinado + /* + if (powerResult1 > powerResult2 && character2.PONTOS > 0) { + console.log( + `${character1.NOME} venceu o confronto! ${character2.NOME} perdeu 1 ponto 🐢!` + ); + character2.PONTOS--; + } + */ + + /*if (powerResult1 > powerResult2) { + if (character2.PONTOS > 0) { + character2.PONTOS--; + } + } */ + + // Diminuindo Ifs - If ternario + /*character1.PONTOS -= + powerResult1 < powerResult2 && character1.PONTOS > 0 ? 1 : 0;*/ + + // Condição Dupla - If Combinado + /* + if (powerResult1 < powerResult2 && character1.PONTOS > 0) { + console.log( + `${character2.NOME} venceu o confronto! ${character1.NOME} perdeu 1 ponto 🐢!` + ); + character1.PONTOS--; + } + */ + + /*if (powerResult1 < powerResult2) { + if (character1.PONTOS > 0) { + character1.PONTOS--; + } + }*/ + + // Diminuindo Ifs - If ternario + /* + console.log( + powerResult1 == powerResult2 + ? "Confronto empatado! Nenhum ponto foi perdido!" + : "" + ); + */ + /*if (powerResult1 == powerResult2) { + console.log("Confronto empatado! Nenhum ponto foi perdido!"); + }*/ + + + // Obtendo o maior valor de powerResult + let maxPower = 0; + for(index = 0; index < playersForRace.length; index++) { + // if Ternario + maxPower = powerResult[index] > maxPower ? + powerResult[index] : maxPower + } + + // Identificando os vencedores e perdedores do confronto! + let vencedores = []; + let perdedores = []; + for(index = 0; index < playersForRace.length; index++) { + //let playerForRace = playersForRace[index]; + if (powerResult[index] == maxPower) { + //vencedores.push({index: index, ...playerForRace}); // ... spread syntax + vencedores.push({INDEX: index, ...playersForRace[index]}); // ... spread syntax + } else { + //perdedores.push({INDEX: index, ...playerForRace}); + perdedores.push({INDEX: index, ...playersForRace[index]}); // ... spread syntax + } + } + + // Empate + if (vencedores.length == playersForRace.length) { + console.log("Confronto empatado! Nenhum ponto foi perdido!"); + } else { + // Vencedores + let turbo = Math.random() > 0.5 ? true : false; + let msgPlayerNames = await getMsgWithPlayers(vencedores); + if (vencedores.length == 1) { + if (turbo == true) { + console.log(`${msgPlayerNames} venceu o confronto e ganhou 1 ponto de turbo 🌟!`); + } else { + console.log(`${msgPlayerNames} venceu o confronto!`) + } + } else if (vencedores.length > 1) { + if (turbo == true) { + console.log(`${msgPlayerNames} venceram o confronto e ganharam 1 ponto de turbo 🌟!`); + } else { + console.log(`${msgPlayerNames} venceram o confronto!`) + } + } + + for (let index = 0; index < vencedores.length; index++) { + if (turbo == true) { + //console.log(`${playersForRace[vencedores[index].INDEX].NOME} - ${playersForRace[vencedores[index].INDEX].PONTOS}`); + playersForRace[vencedores[index].INDEX].PONTOS++; + //console.log(`${playersForRace[vencedores[index].INDEX].NOME} - ${playersForRace[vencedores[index].INDEX].PONTOS}`); + } + } + + + // Perdedores + let cascoOuBomba = Math.random() > 0.5 ? 1 : 2; // 1 -> casco, 2 -> bomba + for (let index = 0; index < perdedores.length; index++){ + //console.log(`${playersForRace[perdedores[index].INDEX].NOME} - ${playersForRace[perdedores[index].INDEX].PONTOS}`); + if (cascoOuBomba == 1) { + if (playersForRace[perdedores[index].INDEX].PONTOS > 0) { + console.log( + `${playersForRace[perdedores[index].INDEX].NOME} perdeu 1 ponto 🐢!` + ); + playersForRace[perdedores[index].INDEX].PONTOS--; + } + } else { + if (playersForRace[perdedores[index].INDEX].PONTOS > 1) { + console.log( + `${playersForRace[perdedores[index].INDEX].NOME} perdeu 2 pontos 💣!` + ); + playersForRace[perdedores[index].INDEX].PONTOS = playersForRace[perdedores[index].INDEX].PONTOS - 2 ; + } else if (playersForRace[perdedores[index].INDEX].PONTOS > 0) { + console.log( + `${playersForRace[perdedores[index].INDEX].NOME} perdeu 1 ponto 💣!` + ); + playersForRace[perdedores[index].INDEX].PONTOS-- ; + } + } + //console.log(`${playersForRace[perdedores[index].INDEX].NOME} - ${playersForRace[perdedores[index].INDEX].PONTOS}`); + } + } + + } + + // Verificando o vencedor. + // Winner - Else If's + /* + if (totalTestSkill1 > totalTestSkill2) { + console.log(`${character1.NOME} marcou um ponto!`); + character1.PONTOS++; + } else if (totalTestSkill1 < totalTestSkill2) { + console.log(`${character2.NOME} marcou um ponto!`); + character2.PONTOS++; + } + */ + + // Obtendo o maior valor de totalTestSkill + let maxSkill = 0; + for(index = 0; index < playersForRace.length; index++) { + // if Ternario + maxSkill = totalTestSkill[index] > maxSkill ? + totalTestSkill[index] : maxSkill + } + + // Identificando os vencedores da etapa! + + for(index = 0; index < playersForRace.length; index++) { + if (totalTestSkill[index] == maxSkill && maxSkill != 0) { + playersForRace[index].PONTOS++; + console.log(`${playersForRace[index].NOME} marcou um ponto!`); + } + } + + console.log("-----------------------------------------"); + + } + } +// Encapsulate async function logRollResult(characterName, block, diceResult, attribute) { - console.log( - `${characterName} 🎲 rolou um dado de ${block} ${diceResult} + ${attribute} = ${ - diceResult + attribute - }` - ); + // Javascript Expressions: $ { + // a + b +// } + console.log(`${characterName} 🎲 rolou um dado de ${block} ${diceResult} + ${ + attribute} = ${ + diceResult + attribute + }`); +} + +// Game Over - Clean Ifs +async function declareWinner(charactes) { + console.log("Resultado final:"); + //console.log(`${character1.NOME}: ${character1.PONTOS} ponto(s).`); + //console.log(`${character2.NOME}: ${character2.PONTOS} ponto(s).`); + for(let index = 0; index < charactes.length; index++) { + console.log(`${charactes[index].NOME}: ${charactes[index].PONTOS} ponto(s).`); + } + console.log(""); + + // If encadeado + /* + if (character1.PONTOS > character2.PONTOS) + console.log(`\n${character1.NOME} venceu a corrida! Parabéns! 🏆!`); + else if ((character2.PONTOS > character1.PONTOS)) + console.log(`\n${character2.NOME} venceu a corrida! Parabéns! 🏆!`); + else + console.log("A corrida terminou em empate!"); + */ + + // Obtendo a pontuação máxima + let maxPontos = 0; + for(let index = 0; index < charactes.length; index++) { + maxPontos = charactes[index].PONTOS > maxPontos ? + charactes[index].PONTOS : maxPontos; + + } + + // Identificando os vencedores da corrida! + let vencedores = []; + for(let index = 0; index < charactes.length; index++) { + if (charactes[index].PONTOS >= maxPontos) { + vencedores.push({INDEX: index, ...charactes[index]}); // ... spread syntax + } + } + + // Msg com os nomes dos vencedores + let msgPlayerNames = await getMsgWithPlayers(vencedores); + if (vencedores.length == 1) { + console.log(`${msgPlayerNames} venceu a corrida! Parabéns! 🏆!`) + } else if (vencedores.length < charactes.length) { + console.log(`${msgPlayerNames} venceram a corrida! Parabéns! 🏆!`) + } else { + console.log("A corrida terminou em empate!"); + } } -async function playRaceEngine(character1, character2) { - for (let round = 1; round <= 5; round++) { - console.log(`🏁 Rodada ${round}`); - - // sortear bloco - let block = await getRandomBlock(); - console.log(`Bloco: ${block}`); - - // rolar os dados - let diceResult1 = await rollDice(); - let diceResult2 = await rollDice(); - - //teste de habilidade - let totalTestSkill1 = 0; - let totalTestSkill2 = 0; - - if (block === "RETA") { - totalTestSkill1 = diceResult1 + character1.VELOCIDADE; - totalTestSkill2 = diceResult2 + character2.VELOCIDADE; - - await logRollResult( - character1.NOME, - "velocidade", - diceResult1, - character1.VELOCIDADE - ); - - await logRollResult( - character2.NOME, - "velocidade", - diceResult2, - character2.VELOCIDADE - ); +// Print all players +async function printAllCharacters(charcters) { + let msgAllCharacters = ""; + console.log(""); + console.log("🏁🤩 Lista dos personagens disponíveis e suas características!"); + console.log(""); + for(let index = 0; index < charcters.length; index++) { + msgAllCharacters = `${index + 1} - ${charcters[index].NOME}. [velocidade: ${charcters[index].VELOCIDADE},`; + msgAllCharacters += `manobrabilidade: ${charcters[index].MANOBRABILIDADE}, poder: ${charcters[index].PODER}].`; + console.log(msgAllCharacters); } + console.log(""); + +} + +// Number of players +async function getNumberOfPlayers(defaultNumberPlayers) { + + console.log(""); + console.log("🏁🤩 Número de jogadores! "); + + const prompt = require("prompt-sync")(); //npm install prompt-sync + const userInput = prompt(`Qual o número de jogadores? (Mínimo: 2. Máximo: ${players.length}.): `); + + let numJogadores = parseInt(userInput, 10); + //console.log(`Número de jogadores: ${numJogadores}.`); + + //if (typeof numJogadores === 'number' && numJogadores != NaN){ + if (numJogadores !== NaN && numJogadores >= 2 && numJogadores <= 6){ + /* + if (numJogadores < 2 || numJogadores > 6) { + numJogadores = defaultNumberPlayers; + }*/ + console.log(`Foi escolhido ${numJogadores} jogadores!`); + } else { + numJogadores = defaultNumberPlayers; + console.log(`Foi definido o número padrão de ${numJogadores} jogadores!`) + } + + console.log(""); + + return numJogadores; + +} + +// Selecting players for race +async function getPlayersForRace(numberOfPlayers) { + let playersForRace = []; + + console.log(""); + console.log(`🏁🤩 Definindo os ${numberOfPlayers} jogadores que participarão da corrida!`); + console.log("As seis opções estão listadas acima!"); + console.log("Defina cada jogador com um número correspondente ao personagem!"); + console.log("O sistema irá definir o personagem de forma aleatória para números diferentes aos listados acima ou para números repetidos!"); + + const prompt = require("prompt-sync")(); //npm install prompt-sync + + for (let jogador = 1; jogador <= numberOfPlayers; jogador++) { + console.log(""); + const userInput = prompt(`Definindo o jogador ${jogador}. Digite um número entre 1 a 6: `); + let numPlayer = parseInt(userInput, 10); + //console.log(`Número do personagem: ${numPlayer}. ${(numPlayer == NaN)}`); + + if (numPlayer !== NaN || numPlayer < 1 || numPlayer > players.length) { + let playerSelected = false; + const min = 1; + const max = 6; + while(!playerSelected) { + // Math.random() -> [0, 1) - 0->inclusivo e 1-> exclusivo + // Math.floor(number) -> maior inteiro menor ou igual ao argumento + numPlayer = Math.floor(Math.random() * (max - min + 1)) + min; + //console.log(`Jogador ${jogador} - random ${numPlayer}`); + playerSelected = true + if (playersForRace.length > 0){ + for(let indexRace = 0; indexRace < playersForRace.length; indexRace++) { + if (players[numPlayer-1].NOME === playersForRace[indexRace].NOME) { + playerSelected = false; + } + //console.log(`Jogador ${jogador} - Players.NOME = ${players[numPlayer-1].NOME} === PlayersForRace.NOME = ${playersForRace[indexRace].NOME}: ${players[numPlayer-1].NOME === playersForRace[indexRace].NOME}`); + } + } + } + } + playersForRace.push(players[numPlayer-1]) + console.log(`Jogador ${jogador} - ${playersForRace[jogador-1].NOME}. [velocidade: ${playersForRace[jogador-1].VELOCIDADE}, manobrabilidade: ${playersForRace[jogador-1].MANOBRABILIDADE}, poder: ${playersForRace[jogador-1].PODER}].`); - if (block === "CURVA") { - totalTestSkill1 = diceResult1 + character1.MANOBRABILIDADE; - totalTestSkill2 = diceResult2 + character2.MANOBRABILIDADE; - - await logRollResult( - character1.NOME, - "manobrabilidade", - diceResult1, - character1.MANOBRABILIDADE - ); - - await logRollResult( - character2.NOME, - "manobrabilidade", - diceResult2, - character2.MANOBRABILIDADE - ); } + + //console.log(``) + //await printAllPlayers(playersForRace); + + console.log(``) - if (block === "CONFRONTO") { - let powerResult1 = diceResult1 + character1.PODER; - let powerResult2 = diceResult2 + character2.PODER; - - console.log(`${character1.NOME} confrontou com ${character2.NOME}! 🥊`); - - await logRollResult( - character1.NOME, - "poder", - diceResult1, - character1.PODER - ); - - await logRollResult( - character2.NOME, - "poder", - diceResult2, - character2.PODER - ); - - if (powerResult1 > powerResult2 && character2.PONTOS > 0) { - console.log( - `${character1.NOME} venceu o confronto! ${character2.NOME} perdeu 1 ponto 🐢` - ); - character2.PONTOS--; - } - - if (powerResult2 > powerResult1 && character1.PONTOS > 0) { - console.log( - `${character2.NOME} venceu o confronto! ${character1.NOME} perdeu 1 ponto 🐢` - ); - character1.PONTOS--; - } - - console.log( - powerResult2 === powerResult1 - ? "Confronto empatado! Nenhum ponto foi perdido" - : "" - ); + return playersForRace; +} + +// Creating a message with the players name +async function getMsgWithPlayers(players) { + let msgWithPlayers = "" + + for (let index = 0; index < players.length; index++) { + if (index == 0) { + //msgWithPlayers = `${msgWithPlayers} ${players[index].NOME}`; + msgWithPlayers = `${players[index].NOME}`; + } + else if (players.length - index >= 2) + msgWithPlayers = `${msgWithPlayers}, ${players[index].NOME}`; + else + msgWithPlayers = `${msgWithPlayers} e ${players[index].NOME}`; } - // verificando o vencedor - if (totalTestSkill1 > totalTestSkill2) { - console.log(`${character1.NOME} marcou um ponto!`); - character1.PONTOS++; - } else if (totalTestSkill2 > totalTestSkill1) { - console.log(`${character2.NOME} marcou um ponto!`); - character2.PONTOS++; + //msgWithPlayers = "\n"; + + return msgWithPlayers; +} + +// Creating a message with the players name +async function getMsgConfronto(players) { + let msgConfronto = "Confronto entre" + + for (let index = 0; index < players.length; index++) { + if (index == 0) + msgConfronto = `${msgConfronto} ${players[index].NOME}`; + else if (players.length - index >= 2) + msgConfronto = `${msgConfronto}, ${players[index].NOME}`; + else + msgConfronto = `${msgConfronto} e ${players[index].NOME}`; } - console.log("-----------------------------"); - } + msgConfronto = msgConfronto + " começando 🥊!\n"; + + return msgConfronto; } -async function declareWinner(character1, character2) { - console.log("Resultado final:"); - console.log(`${character1.NOME}: ${character1.PONTOS} ponto(s)`); - console.log(`${character2.NOME}: ${character2.PONTOS} ponto(s)`); +// Creating a message with the players name +async function getMsgCorrida(players) { + let msgCorrida = "🏁🚨 Corrida entre" + + for (let index = 0; index < players.length; index++) { + if (index == 0) + msgCorrida = `${msgCorrida} ${players[index].NOME}`; + else if (players.length - index >= 2) + msgCorrida = `${msgCorrida}, ${players[index].NOME}`; + else + msgCorrida = `${msgCorrida} e ${players[index].NOME}`; + } + + msgCorrida = msgCorrida + " começando...\n"; - if (character1.PONTOS > character2.PONTOS) - console.log(`\n${character1.NOME} venceu a corrida! Parabéns! 🏆`); - else if (character2.PONTOS > character1.PONTOS) - console.log(`\n${character2.NOME} venceu a corrida! Parabéns! 🏆`); - else console.log("A corrida terminou em empate"); + return msgCorrida; } +// Auto invoke (async function main() { - console.log( - `🏁🚨 Corrida entre ${player1.NOME} e ${player2.NOME} começando...\n` - ); - await playRaceEngine(player1, player2); - await declareWinner(player1, player2); + console.log(""); + console.log("🏁🕹️ Desafio de projeto do Felipão: Mario Kart.JS."); + console.log("🏁🕹️ Modificado por Fabio Toledo Bonemer De Salvi."); + console.log(""); + + await printAllCharacters(players); + + let numberOfPlayers = await getNumberOfPlayers(2); + + let playersForRace = await getPlayersForRace(numberOfPlayers); + + let msgCorrida = await getMsgCorrida(playersForRace); + + //console.log(`🏁🚨 Corrida entre ${player1.NOME} e ${player2.NOME} começando...\n`) + console.log(msgCorrida); + + //await playRaceEngine(player1, player2); + await playRaceEngine(playersForRace); + + //await declareWinner(player1, player2); + await declareWinner(playersForRace); })(); + +/* +// Or +async function main() { + console.log(`🏁🚨 Corrida entre ${player1.NOME} e ${player2.NOME} começando...\n`) + + await playRaceEngine(player1, player2); + await declareWinner(player1, player2); +} + +main(); +*/ + + +/* Sketch + + To insert icon press "win" + ".". + + const -> não pode ser modificado + let -> pode ser modificado + + + For input data in Node.js + $ npm install prompt-sync + + In JavaScript, comparing NaN (Not-a-Number) values directly using equality operators (==, ===, !=, !==) yields specific and often counter-intuitive results: + - NaN is never equal to itself: NaN == NaN and NaN === NaN both evaluate to false. This is a unique characteristic of NaN in JavaScript and other floating-point implementations. + - NaN is never equal to any other value: Comparing NaN to any other number, string, boolean, or object using == or === will always result in false. + - NaN is never unequal to itself: Consequently, NaN != NaN and NaN !== NaN both evaluate to true. + + continue; // skip the rest of the code + +*/ + +/* + - Confronto + - sortear aleatoriamente se é um casco (-1 ponto) ou uma bomba (-2 pontos) + - quem vence o confronto ganha um turbo (+ 1 ponto) aleatoriamente. +*/