fork download
  1. -- Rock, Paper, Scissors Game in Lua
  2.  
  3. -- Function to get the computer's choice
  4. function getComputerChoice()
  5. local choices = {"rock", "paper", "scissors"}
  6. local randomIndex = math.random(1, 3)
  7. return choices[randomIndex]
  8. end
  9.  
  10. -- Function to determine the winner
  11. function determineWinner(playerChoice, computerChoice)
  12. if playerChoice == computerChoice then
  13. return "It's a tie!"
  14. elseif (playerChoice == "rock" and computerChoice == "scissors") or
  15. (playerChoice == "scissors" and computerChoice == "paper") or
  16. (playerChoice == "paper" and computerChoice == "rock") then
  17. return "You win!"
  18. else
  19. return "Computer wins!"
  20. end
  21. end
  22.  
  23. -- Main game loop
  24. function playGame()
  25. print("Welcome to Rock, Paper, Scissors!")
  26. print("Please enter 'rock', 'paper', or 'scissors' to play:")
  27.  
  28. -- Get player's choice
  29. local playerChoice = io.read()
  30.  
  31. -- Ensure the player enters a valid choice
  32. if playerChoice ~= "rock" and playerChoice ~= "paper" and playerChoice ~= "scissors" then
  33. print("Invalid choice! Please enter 'rock', 'paper', or 'scissors'.")
  34. return
  35. end
  36.  
  37. -- Get the computer's choice
  38. local computerChoice = getComputerChoice()
  39. print("Computer chose: " .. computerChoice)
  40.  
  41. -- Determine and display the result
  42. local result = determineWinner(playerChoice, computerChoice)
  43. print(result)
  44. end
  45.  
  46. -- Seed the random number generator
  47. math.randomseed(os.time())
  48.  
  49. -- Play the game
  50. playGame()-- your code goes here
Success #stdin #stdout 0.01s 5280KB
stdin
rock
stdout
Welcome to Rock, Paper, Scissors!
Please enter 'rock', 'paper', or 'scissors' to play:
Computer chose: paper
Computer wins!