• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Fix Rock Paper Scissors Game Code in Ruby?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction


Welcome to the world of Ruby programming! If you're reading this, you're likely trying to troubleshoot a Rock Paper Scissors game that you're working on. Your code serves as a great starting point for developing this classic game, but there are a few issues that prevent it from functioning as intended. In this article, we'll dissect your existing code, explore why it may not be yielding the desired results, and provide a step-by-step fix to ensure your game operates smoothly.

Understanding the Problem


Your code is designed to randomly choose between Rock, Paper, and Scissors, allowing the player to input their choice and determining the outcome based on comparisons. However, the code currently has a few issues that lead to incorrect output.


  1. Random Choice Issues: The variable comp is assigned a random number between 1 and 3. This means it could evaluate as 1 (Rock), 2 (Paper), or 3 (Scissors), which is correct. However, you're trying to access an element of the array cchoice using comp, which results in a problem since arrays in Ruby are zero-indexed. Thus, the first element is accessed with index 0 instead of 1.


  2. Determining the Winner: The logic used to determine whether the player has won or lost doesn't account for ties. This would lead to scenarios where neither the player nor the computer wins.


  3. Improper User Input Handling: When the user inputs something outside of Rock, Paper, or Scissors, the provided message doesn’t terminate the program to gracefully exit.

With these issues in mind, let's go through a corrected version of your code and improve it.

Improved Rock Paper Scissors Code


Here’s the revised version of your Ruby Rock Paper Scissors game:

puts "Rock, Paper, or Scissors? Type your choice:"
choice = gets.chomp.capitalize
cchoice = ["Rock", "Paper", "Scissors"]
comp = rand(0..2)

puts "Computer chose #{cchoice[comp]}"

if choice == "Rock"
if comp == 0
puts "It's a tie!"
elsif comp == 1
puts "You lost.."
else
puts "YOU WON!!!"
end
elsif choice == "Paper"
if comp == 0
puts "You won!!!"
elsif comp == 1
puts "It's a tie!"
else
puts "You lost.."
end
elsif choice == "Scissors"
if comp == 0
puts "You lost.."
elsif comp == 1
puts "You won!!!"
else
puts "It's a tie!"
end
else
puts "I don’t know what that means. Please choose Rock, Paper, or Scissors."
end

Key Changes Made:

  • Indexing Adjustment: Changed the random choice range from 1..3 to 0..2 and adjusted how we access cchoice. The index must start from 0 to align with Ruby's zero-based indexing convention.
  • Winner Logic Improvement: Incorporated checks for ties and the correct winning conditions based on the computer's choice against the user’s input.
  • Input Normalization: Added .capitalize to ensure that regardless of how the user types their choice (whether "rock", "Rock", or other combinations), it will be properly recognized.
Conclusion


By making these adjustments, your Ruby Rock Paper Scissors game should now run as expected: accurately determining wins, losses, and ties. Testing your code is key, so try playing several rounds to ensure it functions smoothly.

Frequently Asked Questions (FAQ)


Q: Why did I need to change the random range for the computer?
A: Ruby arrays are zero-indexed, meaning the first element is at index 0. Changing the range to 0..2 aligns with the available indexes of your choices.

Q: Can I add a feature to play again?
A: Absolutely! You can wrap your game code inside a loop to allow the player to play multiple rounds in one run, adding a prompt at the end to ask if they want to continue.

With these insights and code tweaks, you're now well on your way to enhancing your Ruby programming skills! Happy coding!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу