Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local grid = {}
- -- Defining the 2D table as grid
- local maxX,maxY = term.getSize()
- -- Getting the dimensions of the screen for the game
- local colours = {
- on = colors.green,
- off = colors.red
- }
- -- Defining the colours used below
- for x=1,maxX do
- grid[x] = {}
- for y=1,maxY do
- grid[x][y] = "on"
- end
- end
- -- Making the 2D table with "on" as all of the values
- local function checkWin()
- for i=1,#grid do
- for j=1,#grid[i] do
- if grid[i][j] == "on" then
- return false
- -- If there is a value that is "on" it will immediately return false and prevent further unecessary iterations
- end
- end
- end
- -- Iterating over the 2D table
- return true
- -- If the function hasn't already returned false, it will return true meaning that the user has won
- end
- -- Seeing if the user has won the game or not
- local function toggle(x,y)
- if grid[x][y] == "on" then
- grid[x][y] = "off"
- else
- grid[x][y] = "on"
- end
- end
- -- Toggling the status of a single tile in the 2D table
- local function toggleAdjacent(x,y)
- toggle(x,y)
- -- Toggling the tile that the user has clicked. I don't need an if to see if it exists since i already know it exists
- if grid[x+1] then
- toggle(x+1,y)
- end
- if grid[x-1] then
- toggle(x-1,y)
- end
- if grid[x][y+1] then
- toggle(x,y+1)
- end
- if grid[x][y-1] then
- toggle(x,y-1)
- end
- -- First seeing if the 4 adjacent tiles exist and then if they do, it will toggle them
- end
- local function displayGrid()
- for y=1,#grid do
- for x=1,#grid[y] do
- term.setCursorPos(x,y)
- -- Setting the cursor's position to what the for loop's are up to
- if grid[x][y] == "on" then
- term.setBackgroundColor(colours.on)
- -- Displaying the on colour if the tile is on
- else
- term.setBackgroundColor(colours.off)
- -- Displaying the off colour if the tile is off
- end
- term.write(" ")
- -- displaying the background without text
- end
- end
- end
- -- Displaying the 2D table so that the user can see whats been turned on and off
- while not checkWin() do
- -- Only iterating while the user hasn't won the game
- displayGrid()
- local event, button, clickX, clickY = os.pullEvent("mouse_click")
- -- Getting where the user has clicked
- toggleAdjacent(clickX,clickY)
- -- toggling the adjacent tiles aswell as the tile the user has clicked on
- end
- term.setBackgroundColor(colors.black)
- shell.run("clear")
- print("You Win!")
- sleep(2)
- -- Displaying the win message
Advertisement
Add Comment
Please, Sign In to add comment