Initial Websockets, Rooms & Players done

This commit is contained in:
Johnathon Slightham
2021-02-20 03:43:23 -05:00
parent eb946e93be
commit d9da392ae8
18 changed files with 3964 additions and 104 deletions

3
API/DB.js Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
DB: 'mongodb://localhost:27017/stick-figure-game'
}

View File

@@ -1,17 +1,42 @@
const express = require('express'); const express = require('express');
const app = express(); const app = express();
const webSockets = express();
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const PORT = 4000; const PORT = 4000;
const cors = require('cors'); const cors = require('cors');
const axios = require('axios'); const mongoose = require('mongoose');
const socket = require('socket.io');
const config = require('./DB.js');
const roomRoute = require('./room.route');
var expressWs = require('express-ws')(app);
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
app.use(cors()); app.use(cors());
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use('/rooms', roomRoute);
app.listen(PORT, function () { app.listen(PORT, function () {
console.log('Express server running on port:', PORT); console.log('Express server running on port:', PORT);
})
app.ws('/:id', function (ws, req) {
ws.on('message', function (msg) {
msgJ = JSON.parse(msg);
console.log(req.params.id);
console.log(msgJ.playerId);
ws.send(msg);
}); });
ws.onclose = function (event) {
console.log("Client disconnected from: " + req.params.id);
};
console.log("Client connected to: " + req.params.id);
});

1743
API/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -7,5 +7,16 @@
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"author": "", "author": "",
"license": "ISC" "license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-ws": "^4.0.0",
"mongoose": "^5.11.17",
"socket.io": "^3.1.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
} }

13
API/player.model.js Normal file
View File

@@ -0,0 +1,13 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema for Post
let Player = new Schema({
name: {
type: String
}
}, {
collection: 'players'
});
module.exports = mongoose.model('Player', Player);

0
API/player.route.js Normal file
View File

16
API/room.model.js Normal file
View File

@@ -0,0 +1,16 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema for Post
let Room = new Schema({
title: {
type: String
},
members: {
type: Array
}
}, {
collection: 'rooms'
});
module.exports = mongoose.model('Room', Room);

69
API/room.route.js Normal file
View File

@@ -0,0 +1,69 @@
const express = require('express');
const postRoutes = express.Router();
let Room = require('./room.model');
let Player = require('./player.model');
// Add a room
postRoutes.route('/add').get(function (req, res) {
let r = new Room();
let p = new Player();
r.members.push(p);
r.save()
.then(() => {
let ret = {};
ret._id = r._id;
ret.playerId = p._id;
res.send(ret);
console.log("Created Room");
})
.catch(() => {
console.log("Unable to save to db");
res.status(400).send("Unable to save to the database");
});
});
// Join a room
postRoutes.route('/join').post(function (req, res) {
console.log(req.body);
Room.findById(req.body.id, function (err, r) {
if (err) {
res.json(err);
console.log("Error Joining Room");
} else {
let p = new Player();
r.members.push(p);
r.save().then(() => {
res.send(p);
console.log("Joined Room");
console.log(r.members);
}).catch(() => {
console.log("Unable to save to db");
res.status(400).send("Unable to save to the database")
})
}
})
});
// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
Post.find(function (err, posts) {
if (err) {
res.json(err);
}
else {
res.json(posts);
}
});
});
// Defined delete | remove | destroy route
postRoutes.route('/delete/:id').delete(function (req, res) {
Post.findByIdAndRemove({ _id: req.params.id }, function (err) {
if (err) res.json(err);
else res.json('Successfully removed');
});
});
module.exports = postRoutes;

