Now you've built a simple chat application :star:! In the next section, we will extend our chat application with more views to create a peer-to-peer game.
Eventually we'd like to add movable characters to the game, so it would be nice if the chat messages only took up a fixed portion along the bottom of the screen.
Two useful modules for managing a fullscreen terminal app's UI are neat-log and txt-blit. Both should already be installed in your workshop folder.
Here is an example terminal app that draws the text HELLO WORLD
animated in the middle of the screen. Type it into a file caled ui.js:
const neatLog = require('neat-log')
const blit = require('txt-blit')
const neat = neatLog(view, { fullscreen: true })
neat.use(mainloop)
const termWidth = process.stdout.columns
const termHeight = process.stdout.rows
function view (state) {
const screen = []
var x = Math.floor(termWidth / 2) + state.xOffset
var y = Math.floor(termHeight / 2)
blit(screen, ['HELLO WORLD'], x, y)
return screen.join('\n')
}
function mainloop (state, bus) {
state.xOffset = 0
setInterval(function () {
state.xOffset = Math.floor(Math.sin(new Date().getTime() / 500) * 20)
bus.emit('render')
}, 5)
}
A common neat-log/txt-blit pattern is to write drawing functions that take a width and height parameter, that you can then draw to any dimensions.
For example, here is a draw function that returns a filled box of the given width/height:
function drawFilledBox (w, h) {
const across = new Array(w).fill('#').join('')
const down = new Array(h).fill(across)
return down
}
Paste this into your code and call it in view
using blit(screen, drawFilledBox(10, 5), 0, 0)
to start.
Now, modify the function to draw the outline of a box (no text on the inside of the box; just the edges). This will become the border around the chat messages we'll draw next!
Next, modify the blit()
call to draw the box so it fills the last 10 rows of the screen, and fills the full width of the screen.
process.stdout.columns
and process.stdout.rows
give the current size of the terminal.Once you solve this exercise continue to exercise 13