Browse Source

Almost working!

iam 1 year ago
parent
commit
b469e76bed

File diff suppressed because it is too large
+ 1 - 1
info


+ 26 - 4
webserver/app.js

@@ -4,13 +4,15 @@ var favicon = require('static-favicon');
4 4
 var logger = require('morgan');
5 5
 var cookieParser = require('cookie-parser');
6 6
 var bodyParser = require('body-parser');
7
-fs = require("fs");
7
+var fs = require("fs");
8 8
 
9 9
 var findGames = require('./routes/findGames');
10
-var sendGames = require('./routes/sendGame');
10
+var playGame = require('./routes/playGame')
11 11
 var misc = require('./routes/misc');
12 12
 
13 13
 var app = express();
14
+var http = require('http').Server(app);
15
+var io = require('socket.io')(http);
14 16
 
15 17
 app.use(favicon());
16 18
 app.use(logger('dev'));
@@ -28,6 +30,13 @@ app.use('/', findGames);
28 30
 app.use('/contact', misc);
29 31
 app.use('/about', misc);
30 32
 
33
+var mainGameServer = require('child_process').spawn('./game')
34
+
35
+require('./routes/manageSocket')(io, mainGameServer);
36
+require('./routes/getGames')(mainGameServer);
37
+
38
+app.use('/playGame', playGame);
39
+
31 40
 /// catch 404 and forward to error handler
