Last active
December 27, 2023 21:25
-
-
Save TheTrueShell/91aadbcb1df972b4143664056d1d9db2 to your computer and use it in GitHub Desktop.
cc main
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Central Bank Server Script for Computercraft | |
-- Table to store account information | |
local accounts = {} | |
-- Load existing accounts from disk (if any) | |
local function loadAccounts() | |
if fs.exists("accounts") then | |
local file = fs.open("accounts", "r") | |
accounts = textutils.unserialize(file.readAll()) | |
file.close() | |
end | |
end | |
-- Save accounts to disk | |
local function saveAccounts() | |
local file = fs.open("accounts", "w") | |
file.write(textutils.serialize(accounts)) | |
file.close() | |
end | |
-- Handle a request from an ATM | |
local function handleRequest(senderID, request) | |
local accountID = request.accountID | |
local action = request.action | |
local amount = request.amount | |
-- Check if the account exists | |
if accounts[accountID] == nil then | |
return "Account not found" | |
end | |
if action == "balance" then | |
-- Return the account balance | |
return accounts[accountID].balance | |
elseif action == "deposit" then | |
-- Process deposit | |
accounts[accountID].balance = accounts[accountID].balance + amount | |
saveAccounts() | |
return "Deposit successful" | |
elseif action == "withdraw" then | |
-- Process withdrawal | |
if accounts[accountID].balance >= amount then | |
accounts[accountID].balance = accounts[accountID].balance - amount | |
saveAccounts() | |
return "Withdrawal successful" | |
else | |
return "Insufficient funds" | |
end | |
else | |
return "Invalid action" | |
end | |
end | |
-- Main function | |
local function main() | |
loadAccounts() | |
-- Open modem | |
local modem = peripheral.find("modem") | |
if not modem then | |
print("No modem attached") | |
return | |
end | |
modem.open(1) -- Open on channel 1, for example | |
-- Main loop | |
while true do | |
local event, side, senderChannel, replyChannel, message, senderDistance = os.pullEvent("modem_message") | |
-- Check if the message is for the bank | |
if senderChannel == 1 then | |
local response = handleRequest(senderID, message) | |
modem.transmit(replyChannel, 1, response) | |
end | |
end | |
end | |
-- Run the main function | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment