一段游戏应用中的lua脚本

----------------------------------------------------------

--Name: rock_paper_scissors2.lua

--Author: Mat Buckland

--Desc: lua script to implement a rock-paper-scissors game

-----------------------------------------------------------

--[[seed the random number generator]]
math.randomseed(os.time())


--[[these global variables will hold the scores of the player
   and the computer]]

user_score = 0
comp_score = 0


--[[ this table is used to determine who wins which round ]]

lookup = {};
lookup["rock"] = {rock ="draw", paper = "lose", scissors = "win" }
lookup["paper"] = {rock = "win", paper ="draw", scissors = "lose"}
lookup["scissors"] = {rock = "lose", paper = "win", scissors ="draw"}


--[[this function returns the computer's best guess]]

function GetAIMove()

  --create a table so we can convert an integer to a play string
  local int_to_name = {"scissors", "rock", "paper"}

  --get a random integer in the range 1-3 and use it as an index
  --into the table we've just made so that the function can return
  --a random play
  return int_to_name[math.random(3)]

end


--[[this function uses the lookup table to decide the winner and
    allocates scores accordingly]]

function EvaluateTheGuesses(user_guess, comp_guess)

  print ("user guess... "..user_guess.." comp guess... "..comp_guess)

  if(lookup[user_guess][comp_guess] == "win") then

      print ("You Win the Round!")

      user_score = user_score + 1

  elseif(lookup[user_guess][comp_guess] == "lose") then

      print ("Computer Wins the Round")

      comp_score = comp_score + 1
  else

    print ("Draw!")

    print (lookup[user_guess][comp_guess])

  end

end


--[[ main game loop ]]

print ("Enter q to quit game");
print()

loop = true
while loop == true do

  --let the user know the current score
  print("User: "..user_score.." Computer: "..comp_score)

  --grab input from the user via the keyboard
  user_guess = io.stdin:read '*l'

  --[[declare a table to convert the user's input into a string]]

  local letter_to_string = {s = "scissors", r = "rock", p = "paper"}


  if user_guess == "q" then

     loop = false --quit the game if user enters 'q'

  elseif (user_guess == "r") or (user_guess == "p") or (user_guess == "s") then

     comp_guess = GetAIMove()

     EvaluateTheGuesses(letter_to_string[user_guess], comp_guess)

  else

     print ("Invalid input, try again")

  end
end

你可能感兴趣的:(游戏,脚本,OS,lua)