Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <meta charset='utf-8'>
- <title>Meu Primeiro Jogo Multiplayer</title>
- <style>
- #screen {
- border: 10px solid #CCC;
- image-rendering: pixelated;
- image-rendering: crisp-edges;
- image-rendering: -moz-crisp-edges;
- width: 400px;
- height: 400px;
- }
- </style>
- </head>
- <body>
- <canvas id='screen' width='10' height='10'></canvas>
- <script>
- const screen = document.getElementById('screen')
- const context = screen.getContext('2d')
- const currentPlayerId = 'player1'
- function createGame() {
- const state = {
- players: {
- 'player1': { x: 1, y: 1 },
- 'player2': { x: 9, y: 9 },
- },
- fruits: {
- 'fruit1': { x: 3, y: 1 }
- }
- }
- function movePlayer(command) {
- console.log(`Moving ${command.playerId} with ${command.keyPressed}`)
- const keyPressed = command.keyPressed
- const player = state.players[command.playerId]
- if (keyPressed === 'ArrowUp' && player.y - 1 >= 0) {
- player.y = player.y - 1
- return
- }
- if (keyPressed === 'ArrowRight' && player.x + 1 < screen.width) {
- player.x = player.x + 1
- return
- }
- if (keyPressed === 'ArrowDown' && player.y + 1 <= screen.height) {
- player.y = player.y + 1
- return
- }
- if (keyPressed === 'ArrowLeft' && player.x - 1 >= 0) {
- player.x = player.x - 1
- return
- }
- }
- return {
- movePlayer, state
- }
- }
- const game = createGame()
- const keyboardListener = createKeyboardListener()
- function createKeyboardListener() {
- const state = {
- observers: []
- }
- function subscribe(observerFunction){
- state.observers.push(observerFunction)
- }
- function notifyAll(command){
- console.log(`Notifying ${state.observers.length} observers`)
- for (const observerFunction of state.observers)
- observerFunction(command)
- }
- document.addEventListener('keydown', handleKeyDown)
- function handleKeyDown(event) {
- const keyPressed = event.key
- const command = {
- playerId: 'player1', keyPressed
- }
- game.movePlayer(command)
- notifyAll(command)
- }
- return{
- subscribe
- }
- }
- renderScreen()
- function renderScreen() {
- context.fillStyle = 'white'
- context.clearRect(0, 0, 10, 10)
- for (const playerId in game.state.players) {
- const player = game.state.players[playerId]
- context.fillStyle = 'black'
- context.fillRect(player.x, player.y, 1, 1)
- }
- for (const fruitId in game.state.fruits) {
- const fruit = game.state.fruits[fruitId]
- context.fillStyle = 'green'
- context.fillRect(fruit.x, fruit.y, 1, 1)
- }
- requestAnimationFrame(renderScreen)
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement