| 1 | <!DOCTYPE html> |
| 2 | <html lang="es"> |
| 3 | |
| 4 | <head> |
| 5 | <meta charset="UTF-8"> |
| 6 | <meta name="viewport" |
| 7 | content="width=device-width"> |
| 8 | <title>Mueve Aleatorio</title> |
| 9 | <style> |
| 10 | .sprite { |
| 11 | position: fixed; |
| 12 | font-size: 3rem; |
| 13 | } |
| 14 | </style> |
| 15 | </head> |
| 16 | |
| 17 | <body> |
| 18 | <h1>Mueve Aleatorio</h1> |
| 19 | <output id="carita" |
| 20 | class="sprite"> |
| 21 | 😄 |
| 22 | </output> |
| 23 | <script> |
| 24 | const REFRESCO = 5 |
| 25 | const RUIDO = 4 |
| 26 | let velocidad = 0.5 |
| 27 | let x = 0 |
| 28 | setInterval(avanza, REFRESCO) |
| 29 | |
| 30 | function avanza() { |
| 31 | const y = innerHeight / 2 |
| 32 | const xMáxima = innerWidth |
| 33 | carita.style.left = `${x}px` |
| 34 | carita.style.bottom = `${y}px` |
| 35 | x += velocidad + |
| 36 | aleatorio(-RUIDO, RUIDO) |
| 37 | if (x < 0) { |
| 38 | x = 0 |
| 39 | velocidad = -velocidad |
| 40 | } else if (x > xMáxima) { |
| 41 | x = xMáxima |
| 42 | velocidad = -velocidad |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | function |
| 61 | aleatorio(menor, mayor) { |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | return menor + |
| 68 | Math.floor( |
| 69 | Math.random() * |
| 70 | (mayor - menor + 1)) |
| 71 | } |
| 72 | </script> |
| 73 | </body> |
| 74 | |
| 75 | </html> |