1928
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,16 +8,26 @@
"lint": "vue-cli-service lint" "lint": "vue-cli-service lint"
}, },
"dependencies": { "dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5", "core-js": "^3.6.5",
"vue": "^2.6.11" "socket.io": "^3.1.1",
"socket.io-client": "^3.1.1",
"vue": "^2.6.11",
"vue-axios": "^3.2.4",
"vue-router": "^3.5.1",
"vue-socket.io": "^3.0.10"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss7-compat": "^2.0.3",
"@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0", "@vue/cli-service": "~4.5.0",
"autoprefixer": "^9.8.6",
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"eslint": "^6.7.2", "eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2", "eslint-plugin-vue": "^6.2.2",
"postcss": "^7.0.35",
"tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.0.3",
"vue-template-compiler": "^2.6.11" "vue-template-compiler": "^2.6.11"
}, },
"eslintConfig": { "eslintConfig": {

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -5,6 +5,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico"> <link rel="icon" href="<%= BASE_URL %>favicon.ico">
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
<title><%= htmlWebpackPlugin.options.title %></title> <title><%= htmlWebpackPlugin.options.title %></title>
</head> </head>
<body> <body>

View File

@@ -1,28 +1,20 @@
<template> <template>
<div id="app"> <div>
<img alt="Vue logo" src="./assets/logo.png"> <router-view></router-view>
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div> </div>
</template> </template>
<script> <script>
import HelloWorld from './components/HelloWorld.vue'
export default { export default {
name: 'App', name: 'app'
components: {
HelloWorld
}
} }
</script> </script>
<style> <style>
#app { @tailwind base;
font-family: Avenir, Helvetica, Arial, sans-serif; @tailwind components;
-webkit-font-smoothing: antialiased; @tailwind utilities;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style> </style>

61
src/components/Game.vue Normal file
View File

@@ -0,0 +1,61 @@
<template>
<div>
<button v-on:click="sendMessage()">Send Message</button>
</div>
</template>
<script>
export default {
data() {
return {
connection: null,
message: {},
};
},
created() {
console.log("Starting connection to websocet server");
console.log(this.$route.params.id);
this.connection = new WebSocket(
"ws://192.168.1.244:4000/" + this.$route.params.id
);
this.connection.onopen = function (event) {
console.log(event);
console.log("Successfully connected to the echo WebSocket Server");
};
this.connection.onmessage = function (event) {
console.log(event); // When we recieve a message
};
},
mounted() {},
methods: {
sendMessage() {
console.log(this.connection);
this.message.playerId = this.getCookie("playerId");
this.message.gameId = this.$route.params.id;
console.log(this.message);
let str = JSON.stringify(this.message);
this.connection.send(str);
},
getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
},
},
};
</script>
<style>
</style>

View File

@@ -1,58 +0,0 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br>
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
</p>
<h3>Installed CLI Plugins</h3>
<ul>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
</ul>
<h3>Essential Links</h3>
<ul>
<li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
<li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
<li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
<li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
<li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

44
src/components/Home.vue Normal file
View File

@@ -0,0 +1,44 @@
<template>
<div class="hello">
Create Room: <button v-on:click="createRoom" style="border: solid">Create Room</button>
<br>
Join Room: <input type="text" v-model="room.id" style="border: solid"> <button v-on:click="joinRoom" style="border: solid">Join Room</button>
</div>
</template>
<script>
export default {
data() {
return {
room: {},
};
},
methods: {
createRoom() {
this.axios.get("http://localhost:4000/rooms/add").then((res) => {
let id = res.data._id;
let playerId = res.data.playerId;
this.setCookie("playerId", playerId, 1);
this.$router.push({path: `game/${id}`});
});
},
joinRoom() {
console.log(this.room);
this.axios.post("http://localhost:4000/rooms/join", this.room).then((res) => {
let playerId = res.data._id;
this.setCookie("playerId", playerId, 1);
this.$router.push({path: `game/${this.room.id}`});
});
},
setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
},
},
};
</script>
<style scoped>
</style>

View File

@@ -1,8 +1,31 @@
import Vue from 'vue' import Vue from 'vue'
import App from './App.vue' import App from './App.vue'
Vue.config.productionTip = false import VueRouter from 'vue-router';
Vue.use(VueRouter);
new Vue({ import VueAxios from 'vue-axios';
render: h => h(App), import axios from 'axios';
}).$mount('#app') Vue.use(VueAxios, axios);
Vue.config.productionTip = false;
import Home from './components/Home.vue';
import Game from './components/Game.vue';
const routes = [
{
name: 'home',
path: '/',
component: Home
},
{
name: 'game',
path: '/game/:id',
component: Game
}
];
const router = new VueRouter({ mode: 'history', routes: routes});
new Vue(Vue.util.extend({ router }, App)).$mount('#app');

11
tailwind.config.js Normal file
View File

@@ -0,0 +1,11 @@
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}