### Graphics and Animation Use the #link: graphics# or #link: graphicswindow# functions to open a graphics window and start drawing things on screen. You can draw lines, circles, rectangles etc. Co-ordinate (0, 0) is at top left corner. `x` co-ordinate increases as you move down right, and `y` values increase as you move down. Objects are drawn in the currently set draw color. Use #link: setcolor# function to change the draw color. Color is represented by its red, green and blue components. Each can range from 0 to 255. The following program draws a line from top left corner to bottom left corner of the screen. ``` graphics() let screensize = getwindowsize() setcolor(0, 0, 0) clearscreen() setcolor(255, 0, 0) -- red color line(0, 0, screensize.width, screensize.height) render() waitforkey() ``` So generally the procedure to draw stuff on screen is as follows. 1. clear screen using setcolor and clearscreen. 2. Draw stuff on the screen. 3. call `render()` to actually show the drawn stuff. This means that you need to keep track of all the stuff that is on screen and redraw then every frame. To draw incrementally, use non-accelerated mode. ##### Non-accelerated mode Graphics acceleration is enabled by default, and output of the drawing commands are not rendered until #link: render# is called. If you want to draw incremently, you have to disable acceleration. For example, if you want to animate a line being drawn from the left edge of the screen to the right edge, you can use the following program. ``` graphics(false) let screensize = getwindowsize() setcolor(255, 0, 0) for i = 1 to screensize.width point(i, 200) endfor render() waitforkey() ``` ##### Working with screens of different resolutions Since displays vary widely in their sizes and resolutions, dimensions that look good on one display might look too small, or too large in a different display resolution. To workaround this this, use #link: setlogicalsize# function to work in a virtual screen, and have your drawings stretched to the actual resolution automatically. ##### Keyboard input handling Use #link: getkeystate# function to capture the keyboard state and use the `inkeystate` function to query if some keys were pressed during the moment of capture. The following program moves a point across the screen controlled by the arrow keys. You can press up/right arrows simultaneously to move the point diagonally. Example: ``` graphics() setcolor(0, 0, 0) clearscreen() let x = 0 let y = 0 setcolor(255, 255, 255) loop point(x, y) let ks = getkeystate() if inkeystate(ks, scancodes.up) then let y = (y - 1) endif if inkeystate(ks, scancodes.down) then let y = (y + 1) endif if inkeystate(ks, scancodes.left) then let x = (x - 1) endif if inkeystate(ks, scancodes.right) then let x = (x + 1) endif if inkeystate(ks, scancodes.x) then break endif endloop ```