Skip to content

Commit 4e12e09

Browse files
authored
JS Skeleton (#126)
* JS Skeleton * Configure URL
1 parent 7d61bde commit 4e12e09

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

clients/client.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Import the WebSocket library with `npm install ws`
2+
const WebSocket = require('ws');
3+
// Import the readline module to read keypresses
4+
const readline = require('readline');
5+
6+
// --- Configuration ---
7+
// Change your ship name to your initials
8+
const YOUR_NAME_3 = 'YOUXX'
9+
const SERVER = '54.251.134.162'
10+
const SERVER_ADDRESS = 'ws://' + SERVER + '/0/ship/' + YOUR_NAME_3;
11+
12+
// --- WebSocket Connection ---
13+
console.log(`Connecting to ${SERVER_ADDRESS}`);
14+
const ws = new WebSocket(SERVER_ADDRESS);
15+
16+
// --- Event Handlers ---
17+
18+
// Handle the connection opening
19+
ws.on('open', function open() {
20+
console.log('Press "j" for LEFT, "k" for RIGHT, SPACE for FIRE. Press CTRL+C to exit.');
21+
});
22+
23+
// Handle incoming messages from the server
24+
ws.on('message', function incoming(data) {
25+
console.log(`Game state from server: ${data}`);
26+
});
27+
28+
// Handle connection errors
29+
ws.on('error', function error(err) {
30+
console.error('Connection Error:', err.message);
31+
process.exit(1); // Exit the program on error
32+
});
33+
34+
// Handle the connection closing
35+
ws.on('close', function close() {
36+
console.log('Disconnected from the server.');
37+
process.exit(0);
38+
});
39+
40+
// Set up readline to listen for single keypresses
41+
readline.emitKeypressEvents(process.stdin);
42+
if (process.stdin.isTTY) {
43+
process.stdin.setRawMode(true);
44+
}
45+
46+
// Radians
47+
// 0 - EAST
48+
// π/2 - SOUTH
49+
// π - WEST
50+
// 3π/2 - NORTH
51+
var ship_theta = 0.0;
52+
53+
process.stdin.on('keypress', (str, key) => {
54+
if (key.ctrl && key.name === 'c') {
55+
ws.close();
56+
}
57+
58+
if (ws.readyState === WebSocket.OPEN) {
59+
let message = '';
60+
61+
if (key.name === 'j') {
62+
message = '{"theta": ' + ship_theta + '}';
63+
} else if (key.name === 'k') {
64+
message = '{"theta": ' + ship_theta + '}';
65+
} else if (key.name === 'space') {
66+
message = '{"fire":true}';
67+
}
68+
69+
if (message) {
70+
console.log(`Sending: ${message}`);
71+
ws.send(message);
72+
}
73+
} else {
74+
console.log('WebSocket is not connected. Cannot send message.');
75+
}
76+
});

0 commit comments

Comments
 (0)