Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 05.03.2018, 01:21
Новичок на форуме
Отправить личное сообщение для YaninaT Посмотреть профиль Найти все сообщения от YaninaT
 
Регистрация: 05.03.2018
Сообщений: 1

Нужна срочная помощь в разработке игры "Виселица"
Пожалуйста помогите с разработкой игры "Виселица". Я только учусь и мало что понимаю в этом.
Задание отличается от традиционного подхода.
1) Должна быть функция "start", которая запускает игру и выбирает слово(random) из категорий. Она работает (помог учитель).
2) Далее должна ,быть функция "guess", которая по сути все и делает. (не работает).
3) За неугаданную букву игрок получает strike.
4) Игрок получает извещения при любом раскладе, типа "Да, такие буквы есть..." или "Нет такой буквы, вы получили страйк"...
5) Все на английском языке.
6) Игра полностью реализуется на консоли через return() и console.log(). Никаких дополнений ввиде html и css не надо.

Очень прошу, помогите. Хотя бы с функцией "guess"!!!
Мой код:
const words = {
  Animals: ['muskrat', 'hyena', 'armadillo', 'platypus', 'iguana'],
  Artists: ['Caravaggio', 'Michelangelo', 'Rembrandt', 'Bosch', 'Kandinsky'],
  Scientists: ['Archimedes', 'Newton', 'Darwin', 'Tesla', 'Galilei'],
  Countries: ['Andorra', 'Belgium', 'Cameroon', 'Estonia', 'Guatemala']
}

const categories = ['Animals', 'Artists', 'Scientists', 'Countries']

const randomInt = function (max) {
  return Math.floor(Math.random() * Math.floor(max))
}

const playerTotal = {
	guessedLetters: [],
	strikes: 0,
	countTry: 6,
	remainLetters: [],
	currentPuzzle: []
}

playerTotal.remainLetters = words.length

function start () {
	// randomly select a category
	const i = randomInt(categories.length)
	const category = categories[i]

	// radomly select puzzle from category array
	const j = randomInt(words[category].length)
	const word = words[category][j]
  playerTotal.currentPuzzle = word
	const answer = []
	for (let i = 0; i < word.length; i++) {
		answer[i] = '_'
	}
	console.log(`Category: ${category}. Word: ${answer}`)
}

const answerArray = []
for (let i = 0; i < words.length; i++) {
	answerArray[i] = '_'
}
const lettersArray = []
for (let y = 0; y < words.length; y++) {
  letter.join(' ')
}

function letter () {
	const answer = []
	for (let i = 0; i < words.length; i++) {
		// create if to compare words[i] (letter) with guessed letters
     // if a match don't change the letter
    if (words[i] === playerTotal.guessedLetters) {
      playerTotal.guessedLetters = letter.join(' ')
    } else { // else change to underscore
      playerTotal.guessedLetters = answerArray.join(' ')
    }
	}
}

const letterUpperCase = letter.toUpperCase

function guess () {
  // store letter into array of guessed letters
  playerTotal.guessedLetters.push(letter)
	playerTotal.currentPuzzle = word
  const category = categories[i]
	// check if letter is part of the phrase, if so, rebuild the puzzle

	if (words.indexOf(answerArray) !== -1) {
	// else update strikes and return the puzzle as is
  playerTotal.guessedLetters.push(answerArray)
  playerTotal.strikes
  return (answerArray).join(' ')
  console.log(`Yes, there are ${letter.toUpperCase}s in this word.`)
	} else {
		playerTotal.strikes++
		playerTotal.countTry--
    return (answerArray).join(' ')
		console.log(`No, there are no ${letter.toUpperCase}s in this word.
		You've got a strike. Now you have only ${playerTotal.countTry} attempts`)
	}
}

Последний раз редактировалось YaninaT, 06.03.2018 в 03:04. Причина: нужно отредактировать код
Ответить с цитированием
  #2 (permalink)  
Старый 05.03.2018, 10:43
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,723

Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[js]
... ваш код...
[/js]


О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Нужна помощь по javascript darklend Общие вопросы Javascript 0 12.01.2014 23:33
Нужна срочная помощь по JS! Merdok351 Общие вопросы Javascript 2 07.06.2013 23:54
Нужна помощь: Slider wheel Alex555 Мобильный JavaScript 0 15.05.2013 18:06
нужна помощь dominosoko Серверные языки и технологии 4 14.03.2010 02:17
нужна срочная помощь с jquery Hetfield jQuery 2 19.11.2008 21:45