Skip to content

Commit

Permalink
add trivial examples
Browse files Browse the repository at this point in the history
  • Loading branch information
artgreen committed Aug 2, 2023
1 parent caaf134 commit 3ae3ba3
Show file tree
Hide file tree
Showing 3 changed files with 258 additions and 0 deletions.
131 changes: 131 additions & 0 deletions examples/blackjack.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
-- Function to shuffle the deck of cards
local function shuffleDeck()
local suits = { "Hearts", "Diamonds", "Clubs", "Spades" }
local values = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }

local deck = {}
for _, suit in ipairs(suits) do
for _, value in ipairs(values) do
table.insert(deck, value .. " of " .. suit)
end
end

-- Shuffle the deck
for i = #deck, 2, -1 do
local j = math.random(i)
deck[i], deck[j] = deck[j], deck[i]
end

return deck
end

-- Function to calculate the total value of a hand
local function calculateHandValue(hand)
local value = 0
local hasAce = false

for _, card in ipairs(hand) do
local cardValue = tonumber(card:match("%d+")) or (card:match("Ace") and 11) or 10
value = value + cardValue

if cardValue == 11 then
hasAce = true
end
end

-- If the hand value is over 21 and we have an Ace, treat the Ace as 1 instead of 11
if value > 21 and hasAce then
value = value - 10
end

return value
end

-- Function to draw a card from the deck
local function drawCard(deck, hand)
local card = table.remove(deck, 1)
table.insert(hand, card)
end

-- Function to check if the player wants to play again
local function playAgain()
print("Do you want to play again? (y/n)")
local input = io.read():lower()
return input == "y"
end

-- Main game loop
local function main()
math.randomseed(os.time())
local playerMoney = 1000

while true do
print("Welcome to Blackjack!")
print("You currently have $" .. playerMoney)

local deck = shuffleDeck()
local playerHand = {}
local dealerHand = {}

drawCard(deck, playerHand)
drawCard(deck, dealerHand)
drawCard(deck, playerHand)

while true do
print("Your hand: " .. table.concat(playerHand, ", "))
print("Dealer's face-up card: " .. dealerHand[1])
print("Your hand value: " .. calculateHandValue(playerHand))
print("Options: (h)it, (s)tand")

local input = io.read():lower()

if input == "h" then
drawCard(deck, playerHand)

if calculateHandValue(playerHand) > 21 then
print("Bust! Your hand value is over 21.")
break
end
elseif input == "s" then
break
else
print("Invalid input. Please try again.")
end
end

-- Dealer's turn
while calculateHandValue(dealerHand) < 17 do
drawCard(deck, dealerHand)
end

-- Determine the winner
local playerValue = calculateHandValue(playerHand)
local dealerValue = calculateHandValue(dealerHand)

print("Your hand: " .. table.concat(playerHand, ", "))
print("Your hand value: " .. playerValue)
print("Dealer's hand: " .. table.concat(dealerHand, ", "))
print("Dealer's hand value: " .. dealerValue)

if playerValue > 21 or (dealerValue <= 21 and dealerValue > playerValue) then
print("Dealer wins!")
playerMoney = playerMoney - 10
else
print("You win!")
playerMoney = playerMoney + 10
end

-- Check if the player wants to play again
if playerMoney <= 0 then
print("You've run out of money!")
break
elseif not playAgain() then
break
end
end

print("Thanks for playing Blackjack!")
end

-- Run the game
main()
29 changes: 29 additions & 0 deletions examples/more.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- Function to read the file and output its contents
function readAndOutputFile(filename)
local file = io.open(filename, "r")
if not file then
print("Error: File not found.")
return
end

local lineCount = 0
for line in file:lines() do
lineCount = lineCount + 1
print(line)

if lineCount % 23 == 0 then
io.write("Press Enter to continue or 'q' to quit: ")
local input = io.read()
if input == "q" then
break
end
end
end

file:close()
end

-- Main program
print("Please enter the file name:")
local filename = io.read()
readAndOutputFile(filename)
98 changes: 98 additions & 0 deletions examples/replcli.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@

-- Function to read and display the content of a file
local function catFile(params, filenames)
for _, filename in ipairs(filenames) do
local file = io.open(filename, "r")
if file then
local content = file:read("*a")
io.close(file)

-- Check if "--number" is specified in the parameters
if params["number"] then
local lineNumber = 1
for line in content:gmatch("[^\r\n]+") do
print(string.format("%4d %s", lineNumber, line))
lineNumber = lineNumber + 1
end
else
print(content)
end
else
print("Error: Cannot open file '" .. filename .. "'")
end
end
end

-- Function to echo the parameters to the console
local function echoParams(params, filenames)
local output = {}

-- Add parameters to the output table
for param, value in pairs(params) do
table.insert(output, param .. "=" .. value)
end

-- Add filenames to the output table
for _, filename in ipairs(filenames) do
table.insert(output, filename)
end

-- Print everything on one line
print(table.concat(output, " "))
end

-- Function to parse the user's input into a command, parameters, and optional filenames
local function parseInput(input)
local command, rest = input:match("([%w_]+)%s*(.*)")

local parsedParams = {}
local filenames = {}

for part in rest:gmatch("%S+") do
-- Check if the part starts with "-" or "--" to identify parameters
if part:sub(1, 1) == "-" then
local param, val = part:match("([%-%-]?[%w_]+)=(.*)")
if param then
param = param:sub(1, 2) == "--" and param:sub(3) or param:sub(2)
parsedParams[param] = val
else
param = part:sub(1, 2) == "--" and part:sub(3) or part:sub(2)
parsedParams[param] = true
end
else
table.insert(filenames, part)
end
end

return command, parsedParams, filenames
end

local function runCLI()
print("Welcome to the CLI! Type 'exit' to quit.")

while true do
io.write("> ")
io.flush()

local input = io.read()
if input == "exit" then
break
else
local command, params, filenames = parseInput(input)
-- Handle the "cat" command
if command == "cat" then
catFile(params, filenames)
-- Handle the "echo" command
elseif command == "echo" then
echoParams(params, filenames)
else
print("Invalid input. Please try again.")
end
end
end

print("Goodbye!")
end

runCLI()

0 comments on commit 3ae3ba3

Please sign in to comment.