32 41
 app.use(function(req, res, next) {
33 42
     var err = new Error('Not Found');
@@ -56,9 +65,22 @@ app.use(function(err, req, res, next) {
56 65
 app.set('port', process.env.PORT || 3000);
57 66
 
58 67
 if(fs.existsSync('../info')) {
59
-    var server = app.listen(app.get('port'), function() {
60
-        console.log('Server listening on port ' + server.address().port);
68
+    http.listen(app.get('port'), function() {
69
+        console.log('Server listening on port ' + app.get('port'));
61 70
     });
62 71
 } else {
63 72
     console.log("Error: info file not found");
64 73
 }
74
+
75
+function closeServer(callback_)
76
+{
77
+    console.log('Stopping ...');
78
+    mainGameServer.kill('SIGINT');
79
+    callback_();
80
+}
81
+
82
+process.on('SIGINT', function() {
83
+    closeServer(function() {
84
+        process.exit();
85
+    });
86
+});

+ 3 - 0
webserver/dboutline

@@ -0,0 +1,3 @@
1
+Users:
2
+    UserID: <sessionid>
3
+    GameKeys: [<keys>]

+ 65 - 0
webserver/game.txt

@@ -0,0 +1,65 @@
1
+;setup;
2
+    text: fork in the road
3
+    var: moo = muu
4
+    info: the current storyline is $storyline and your health is $health
5
+    info: moo is $int($calc(1+1+1+0.5+int(10.7)))
6
+    
7
+    if: (item(moo >= 10)&item(moo >= 1000))|(life(> 1000)|gameclock(> 10))
8
+        option: item
9
+            var: moo = true
10
+            info: You gain 500 health!
11
+            health: +500|You died
12
+            info: you find 500 moos
13
+            item: moo+500
14
+            goto: ;setup;
15
+        option: hasMOOs
16
+            info: this was just a test
17
+            goto: ;setup;
18
+        endoption
19
+    endif
20
+    
21
+    if: var(moo=true)
22
+        option: Moo is true!
23
+            goto: ;setup;
24
+        endoption
25
+    endif
26
+    
27
+    if: life(> 1000)
28
+        option: highHealth!
29
+            info: wow high health
30
+            goto: ;setup;
31
+        endoption
32
+    endif
33
+    
34
+    if: gameclock(> 10)
35
+        option: you have lived over 10 moves
36
+            info: wow high gameclock
37
+            goto: ;setup;
38
+        endoption
39
+    endif
40
+    
41
+    option: get free moos
42
+        goto: ;moos;
43
+    option: lose health
44
+        info: you lose 10 health
45
+        health: -10|You died
46
+        goto: ;setup;
47
+    option: end game
48
+        endgame: moo
49
+    endoption
50
+end
51
+
52
+;moos;
53
+    text: You found a moo farm and were given 500 moos
54
+    
55
+    item: moo+500
56
+    info: moo + 500!
57
+    
58
+    option: give back moos
59
+        info: Why... idk but you give them all back
60
+        item: moo-500
61
+        goto: ;setup;
62
+    option: back
63
+        goto: ;setup;
64
+    endoption
65
+end

File diff suppressed because it is too large
+ 2 - 2
webserver/html/findGame.html


+ 3 - 1
webserver/html/headings/footer.ejs

@@ -1,3 +1,5 @@
1 1
 <footer>
2
-    Ace Parent - Text Game 4 Web UI © 2016
2
+    <div class="container">
3
+        Ace Parent - Text Game 4 Web UI © 2016
4
+    </div>
3 5
 </footer>

+ 1 - 0
webserver/html/headings/navbar.ejs

@@ -13,6 +13,7 @@
13 13
             <ul class="nav navbar-nav">
14 14
               <li <%if (active == "Home") { %>class="active" <% } %> ><a href="/">Home</a></li>
15 15
               <li <%if (active == "Find") { %>class="active" <% } %> ><a href="/findgame">Find Game</a></li>
16
+              <li <%if (active == "Resume") { %>class="active" <% } %> ><a href="/resume">Resume Game</a></li>
16 17
               <li <%if (active == "About") { %>class="active" <% } %> ><a href="/about">About</a></li>
17 18
               <li <%if (active == "Contact") { %>class="active" <% } %> ><a href="/contact">Contact</a></li>
18 19
             </ul>

+ 46 - 0
webserver/html/playGame.html

@@ -0,0 +1,46 @@
1
+<!DOCTYPE html>
2
+<html>
3
+    <head>
4
+        <%- include ./headings/header.ejs %>
5
+        <title>RPG</title>
6
+        <link rel="stylesheet" href="/stylesheets/game.css"> <!-- CSS Created by boxmein -->
7
+    </head>
8
+    
9
+    <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
10
+    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
11
+    
12
+    <body>
13
+        <%- include ./headings/navbar.ejs %>
14
+        <div class="container gameText">
15
+            <div id="log"></div>
16
+            <div class="textarea"><span id="lts">&lt;&lt;</span><input id="textbox" type="text" autofocus></div>
17
+        </div>
18
+    </body>
19
+    
20
+    <%- include ./headings/footer.ejs %>
21
+    
22
+    <script>
23
+        var socket = io();
24
+        
25
+        $('#textbox').bind("enterKey",function(e){
26
+            socket.emit('out', $("#textbox").val());
27
+            $("#log").append("<br><b>>&emsp;&emsp;" + $("#textbox").val() + "</b><br>");
28
+            $("#textbox").val("");
29
+        });
30
+        
31
+        $('#textbox').keyup(function(e){
32
+            if(e.keyCode == 13)
33
+            {
34
+                $(this).trigger("enterKey");
35
+            }
36
+        });
37
+        
38
+        socket.on('in', function(data) {
39
+            console.log(data);
40
+            $("#log").append(data);
41
+            $("html, body").stop();
42
+            $("html, body").animate({ scrollTop: $(document).height() }, "slow");
43
+            return false;
44
+        });
45
+    </script>
46
+</html>

+ 16 - 0
webserver/html/resumeGame.html

@@ -0,0 +1,16 @@
1
+<!DOCTYPE html>
2
+<html lang="en">
3
+    <head>
4
+        <%- include ./headings/header.ejs %>
5
+        <title>Resume</title>
6
+    </head>
7
+    <body>
8
+        <%- include ./headings/navbar.ejs %>
9
+        <div class="container">
10
+            Resume
11
+            <hr>
12
+            <%=JSON.stringify(sessions)%>
13
+        </div>
14
+    </body>
15
+    <%- include ./headings/footer.ejs %>
16
+</html>

+ 16 - 4
webserver/public/stylesheets/footer.css

@@ -1,8 +1,20 @@
1 1
 footer{
2
-   position:fixed;
3
-   left:0px;
4
-   bottom:0px;
5
-   height:30px;
2
+   height:40px;
6 3
    width:100%;
7 4
    background:#999;
5
+   padding-top: 10px;
6
+}
7
+
8
+body {
9
+  min-height: 100%;
10
+  display: flex;
11
+  flex-direction: column;
12
+}
13
+
14
+.container {
15
+   flex: 1 0 auto;
16
+}
17
+
18
+html {
19
+  height: 100%;
8 20
 }

+ 89 - 0
webserver/public/stylesheets/game.css

@@ -0,0 +1,89 @@
1
+#game {
2
+    font-family: "Courier New", Courier, monospace;
3
+}
4
+
5
+.gameText
6
+{
7
+    background: white;
8
+    color: black;
9
+    font-family: monospace;
10
+}
11
+
12
+#log
13
+{
14
+    color: #555;
15
+    max-width: 960px;
16
+    margin-top: 50px;
17
+}
18
+
19
+#log:after
20
+{
21
+    content: ' ';
22
+    display: block;
23
+    height: 150px;
24
+}
25
+
26
+#log b
27
+{
28
+    color: #000;
29
+}
30
+
31
+.textarea
32
+{
33
+    background-color: rgba(255, 255, 255, 0.5);
34
+    bottom: 50px;
35
+    height: 50px;
36
+    left: 8px;
37
+    max-width: 960px;
38
+    position: fixed;
39
+    right: 20px;
40
+}
41
+#lts
42
+{
43
+    font-size: 14pt;
44
+}
45
+#textbox
46
+{
47
+    background-color: white;
48
+    border: 2px solid rgba(0, 0, 0, 0.1);
49
+    color: black;
50
+    font-family: monospace;
51
+    font-size: 16px;
52
+    margin-left: 5px;
53
+    width: 95%;
54
+}
55
+.line
56
+{
57
+    white-space: pre-line;
58
+}
59
+@media screen and (min-width: 910px)
60
+{
61
+    .textarea,#log
62
+    {
63
+        margin-left: 192px !important;
64
+        margin-right: 192px !important;
65
+    }
66
+}
67
+@media screen and (max-width: 500px)
68
+{
69
+    #lts
70
+    {
71
+        display: none;
72
+    }
73
+}
74
+
75
+.restart {
76
+    box-shadow: 0px 1px 0px 0px #FFF inset;
77
+    background: #F9F9F9 linear-gradient(to bottom, #F9F9F9 5%, #E9E9E9 100%) repeat scroll 0% 0%;
78
+    border-radius: 6px;
79
+    border: 1px solid #DCDCDC;
80
+    display: inline-block;
81
+    cursor: pointer;
82
+    color: #666;
83
+    font-family: Arial;
84
+    font-size: 15px;
85
+    font-weight: bold;
86
+    padding: 6px 18px;
87
+    text-decoration: none;
88
+    text-shadow: 0px 1px 0px #FFF;
89
+}

BIN
webserver/public/thumbnails/shopping.jpeg


BIN
webserver/public/thumbnails/village.jpg


+ 56 - 25
webserver/routes/findGames.js

@@ -2,6 +2,7 @@ var express = require('express');
2 2
 var router = express.Router();
3 3
 var ejs = require('ejs');
4 4
 var fs = require('fs');
5
+var getGames = require('./getGames');
5 6
 
6 7
 var baseFilePath = '/../html/'
7 8
 
@@ -14,34 +15,64 @@ function findGames(callback_)
14 15
 }
15 16
 
16 17
 router.get('/findgame', function(req, res) {
17
-    findGames(function(games) {
18
-        ejs.renderFile(__dirname + baseFilePath + 'findGame.html', {active:"Find", games:games}, function(err, result) {
19
-            if (!err) {
20
-                res.end(result);
21
-            } else {
22
-                res.end(err.toString());
23
-                console.log(err);
24
-            }
18
+    if("sessionID" in req.cookies) {
19
+        findGames(function(games) {
20
+            ejs.renderFile(__dirname + baseFilePath + 'findGame.html', {active:"Find", games:games}, function(err, result) {
21
+                if (!err) {
22
+                    res.end(result);
23
+                } else {
24
+                    res.end(err.toString());
25
+                    console.log(err);
26
+                }
27
+            });
25 28
         });
26
-    });
29
+    } else {
30
+        getGames.createUser(res, function() {
31
+            res.end("Cookie set");
32
+        });
33
+    }
27 34
 });
28 35
 
29
-function generateHash()
30
-{
31
-    var hash = "";
32
-    for(var x = 0; x <= 9; x++)
33
-    {
34
-        currentChar = Math.floor(Math.random() * 36);
35
-        if(currentChar > 9)
36
-        {
37
-            hash += String.fromCharCode(currentChar + 55);
38
-        } else {
39
-            hash += currentChar;
40
-        }
41
-        
42
-        if(x == 9)
43
-            return hash;
36
+router.get('/resume', function(req, res) {
37
+    if("sessionID" in req.cookies) {
38
+        getGames.getUser(req.cookies['sessionID'], function(data) {
39
+            findGames(function(games) {
40
+                ejs.renderFile(__dirname + baseFilePath + 'resumeGame.html', {active:"Resume", sessions:data, games:games}, function(err, result) {
41
+                    if (!err) {
42
+                        res.end(result);
43
+                    } else {
44
+                        res.end(err.toString());
45
+                        console.log(err);
46
+                    }
47
+                });
48
+            });
49
+        });
50
+    } else {
51
+        getGames.createUser(res, function() {
52
+            res.end("Cookie set");
53
+        });
44 54
     }
45
-}
55
+});
46 56
 
47 57
 module.exports = router;
58
+module.exports.findGames = findGames;
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+

+ 92 - 0
webserver/routes/getGames.js

@@ -0,0 +1,92 @@
1
+var mongodb = require('mongodb'),
2
+    MongoClient = mongodb.MongoClient,
3
+    url = 'mongodb://localhost:27017/textgame';
4
+
5
+function generateHash()
6
+{
7
+    var hash = "";
8
+    for(var x = 0; x <= 9; x++)
9
+    {
10
+        currentChar = Math.floor(Math.random() * 36);
11
+        if(currentChar > 9)
12
+        {
13
+            hash += String.fromCharCode(currentChar + 55);
14
+        } else {
15
+            hash += currentChar;
16
+        }
17
+        
18
+        if(x == 9)
19
+            return hash;
20
+    }
21
+}
22
+
23
+function createUser(res, callback_)
24
+{
25
+    var key = generateHash();
26
+    
27
+    MongoClient.connect(url, function (err, db) {
28
+        if (err) {
29
+            console.log('Unable to connect to the mongoDB server. Error:', err);
30
+        } else {
31
+            res.cookie('sessionID', key, {expires: new Date(2147483647000)});
32
+            
33
+            db.collection("Users", function(error, collection) {
34
+                collection.insert({
35
+                GameKeys:[],
36
+                UserID: key
37
+            }, function() {
38
+                console.log("successfully added key " + key);
39
+                db.close();
40
+                callback_(key);
41
+            });
42
+            });
43
+        }
44
+    });
45
+}
46
+
47
+function getUser(key, callback_)
48
+{
49
+    MongoClient.connect(url, function (err, db) {
50
+        if (err) {
51
+            console.log('Unable to connect to the mongoDB server. Error:', err);
52
+            callback_('error');
53
+        } else {
54
+            var collection = db.collection("Users");
55
+            console.log(key);
56
+            collection.find({UserID:key}).toArray(function(err, docs){
57
+                db.close();
58
+                callback_(docs);
59
+            });
60
+        }
61
+    });
62
+}
63
+
64
+module.exports = function(mainGameServer)
65
+{
66
+    function createGame(key, gameInfo, callback_)
67
+    {
68
+        var gameKey = generateHash();
69
+        MongoClient.connect(url, function (err, db) {
70
+            if (err) {
71
+                console.log('Unable to connect to the mongoDB server. Error:', err);
72
+                callback_('error');
73
+            } else {
74
+                var collection = db.collection("Users");
75
+                collection.update({'UserID': key},{$push: { 'GameKeys': {key:gameKey, path:gameInfo['Path']} }}, function(err) {
76
+                    //add game here
77
+                    //File, Start
78
+                    console.log("New game created " + JSON.stringify(gameInfo));
79
+                    
80
+                    mainGameServer.stdin.write("NEW " + gameKey + " " + gameInfo['File'] + " " + gameInfo['Start'] +'\n');
81
+                    
82
+                    db.close();
83
+                    callback_(gameKey);
84
+                });
85
+            }
86
+        });
87
+    }
88
+    module.exports.createGame = createGame;
89
+}
90
+
91
+module.exports.createUser = createUser;
92
+module.exports.getUser = getUser;

+ 103 - 0
webserver/routes/manageSocket.js

@@ -0,0 +1,103 @@
1
+var getGames = require('./getGames');
2
+
3
+module.exports = function(io, mainGameServer)
4
+{
5
+    var sockets = {};
6
+    
7
+    //data sends faster than client connects
8
+    var sendBuffer = {};
9
+    
10
+    function readBuffer() {
11
+        for(x in sendBuffer)
12
+        {
13
+            if(sendBuffer[x].length > 0)
14
+            {
15
+                //console.log(sendBuffer[x])
16
+                
17
+                if(x in sockets)
18
+                {
19
+                    sockets[x].emit('in', sendBuffer[x].join("<br>"));
20
+                    sendBuffer[x] = [];
21
+                    //console.log(sendBuffer);
22
+                }
23
+            }
24
+        }
25
+    }
26
+    //send buffer every x milliseconds
27
+    setInterval(readBuffer, 1000);
28
+    
29
+    mainGameServer.stdout.on('data', function(data) {
30
+        data = data.toString();
31
+        datum = data.split('\n');
32
+        
33
+        for(x in datum)
34
+        {
35
+            w = datum[x].split(' ');
36
+            gameKey = w.slice(w.length-1, w.length)[0];
37
+            toReturn = w.slice(0,w.length-1).join(" ");
38
+            //console.log(gameKey)
39
+            
40
+            if(!(gameKey in sendBuffer))
41
+                sendBuffer[gameKey] = [];
42
+            
43
+            if(toReturn != [''])
44
+                sendBuffer[gameKey].push(toReturn.split("    ").join("&nbsp;&nbsp;&nbsp;&nbsp;"));
45
+        }
46
+    });
47
+    
48
+    io.on('connection', function(socket){
49
+        cookies = socket.request.headers.cookie;
50
+        
51
+        if(cookies !== undefined)
52
+        {
53
+            sections = cookies.split('; ');
54
+            cookieObject = {}
55
+            for (x in sections)
56
+            {
57
+                isSplit = sections[x].split('=')
58
+                cookieObject[isSplit[0]] = isSplit[1]
59
+            }
60
+            
61
+            sockets[cookieObject['currentGame']] = socket;
62
+        }
63
+        
64
+        console.log("Connected");
65
+        
66
+        socket.on('out', function(msg){
67
+            
68
+            cookies = socket.request.headers.cookie;
69
+            console.log(cookies);
70
+            
71
+            sections = cookies.split('; ');
72
+            cookieObject = {}
73
+            for (x in sections)
74
+            {
75
+                isSplit = sections[x].split('=')
76
+                cookieObject[isSplit[0]] = isSplit[1]
77
+            }
78
+            
79
+            console.log(msg);
80
+            console.log(cookieObject);
81
+            //console.log(sockets);
82
+            
83
+            //make sure right user is playing right game
84
+            getGames.getUser(cookieObject['sessionID'], function(data) {
85
+                if(data.length > 0)
86
+                {
87
+                    findingGame = data[0]['GameKeys'].filter(function(v){ return v["key"] == cookieObject['currentGame'];});
88
+                    
89
+                    if(findingGame.length > 0)
90
+                    {
91
+                        toSend = msg + " " + cookieObject['currentGame'] + "|\n";
92
+                        mainGameServer.stdin.write(toSend);
93
+                    }
94
+                    else
95
+                        console.log("Error: game not associated with user"); 
96
+                }
97
+                else
98
+                    console.log("Error: sessionID not found");
99
+            });
100
+            
101
+        });
102
+    });
103
+}

+ 73 - 0
webserver/routes/playGame.js

@@ -0,0 +1,73 @@
1
+var ejs = require('ejs');
2
+var fs = require('fs');
3
+var findGames = require('./findGames');
4
+var getGames = require('./getGames');
5
+
6
+var express = require('express')
7
+var router = express.Router();
8
+
9
+var baseFilePath = '/../html/'
10
+
11
+function renderPage(callback_)
12
+{
13
+    ejs.renderFile(__dirname + baseFilePath + 'playGame.html', {active:"Play"}, function(err, result) {
14
+        if (!err) {
15
+            callback_(result);
16
+        } else {
17
+            callback_(err.toString());
18
+            console.log(err);
19
+        }
20
+    });
21
+}
22
+
23
+router.get('/*', function(req, res) {
24
+    findGames.findGames(function(data) {
25
+        
26
+        newData = data['Games'].filter(function(v){ return v["Path"] == req.url;});
27
+        
28
+        if(newData.length > 0)
29
+        {
30
+            if("sessionID" in req.cookies) {
31
+                if("currentGame" in req.cookies && req.cookies['currentGamePath'] == req.url) {
32
+                    renderPage(function(data) {
33
+                        res.end(data);
34
+                    });
35
+                    //res.end(JSON.stringify(newData[0]) + req.cookies['sessionID']);
36
+                } else {
37
+                    getGames.createGame(req.cookies['sessionID'], newData[0], function(newKey) {
38
+                        res.cookie('currentGame', newKey, {expires: new Date(2147483647000)});
39
+                        res.cookie('currentGamePath', req.url, {expires: new Date(2147483647000)});
40
+                        
41
+                        renderPage(function(data) {
42
+                            res.end(data);
43
+                        });
44
+                        //res.end(JSON.stringify(newData[0]) + req.cookies['sessionID'] + " " + newKey);
45
+                    });
46
+                }
47
+            } else {
48
+                getGames.createUser(res, function(returnedKey) {
49
+                    getGames.createGame(returnedKey, newData[0], function(newKey) {
50
+                        res.cookie('currentGame', newKey, {expires: new Date(2147483647000)});
51
+                        res.cookie('currentGamePath', req.url, {expires: new Date(2147483647000)})
52
+                        res.end("Cookie set");
53
+                    });
54
+                });
55
+            }
56
+        } else {
57
+            res.end("Error: Game path not found");
58
+        }
59
+    });
60
+});
61
+
62
+/*
63
+    ejs.renderFile(__dirname + baseFilePath + 'contact.html', {active:"Contact"}, function(err, result) {
64
+        if (!err) {
65
+            res.end(result);
66
+        } else {
67
+            res.end(err.toString());
68
+            console.log(err);
69
+        }
70
+    });
71
+*/
72
+
73
+module.exports = router;

+ 0 - 0
webserver/routes/sendGame.js