// An old fashion tennis game based on Japanese comic "こんにちわマイコン". // Testted on IE and Firefox. // Select all, and do it. // Set focus to the game screen, and use left and right cursor keys. // run() // Start the game. // stop() // Stop the game. lastCode = 1; timer = undefined; run = function () { display = new Screen(40, 20); ballX = 0; ballY = 0; ballDX = 1; ballDY = 1; playerX = 20; playerY = display.height - 1; display.node.onkeydown = onGameKey; if (timer) clearInterval(timer); timer = setInterval('tick(display)',100); } stop = function () { clearInterval(timer); } tick = function (display) { display.print(ballX, ballY, " "); display.print(playerX, display.height - 1, " "); ballX += ballDX; ballY += ballDY; if (ballX <= 0 || display.width <= ballX) ballDX = 0 - ballDX; if (ballY <= 0) ballDY = 0 - ballDY; if (ballY == (playerY - 1) && (playerX - 1) <= ballX && ballX <= (playerX + 3)) ballDY = -1; if (lastCode) { if (lastCode== 37) playerX = (display.width + playerX - 1) % display.width; if (lastCode== 39) playerX = (playerX + 1) % display.width; lastCode= 0; } display.print(ballX, ballY, "O"); display.print(playerX, display.height - 1, "==="); if (playerY <= ballY) { stop(); display.print(10, 10, "[ G A M E O V E R ]"); } display.show(); } onGameKey = function(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.charCode) ? evt.charCode : evt.keyCode; lastCode = charCode ; return false; } /* Screen library */ Screen = function (width, height) { this.node = initScreen(width, height); this.width = width; this.height = height; this.buffer =""; for (var i = 0; i < width * height; i++) this.buffer += " "; } /* Initialize the screen. */ initScreen = function (width, height) { if (typeof textarea != "undefined") { textarea.parentNode.removeChild(textarea); textarea = undefined; } textarea = document.createElement("textarea"); workspace.parentNode.insertBefore(textarea, workspace); textarea.cols = width + 1; textarea.rows = height + 1; with (textarea.style) { background = "black"; color= "green"; border = "4px solid #cccccc" position = "absolute"; right = "10px"; top = "10px"; } return textarea; } Screen.prototype.show = function () { var screenBuffer = ""; for (var y = 0; y < this.height; y++) { screenBuffer += this.buffer.slice(y * this.width, y * this.width + this.width) + "\n"; } this.node.value = screenBuffer; } Screen.prototype.print = function (x, y, aString) { var position = x + y * this.width; this.buffer = this.buffer.slice(0, position) + aString + this.buffer.slice(position + aString.length); } run(); // workspace.rows = 120; /* I recommend larger textarea during hacking. */