Tag [Live Web]

live-web

Building Cursor Tag

server side attempt (js)

// We need the file system here
var fs = require('fs');
				
// Express is a node module for building HTTP servers
var express = require('express');
var app = express();

// Tell Express to look in the "public" folder for any files first
app.use(express.static('public'));

// If the user just goes to the "route" / then run this function
app.get('/', function (req, res) {
  res.send('Hello World!')
});

// In this case, HTTPS (secure) server
var https = require('https');

// Security options - key and certificate
var options = {
  key: fs.readFileSync('privkey1.pem'),
  cert: fs.readFileSync('cert1.pem')
};

// We pass in the Express object and the options object
var httpServer = https.createServer(options, app);

// Default HTTPS port
httpServer.listen(443);

// WebSocket Portion
// WebSockets work with the HTTP server
// Using Socket.io
const { Server } = require('socket.io');
const io = new Server(httpServer, {});


// Object to store the current state of the game
const gameState = {
    users: {}, // A dictionary to store each user's information
    it: null, // The user who is currently "it"
  };

// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects

// Handle Socket.io connections
io.on('connection', (socket) => {
    // Send a prompt to the user to enter their username
    socket.emit('prompt');
  
    // Handle incoming messages from the client
    socket.on('message', (message) => {
      const data = JSON.parse(message);
      switch (data.type) {
        // When a user enters their username, add them to the gameState
        case 'username':
          const newUser = {
            username: data.username,
            color: 'blue',
            x: 0,
            y: 0,
          };
          gameState.users[socket.id] = newUser;
          broadcastGameState();
          break;
  
        // When a user moves their cursor, update their position and broadcast the new state
        case 'position':
          const user = gameState.users[socket.id];
          user.x = data.x;
          user.y = data.y;
          broadcastGameState();
          break;
  
        // When a user clicks the "who's it?" button, update the gameState
        case 'click':
          gameState.it = socket.id;
          updateCursorColors();
          broadcastGameState();
          break;
      }
    });
  
    // Handle Socket.io disconnections
    socket.on('disconnect', () => {
      delete gameState.users[socket.id];
      broadcastGameState();
    });
  });
  
  // Broadcast the current gameState to all connected clients
  function broadcastGameState() {
    io.emit('gameState', gameState);
  }
  
  // Update the cursor colors based on the current gameState
  function updateCursorColors() {
    const it = gameState.it;
    const users = gameState.users;
    for (const socketId in users) {
      const user = users[socketId];
      if (socketId === it) {
        user.color = 'red';
      } else {
        user.color = 'blue';
      }
    }
  }
  
  // // Start the server
  // server.listen(3000, () => {
  //   console.log('Server listening on port 3000');
  // });

// io.on('connection', 
// 	// We are given a websocket object in our function
// 	function (socket) {
// 	  // Send a prompt to the user to enter their username
//       socket.emit('prompt');

// 		console.log("We have a new client: " + socket.id);
		
// 		// When this user emits, client side: socket.emit('otherevent',some data);
// 		socket.on('chatmessage', function(data) {
// 			// Data comes in as whatever was sent, including objects
// 			console.log("Received: 'chatmessage' " + data);
			
// 			// Send it to all of the clients
// 			socket.broadcast.emit('chatmessage', data);
// 		});
		
// 		socket.on('disconnect', function() {
// 			console.log("Client has disconnected " + socket.id);
// 		});
// 	}
// );

Client side code (html w inline css + script):

<html>
	<head>
		<script type="text/javascript" src="/socket.io/socket.io.js"></script>
		<script type="text/javascript">
		
			var socket = io.connect();
            var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

			
			socket.on('connect', function() {
				console.log("Connected");
			});

  // Handle the 'prompt' event by displaying a prompt to the user to enter their username
  socket.on('prompt', () => {
    const username = prompt('Please enter your username:');
    socket.emit('message', JSON.stringify({ type: 'username', username }));
  });
  
  socket.on('gameState', function(data) {
  // Parse the data received from the server
  var gameState = JSON.parse(data);

  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the game state on the canvas
  // For example, draw a circle at position (x, y) with radius r:
  ctx.beginPath();
  ctx.arc(gameState.x, gameState.y, gameState.r, 0, 2 * Math.PI);
  ctx.fillStyle = 'red';
  ctx.fill();
});

  
  // Add event listeners to update the server when the user moves their cursor or clicks the "who's it?" button
  // (e.g. using jQuery to listen for mousemove and click events)
  $(document).on('mousemove', (event) => {
    const { pageX: x, pageY: y } = event;
    socket.emit('message', JSON.stringify({ type: 'position', x, y }));
  });
  
  $('#who-is-it-button').on('click', () => {
    socket.emit('message', JSON.stringify({ type: 'click' }));
  })

canvas.addEventListener('mousemove', function(event) {
  var x = event.clientX;
  var y = event.clientY;
  socket.emit('message', JSON.stringify({type: 'position', x: x, y: y}));
});

	
		</script>	
      <style>
        canvas {
           position:absolute;
           top:0;
           left:0;
          right:0;
           width:100%;
           height:100%;
           z-index:-1;
        }
    
    body{
      text-align: center;
    }
  </style>
	</head>
 <body>
    <canvas id="myCanvas"></canvas>

 <input type="text" id="message" name="message">
 <input type="submit" value="submit" onclick="sendmessage(document.getElementById('message').value);">
 </body>
</html>