scieee AI-readable full text Open interactive document viewer

GAP - Game Advantage Protocol

Rui Jorge Ferreira de Almeida

Abstract

O principal objetivo desta dissertação era criar uma API que facilitasse a tarefa de integrar indicadores da vida real, tais como eficiência energética, em aplicações virtuais como videojogos, idealmente fazendo que ações positivas da vida real desencadeassem resultados favoráveis em vídeo jogos motivando assim a adoção de bons hábitos. Começa por analisar o estado da arte no que diz respeito a jogos de realidade aumentada e gamification, dois temas que ganharam mais atenção com o crescimento da indústria dos vídeo jogos e graças à maneira como os media e a internet se tornaram uma parte integral da sociedade humana. Também se analisaram os conceitos e tecnologias de web services e comunicação online para verificar como o use de Node.js e Socket.io são as melhores escolhas para o projeto. Estas são 2 tecnologias que têm ganho bastante popularidade e com boa razão, o use de ambos em conjunto fornecem uma excelente solução quando se criam web services que procuram velocidade, eficiência e escalabilidade. Em termos de arquitetura a solução está dividida da seguinte forma: a API em Java usada tanto pelos criadores de aplicações como os fornecedores de informação que inclui as funções necessárias para facilitar o seu trabalho; os scripts de comunicação que usam Node.js e Socket.io, responsáveis por redirecionar os pedidos da API através do use de mensagens do cliente para o servidor que por sua vez as processa e cria a query adequada para enviar à base de dados. Como prova de conceito foi feito uma experiência com um grupo de pessoas para avaliar o impacto quando estas tiverem um pequeno aspeto das suas vidas quotidianas gamificado. O aspeto em questão era minimizar as janelas que não usam ativamente quando utilizam o computador. A experiência também serviu para realçar a facilidade de uso da API do GAP quando se toma o papel de desenvolvedor ou fornecedor de dados. Devido à natureza de estudos comportamentais e o facto do grupo usado ser relativamente pequeno recomenda-se um estudo mais prolongado e detalhado.

Full text

FACULDADE DE ENGENHARIA DA UNIVERSIDADE DO PORTO GAP – Game Advantage Protocol Rui Jorge Ferreira de Almeida Mestrado Integrado em Engenharia Informática e Computação Orientador: Professor Rui Pedro Amaral Rodrigues Janeiro de 2015 © Rui Jorge Ferreira Almeida, 2015 GAP – Game Advantage Protocol Rui Jorge Ferreira de Almeida Mestrado Integrado em Engenharia Informática e Computação Aprovado em provas públicas pelo Júri: Presidente: Professor Jorge Barbosa Vogal Externo: Professor Paulo Dias Orientador: Professor Rui Rodrigues ____________________________________________________ 26 de Janeiro de 2015 Resumo O principal objetivo desta dissertação era criar uma API que facilitasse a tarefa de integrar indicadores da vida real, tais como eficiência energética, em aplicações virtuais como videojogos, idealmente fazendo que ações positivas da vida real desencadeassem resultados favoráveis em vídeo jogos motivando assim a adoção de bons hábitos. Começa por analisar o estado da arte no que diz respeito a jogos de realidade aumentada e gamification, dois temas que ganharam mais atenção com o crescimento da indústria dos vídeo jogos e graças à maneira como os media e a internet se tornaram uma parte integral da sociedade humana. Também se analisaram os conceitos e tecnologias de web services e comunicação online para verificar como o use de Node.js e Socket.io são as melhores escolhas para o projeto. Estas são 2 tecnologias que têm ganho bastante popularidade e com boa razão, o use de ambos em conjunto fornecem uma excelente solução quando se criam web services que procuram velocidade, eficiência e escalabilidade. Em termos de arquitetura a solução está dividida da seguinte forma: a API em Java usada tanto pelos criadores de aplicações como os fornecedores de informação que inclui as funções necessárias para facilitar o seu trabalho; os scripts de comunicação que usam Node.js e Socket.io, responsáveis por redirecionar os pedidos da API através do use de mensagens do cliente para o servidor que por sua vez as processa e cria a query adequada para enviar à base de dados. Como prova de conceito foi feito uma experiência com um grupo de 10 pessoas para avaliar o impacto quando estas tiverem um pequeno aspeto das suas vidas quotidianas gamificado. O aspeto em questão era minimizar as janelas que não usam ativamente quando utilizam o computador. A experiência também serviu para realçar a facilidade de uso da API do GAP quando se toma o papel de desenvolvedor ou fornecedor de dados. Devido à natureza de estudos comportamentais e o facto do grupo usado ser relativamente pequeno recomenda-se um estudo mais prolongado e detalhado. Abstract The main objective of this dissertation is to develop an API to facilitate the task of integrating real life indicators, such as energy efficiency, into virtual applications like video games, ideally making so that positive actions in real life would trigger favourable outcomes in video games thus enticing the adoption of good habits. It starts by analysing the state of the art in regards to the topics of augmented reality games and gamification, two issues that are gaining more attention as video game industry continues to grow and the media and internet become even more an integral part of human society. Also it revises the concepts and technologies of web services and online communication to evaluate how the usage of Node.js and socket.io are the best choices for the project at hand. Architecture-wise the solution was divided as follows: a java API that would be used by both application developers and data providers which would include the needed functions to ease their jobs; the communication scripts that use Node.js and socket.io, responsible for redirecting the requests from the API through the use of messages from the client side to the server which in turn would process said messages and create the appropriate query to be sent to the database. As a proof of concept an experiment was successfully carried out with a group of 10 people to evaluate the impact having a simple common aspect of their daily lives gamified. Said aspect was minimizing unused widows when using the computer. The experiment also served to highlight the ease of usage of the GAP API when taking the role of both a developer and data provider. Due to the nature of behavioral study and the fact that the group used for the test was rather small a more in-depth and prolonged study is recommended. Acknowledgements First of all I would like to thank two professors in particular. Prof. Rui Rodrigues for being my supervisor but also more than that, for being the voice of reason and always directing me in the right direction. Also thanks to Prof. Augusto Sousa for giving me the best advice I could get when I needed it the most without me realizing it. Secondly I would like to thanks Rúben Costa from SmartWatt for taking me in and teaching and guiding me along the way. Finally I would like to thank above all my mother for being my moral support when things started looking bleakest and always being there supporting me when a moment of respite was needed. Rui Jorge Ferreira de Almeida xvii Abbreviations and Symbols ARG Augmented reality game API Application Programming Interface CPU Central processing unit W3C World Wide Web Consortium WSDL Web Service Definition Language SOAP Simple Object Access Protocol HTTP Hypertext Transfer Protocol XDR eXternal Data Representation XML Extensible Markup Language LAN Local Area Network COM Component Object Model DCOM Distributed Component Object Model RPC Remote Procedure Call TCP Transmission Control Protocol IP Internet Protocol Chapter 1 Introduction Nowadays it is undeniable that more often new ways to reinvent social interaction are being created and designed. This is especially relevant when taken into account the predominance of the internet and the numerous virtual worlds created by videogames. As such there are new ways to make use and incorporate said tendencies to real life itself, making so that the barrier between what is real and virtual gets more and more diluted [1]. With this in mind it is easier to understand that it is in the best interest of many companies to bet on these tendencies to better reach their target audience and captivate more consumers by developing interactive experiences between the real world and a virtual one, while, of course, keep true to their thematic and nature as a company. This is where this dissertation comes in. Proposed by SmartWatt – Energy Services, S.A., its main objective is to create a system that allows for someone’s everyday actions, in terms of energy consumption and saving, to be reflected in a video game he/she might have. It was then decided to take this proposal as a starting point and create a more flexible solution that could cover not only SmartWatt energy consumption indicator but also other types of indicator. As such a system would be developed that would allow collecting relevant data from any source, be it SmartWatt’s systems or any other source, processing this data and then redirecting it to an application to be used by people during their daily life. This would ideally make the user see its positive actions in real life reflected in the application, also in a positive way. 2 1.1 Context As mentioned before this Dissertation was proposed by the SmartWatt Company. It is based in Porto, and its main development area is Energy Services, providing solutions in the areas of renewable energies and energy efficiency, strategic consultancy to producers, users and final consumers of energy, as well as services in the areas of sustainability and carbon management. The main area of development will be energy efficiency. This area concerns the optimization of the use of energy sources in order to use the minimal amount of energy whilst still providing the same energetic value. More often than not, this translates to the way electrical devices are built, that is, how efficient are themselves at consuming energy. However, there are several habits and good practices that consumers can adopt to easily reach such energy efficiency in their everyday, something simple like making sure lights are turned off when necessary or something more serious like installing a photovoltaic panel. Other areas that will be addressed to reach the set goals are web services, responsible for the communication between the different systems involved, like databases and information gathering devices, the servers must be responsible for processing data and redirecting it where necessary. Also the service must be sufficiently flexible to be able to adapt to other end applications and use other real life indicators for example economic data, well-being and health. As mentioned before, in order to be able to create good interactive experiences it is necessary to understand the core concepts and this project is closely related to ARGs (alternate reality games) which make use of the real life world as a base whereupon game or narrative are laid and it is the actions of the people in the real world the move the experience forward. Finally, and once again to be able to create appealing experiences, the concept of gamification is also explored. It is the use of game concepts and design patterns in activities and aspects or real life in order to make them more attractive. 1.2 Motivation and Objectives The main objective was to discern to what extent it would be easy to influence or gamify simple aspects of a person’s daily life and how it would transpire in terms of using and analyzing data from said person. To help such task it would incorporate elements of gamification as well as an API tailored to aid in such situations by providing a developer with an already prepared tool. To attain said objectives, the main tasks set forth were:  Analyze the state of the art in regards in both a conceptual and technological stand point;  Choose the most suitable approach in regards to communication across the web;  Create an API to facilitate said communication; 3  Develop the web service, server and database and respective intercommunication ;  Adapt the service to a real world application 1.3 Dissertation structure In chapter 2 there is a state of the art analysis in regards to augmented reality games and gamification. Also on this chapter there is a technological review on web services, online communication, web sockets and Node.js. In chapter 3 there is the outline of the system architecture, covering components, classes, communication sequence and deployment. In chapter 4 there is more in-depth coverage of the implementation, highlighting the most relevant aspects and examples. Chapter 5 covers the test and deployment of the implementation in a real world scenario along with the respective analysis. Chapter 6 closes with the conclusion and objective satisfaction along with some notes for future work on the project. 4 Chapter 2 State of the art This chapter presents an analysis of the state of the art in regards to the relevant concepts of the project. In terms of emergent concepts it focuses on alternate reality games and gamification and how these have become more present in our society and how these ideas are used in a practical environment. 2.1 Alternate Reality Games According to Jane McGonigal, ARG researcher, an alternate reality game is defined as: “an interactive drama played out online and in real world spaces, taking place over several weeks or months, in which dozens, hundreds, thousands of players come together online, form collaborative social networks, and work together to solve a mystery or problem that would be absolutely impossible to solve alone.” [2] Alternate reality games are games, experiences or many times simply narratives that use the real world as a platform where the events unfold and it is the people involved who, through their actions and motivations, move the experience forward. Most of the time there is a single anonymous individual known as puppet master in charge of managing the game as a whole without ever revealing the main plot to the participants and, more often than not, remaining in complete anonymity. 5 Figure 1: Games topology Due to their nature these experiences are inherently social and easily promote the will to share and interact. This, in turn, makes it so that the game will often become more dynamic than expected. The puppet master, despite is power and control over the game, can hardly predict the human reaction towards a behavior. People gather, organize and discuss about the best way to approach the challenges and this makes it common for the puppet master to need to rethink and even remake his/her plans, scaling the difficulty or scope of the event. For example in the game The Beast [3] (discussed further ahead), the creators had initially designed content for three months but due to the unexpected commitment of the players, in less than one day they had solved most of the challenges. This demonstrates that people’s commitment and dedication easily shape the game even if they do not notice it. However, despite the relationship between players and puppet master being a reactive one, which makes it so the players have a greater sense of possession and belonging over the game, it too can have its negative aspects. On one side it requires the story to be as generic and farreaching as possible in order to be able to make big enough changes whilst still maintaining cohesion. On the other side, it makes it so the content has to be created in near real-time since it is not possible to accurately predict the turnout of the game as well as its proliferation and the players’ commitment. Despite this pressure upon the one responsible for the story, that in itself is the main selling point and probably the main feature of this type of games and experiences. 2.1.1 ARGs in practice The media easily noticed that, when properly executed, an ARG’s virality is an excellent tool for marketing. Probably the most relevant example and most likely the first famous ARG was the marketing campaign around the movie A.I. from Steven Spielberg and Stanley Kubrick from 2001 called The Beast [4]. The creators devised a mystery story whose clues were provided in publicity posters, movie credits and even mass e-mails sent out. The interested people would follow the clues unravelling the past of a movie character. When they searched for said character new websites would show where they could find new information, telephone numbers to contact and even interviews with the movie cast. During three months the community took the initiative, organized itself in online groups where they discussed and shared ideas and even met up on several cities across the United States of America. 6 Another successful example was the game Last Call Poker from 2005, created as a marketing campaign for the video game “Gun” from Activision [2]. Initially it seemed to be a simple website where people could play poker online for free. However, little by little players stated to notice that certain players, they were supposedly playing against, were in fact “ghosts”. Players then started to search the story around a cursed gun by following the clues the ghosts would provide in addition to the clues provided in the real world after they complete certain tasks. Eventually this curiosity created a strong community of players and even strong friendships arose amongst them. Another feature was that the creators would organize every week a game with top five players and the ghosts that the rest of the community could spectate. Here the ghosts were in fact real actors that while playing would subtly lay down more clues that the players would take note of in order to progress further in the collective game. Another potential for ARGs is the alternative proposed by Nicola Whitton, using it for educational purposes and to help students develop an autonomous spirit and mutual aid [5]. Whitton points out the ARG provide several benefits that video games display nowadays: they are collaborative, which is vital to develop cooperation to overcome challenges, they require an active and experimental attitude, and they provide a strong context for several activities. By creating a good narrative, a guideline, it is also creates a strong connection and curiosity towards the events’ unfolding. In addition, since the characters are the players themselves instead of them playing the role of a fictional character, the relevance of the social aspect is even stronger which makes the game appealing to either gender. 2.2 Gamification The video game industry has become a dominating force in the entertainment sector. According to Reuters news agency in 2011 the video games industry reached global revenue of 65 billion dollars which vastly surpassed its closest competitor - the movies industry - which reached only 32.6 billion dollars of revenue in the same year [6]. Figure 2: Video game industry revenue between 2002 and 2012 [6] 7 Of course it is no wonder that many companies and industries turned to videogames to know what were the reasons that lead people to choose this medium and what makes them captivating. All this lead to gamification becoming one of today’s hot topics among software developers. 2.2.1 Definition Gamification began to be defined as: “the use of design elements common to video games in contexts not related to video games” [7]. These elements range from points, rewards (random and effort based), recognition, levels, progression. All this is in the basis of a study conducted by Burrhus Skinner who created the now known “Skinner’s box” through which he intended to expand on Ivan Pavlov’s work on classical conditioning. Pavlov demonstrated that it was possible to condition an animal to react in a certain way when subjected to a stimulus. Skinner on the other side demonstrated that it was possible to attain a type of conditioning not based on external stimuli but instead based on the actions of the subject, thus creating what today is known as operant conditioning. In his experiment, Skinner placed a pigeon inside a box with a button and each time the animal pressed the button it would be granted food. Contrary to Pavlov’s case, here it was the animal’s action that would trigger the reward and conditioning [8]. Another key point is that Skinner also proved that operant conditioning could work on humans. However, he too found out that simply rewarding every time an action was executed was not the best choice and after a certain time the conditioning would lose its effect. Instead if the reward was handed out based on certain criteria such as the number of times the action is performed, elapsed time or even at random, the effect would be much more effective. In addition a very relevant point is that Skinner noted that rewards that satisfy basic necessities, like food, would eventually trigger what is known as diminishing returns, that is, their effect with each successive repetition would be less and less effective after reaching their limit. But, on the other hand, if the rewards were outside the biological context, for example money, social recognition or self-fulfilment, those limits would not be reached as fast, if at all. Many video games nowadays focus on these principles and are even built around them because it has been proven that this conditioning captivates and more often than not players are “hooked” hours on end repeating the same tasks. They know that there is a reward that, as virtual as it may be, still triggers the same satisfaction, the same sense of victory, progression or even social recognition. Two of the most glaring examples are the games “Farmville” and “World of Warcraft”. On the latter all rewards were programmed to be distributed in such a way that the players would be left wanting just a little more. Be it in regards to progressive rewards 8 (level progression), random rewards (“random loot drops”) or social recognition within the community (titles, rare items). All this plus the fact the community reached an impressive number turned Activision Blizzard into one of the most profitable video game companies. In the end, gamification thrives to take these concepts and make other activities outside the video game scope more appealing by providing rewards and recognition in order to trigger the human mind. 2.2.2 Process Skinner’s ideas are only one of the components of gamification, albeit being the most effective and easiest to apply. In reality there are other factors that despite being harder to apply must be taken into account whenever possible [9]. They are:  virality (sharing, social networks, referrals);  reward (scores, leaderboards, rewards);  communication (feedback, self-expression, boasting);  creativity (strategy, self-education, user-created content)  gameplay (altruism, co-operation, competition); Having these aspects in mind and/or implemented is not enough, it is necessary to know how to evaluate its metrics. Most fall back to 4 categories: commitment (frequency of use and time of use), loyalty (repeated visits, referred friends), virality (sharing and social network activity) and monetization. 2.2.3 Examples An example of direct application of gamification is the Nike+ program from Nike [10]. With it their clients could buy accessories that would keep track and monitor their physical activity. After registering a user in the service that data would work as points or experience for that user, just like a video game player, allowing him to raise in level and reach achievements (progress or performance milestones) and also to share his progress with his friends and other participants, enabling thus the spirit of completion and social recognition within a community. Apart from that there were also physical rewards according to the achievements which once again reinforced another level of fulfilment. Another proof that gamification is more than often a crucial point for several companies is the fact that there are now companies exclusively dedicated in providing solutions and consultancy to other companies that seek to adopt gamification in theirs services. Amongst them BunchBall [11], BadgeVille [12] and BigDoor [13] stand out. 15 Figure 7: Node.js processing model [31] In the case of Node.js, despite being several threads working, it differs from the aforementioned alternatives because:  Both the event-loop and worker threads are non-blocking;  While waiting for event the event-loop thread consumes minimal resources;  Since the workers “are carrying out one and only one task at a time asynchronously , the CPU and memory footprint should be lower than a multi-thread scenario, since less threads are required” [22]; 3.2.1 Performance In the example illustrated below, Maciej Zgadzaj, conducted a test to compare the performance of Node.js with an Apache server in PHP [23]. The used code in both cases was as follows: var sys = require('sys'), http = require('http'); http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<p>Hello World</p>'); res.end(); }).listen(8080); Listing 1: Performance test, Node.js code <?php echo '<p>Hello World</p>'; Listing 2: Performance test, Apache code 16 The test includes a total of 100.000 requests, where 1000 of them were concurrent. The results show an advantage for Node.js in what regards the response time. Concurrency Level: 1000 Time taken for tests: 21.162 seconds Complete requests: 100000 Failed requests: 147 (Connect: 0, Receive: 49, Length: 49, Exceptions: 49) Write errors: 0 Total transferred: 8096031 bytes HTML transferred: 1799118 bytes Requests per second: 4725.43 [#/sec] (mean) Time per request: 211.621 [ms] (mean) Time per request: 0.212 [ms] (mean, across all concurrent requests) Transfer rate: 373.61 [Kbytes/sec] received Listing 3: Performance test, Node.js results Concurrency Level: 1000 Time taken for tests: 121.451 seconds Complete requests: 100000 Failed requests: 879 (Connect: 0, Receive: 156, Length: 567, Exceptions: 156) Write errors: 0 Total transferred: 29338635 bytes HTML transferred: 1889607 bytes Requests per second: 823.38 [#/sec] (mean) Time per request: 1214.510 [ms] (mean) Time per request: 1.215 [ms] (mean, across all concurrent requests) Transfer rate: 235.91 [Kbytes/sec] received Listing 4: Performance test, Apache results This serves to highlight Node.js’s scalability when compared with a common approach to creating servers. Summarizing the advantages [24, 25]:  Speed and performance;  Scalability;  JavaScript both on the client and server side;  Handles concurring requests excellently; Some disadvantages:  Since it favors intense communication, Node.js is not the best choice for applications that do not make the most out of it and that require more processing power;  Its relative novelty leads to: o There are not many libraries developed; o For more simples cases of HTML applications the ease in development provided by Rails, CakePHP or Django still has no rival; 17 o The API is still comparatively unstable due to still being in development; 3.3 Web Sockets Websockets is a communication protocol whose main objective is to create a bi-directional connection using a single TCP connection [27]. Usually when bi-directional connections were necessary, such as instant messaging services or video game applications, many problems would arise both in the client and the server side:  The server would need several TCP connections for a single client, one for sending information and one for each message received;  The communication protocol would have high overhead;  The client would need to map the output and input connections to monitor responses; 3.3.1 Structure The protocol has two basic parts: the handshake and the data transfer; The handshake is described and interpreted by the HTTP server as an UPGRADE. This in itself is an advantage because it means that websockets can complement an already existing HTTP system [27]. The client’s handshake looks like the following: GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 The server’s handshake looks like the following: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= 18 Sec-WebSocket-Protocol: chat Figure 8: Websocket model’s basic architecture After both side accept the handshake, the data Exchange can now commence and the important here is that now each side can, independently, send any data, in the form of messages. The usage of websockets excels in two aspects:  Speed  Efficiency In order to illustrate this, Peter Lubbers & Frank Greco from Kaazing Corporation, performed a test to compare the performance between websockets and the traditional polling technique [28]. They created a simple web application that requests data from the stock market in real time. Three cases were outline: A – 1000 clients, 1 message per second; B – 10000 clients, 1 message per second; C – 100000 clients, 1 message per second; In order to more precisely compare, the necessary bits for headers were taken into account, both for polling and websockets. In the first case the headers had a total of 871 bytes taking into account both requests and answers. In the second case, websockets messages had an overhead of only 2 bytes. 19 The image below compares the throughput in the 3 cases and it is clearly visible that polling has significant throughput which in reality is rather unnecessary for it is mostly due to headers, meaning the network would focus most of its efforts on data not directly related to the original message. Figure 9: Polling vs. Web Sockets (throughput) [28] The following image compares the latency between both techniques. Figure 10: Polling vs. Web Sockets (latency) [28] 20 3.3.2 Practical applications To further demonstrate the advantages of websockets technology, it has been used in the creation of a Framework for online browser-based games. These types of games require an active and quite intense communication in order to achieve a fluid experience with low latency. The creators,Chen, B. and Xu, Z. using websockets were able to reach such objective [29]. Another application, create by Lomotey, R. et al, was the usage of websockets in the communication within the field of medicine. With the proliferation of mobile devices these have become more relevant for medical professionals in order to ease information exchange. However, in these fields situations of latency can be problematic especially in wireless communication. The result was that the end latency was reduced significantly when compared with other standard techniques like polling and long-polling [30]. As such the chosen implementation of web sockets was Socket.io, created by Guillermo Rauch, CTO of LearnBoost. Socket.io stands out among other API for two reasons: it can analyze the connection and discern what is the best way to connect without affecting its performance. By default it uses websockets but if need be it can use AJAX long-polling or Adobe flash sockets among others. Also the most important feature, from a developer point of view, is that it provides an API for Node.js that is quite similar to its client-side API and, like Node.js, it too is event-driven [26], making it very easy to integrate with the components developed in Node.js. 21 Chapter 4 Architecture Real life indicators, although rather sensitive data, can be very powerful when applied correctly. These indicators can often demonstrate behaviour patterns and even habits the people have and may not be aware of. By having this information used in gamification it is possible for people to alter said behaviours and of course these changes can be done so for the better. By seeing their actions influencing a game or activity people have the tendency to make use of it, if rewarded they seek to be rewarded again. In a competitive environment they will often seek to win and if the path to victory involves improving themselves they will do so even if for them these changes occur without them realizing it. Additionally, the data interpretation can be done in numerous ways, i.e. the way the raw data gathered from their activities is processed. Different developers may seek to weight the data differently and those who collect the data itself my wish for it to be converted in a specific way. Therefore, it is also useful to have a mechanism to integrate these conversion formulas readily available and distributable among the developers. With all this in mind it is easy to visualize the need to have all this information, which is flowing from different people, gathered and processed. However, having to do so for every instance and application created can be counter-productive; ideally there would be a tool that would handle most of the back-end communication leaving the developers to worry on how to put the data to good use. The GAP system was then devised to be a system that would include a web service component responsible for handling the communication between the involved components, in this case, a server in Node.js capable of handling messages from the different users and communicate with the database to provide and retrieve information. Said database would store the data regarding the real life indicators that is collected from the end-users. The users would come in closest to the system through an API that would provide the functionalities necessary to 22 make use of the server and database communication. This API would include functions to ease the job of either a developer who wants to use real life indicators in his applications or a provider who wants to use API to present the system with the data on said indicators. 4.1 Structure The program is mainly divided in 2 parts: the client-side java API that is handled by the developers and providers and the communication scripts that are responsible for the interaction between client server and database. Figure 11: Component diagram The API is then further divided among the developers’ and providers’ functionalities. Such distinction is made to separate roles of a developer that is using the API to incorporate real life indicators and feedback into its project and the provider who simply wants to supply such values for a database that is later accessed by the developer. 23 Figure 12: Class diagram On the communication side there are 2 different scripts that run node.js. One is used on the client side and responsible for handling the calls from the API’s functions and relay them to the server. The second is the script responsible for the server. It is run by the provider full time and it handles the messages in real time from the client script. It must also interprate the messages, and invoke the appropriate SQL query to be sent to the database and relay the answer back to the client. 4.2 User types It is important to elaborate on the types of users that may interact with the API and system on different levels. Firstly there is the provider. It refers to users who, having chosen to use the GAP System to keep tract of indicators, are able to provide said indicators on a constant accurate basis. That is, they have a way to feed into the database raw data of its own users who chose to do so. For example, a company who can provide the database with entries on customers’ energy spending and saving values. Ideally they will seek to use the API’s functions specific to them that allow to insert, delete and check entries in the database. Secondly we have 24 the developers. These are the users whose intent is to use the GAP API to transform and incorporate that raw data from the providers and use it on their applications. They have at their disposal the tool to fetch and manipulate the values and create their own system of points and milestones, thus, allowing them to inject a handful of elements form gamification to their application. They may or may not be providers too. Finally we have the end users. They are the customers whose indicators are being tracked and who chose to acquire the applications created by the developers. 4.3 Standard communication sequence All the communication follows the same pattern illustrated in the sequence diagram below. On the client side API, whenever a function is used it invokes the client-side node.js script with arguments depending on the function. The script will then establish a socket connection with the server-side script that is running. After connecting it will send a specific message based on the arguments passed when the script is invoked. The server, which is constantly listening for messages, will filter the messages and, when prompted, will establish yet another connection this time though with the database. This connection is used to send a SQL query based on the message received from the client-side script. After the database’s reply is received the server messages back the client with said response. The API finally fetches the output of the client-side script now with the answer from the database query. 31 public double get_sum_timestp(String user, String init,String end) { double value = 0; String command = "node socketclient datagetsumtimestp " + user +" "+ this.type +" "+ init + " "+ end; ArrayList<String> res = Scripts.scriptcaller(command); /*debug print for(int i = 0; i<res.size(); i++){ System.out.println(res.get(i).toString()); }*/ String retstring = Scripts.get_result_by_field("SUM", res); if(retstring != null){ value = Double.parseDouble(retstring); }else value = -1.0; return value; } Listings 3: Data’s get_sum_timestp method As before, if the operation results in error the number -1 is returned instead of the positive double with the sum. The last function, get_total, works similarly to the previous one. However, instead of returning the sum of values on a time frame, it returns the sum of all values. This function could be replicated by using the above one by giving a very early initial time stamp, but since it could be something that was repeatedly used it was created in order to ease the developers work. The main difference is once again the invoked command. String command = "node socketclient datagettotal " + user + " " + this.type; Listings 4: Example of invoked command (Data’s get_total) 5.1.2.2 Points class This class is responsible for handling the information flow of point values from and to the database. It is intended to be used by the developer after he/she is done converting the data values into the appropriate point equivalent of choice. It follows a similar layout to the data class. Firstly the get_last_insert function allows retrieving the latest point entry in the database. It still invokes the same script however the command itself varies. The processing is done by looking for the “points” tag in the results. 32 public double get_last_insert(String user){ double value = 0; String command = "node socketclient pointsgetlastinsert " + user; ArrayList<String> res = Scripts.scriptcaller(command); String retstring = Scripts.get_result_by_field("points", res); if(retstring != null){ value = Double.parseDouble(retstring); }else value = -1.0; return value; } Listings 5: Points’ get_last_insert method The functions get_sum_timestp and get_total once again allow for the retrieval of sums of points based on either a time frame given or simply the total of points input, respectively. When defining the time frame the same system is used as before where both initial and final time stamps follow the format: YYYY-mm-dd hh:mm:ss. Being so that the second part is optional. Also once again the results processing is done so by aiming to extract the value in the “SUM” tag. public double get_sum_timestp(String user, String init,String end) { double value = 0; String command = "node socketclient pointsgetsumtimestp " + user + " "+ init + " "+ end; ArrayList<String> res = Scripts.scriptcaller(command); String retstring = Scripts.get_result_by_field("SUM", res); if(retstring != null){ value = Double.parseDouble(retstring); }else value = -1.0; return value; } Listings 6: Points’ get_sum_timstp method 33 Since it is the developers’ responsibility to update the points database as he/she sees fit, the class includes a insert_points function which of course allows the developer to populate the database giving only the user’s name/id and the value to be input. 5.1.2.3 User class This class is responsible for handling user control and data. From their creation and validation to their stats updating. The class includes a basic constructor which takes the username and password as arguments and instantiates its points variable which will allow for points manipulation through the aforementioned Points class. public User(String username, String password){ ID = username; upass = password; points = new Points(); } Listings 7: Example of a user constructor Note that this will obviously not create a user in the database, only locally. In order to create user in the database the create function must be used. This function will take the given username and password and populate the database with the pair. It is also important to notice that when doing so points will not be inserted. In order to do so the already available function insert_points in the points class would have to be used. Therefore to facilitate such task the User class includes the inputpoints functions which, upon being give a value, will invoke the insert_points function with said value and the username which is being called upon. public void inputpoints(double val){ this.points.insert_points(this.ID, val); } Listings 8: User’s inputpoints making use of already created functions Other notable functions include remove which removes all entries of a given user from the database and the check_if_exist which verifies whether or not a tuple of username plus password is already present in the database. It does so by invoking a command string and checking the results looking for the tags “userID” and “pass”. Depending on the combination of both results 3 outcomes are possible: if both the userID and pass are not null the answer is true, if both are null false the answer is false and the error message “no such pair registered” is issued, if neither of these cases is verified, i.e. when either userID or pass are not null while the other is, the answer is also false but the error message is now “user registration incomplete”. public boolean check_if_exist(String username, String password){ boolean ans = false; 34 String command = "node socketclient usercheckifexist " + username + " "+password; ArrayList<String> res = Scripts.scriptcaller(command); /* for(int i = 0; i<res.size(); i++){ System.out.println(res.get(i).toString()); }*/ String user = Scripts.get_result_by_field("userID", res); String pass = Scripts.get_result_by_field("pass", res); if(user != null && pass != null ) { ans = true; } else if(user == null && pass == null ) { System.err.println("No such pair registered"); ans = false; } else { System.err.println("user registration incomplete"); ans = false; } return ans; } Listings 9: User’s check_if_exist method 5.1.2.4 Milestone class The main role of this class is to provide the developer with an already built capability to create milestones or achievements for their games/application thus allowing to create the experience of progress and reward that is the basis of gamification and its operant conditioning. On its core a milestone is defined by a target value it needs to reach, a start value and its current progress. Since the points are all tracked numerically all these values are also numerical. There are 2 basic constructors: one allows for the setting of the initial value and the target value while making sure that consistency is maintained by checking whether the target is greater than the start value; the other one allows to additionally set a start and end date in case is necessary to establish a time frame for the milestone’s completion or time the reward distribution according to a plan. Milestone(double startval, double targetval){ if(startval > targetval) 35 System.err.println("Start value greater than target value"); this.start_value = startval; this.target = targetval; } Listings 10: Basic Milestone constructor Other relevant functions include checkprogress which return a double with the percentage of completion of the milestone, setprogress to update the current value of the milestone and iscomplete for a quick way to check if the milestone has been attained public double checkprogress(){ double totaldiff = this.target-this.start_value; double progress = (this.current_value/totaldiff)*100; if(this.current_value<this.target){ System.out.printf("Milestone is %d% done",progress); return progress; } else{ System.out.println("Milestone complete"); return progress; } } Listings 11: Milestone’s checkprogress method Ideally the developer will use these feature to create a progress system to draw people to commit to the experience he tailored. He/she can then implement a reward system that can be associated with the milestone completion making it so the end user can trigger the acquisition of said rewards by progressing in the usage of the game/application 5.1.2.5 Converter class As stated before, the raw data values can and should be converted to points by the developers since it may be that different types of values can have different weights and even different developers may chose to have distinct emphasis on their points. In order to do so they may have a formula of their own to convert said raw data or they adopt other formulas made available. Thus it is necessary a way to keep track of these mathematical formulas, share and use them. The converter class uses the exp4j library, developed by Frank Asseg. Its main task is to evaluate mathematical expressions and functions in the real domain and uses the Dijkstra's Shunting Yard Algorithm to do so. It allows the developers to create their expressions using regular notation, for example 3*x + sin (y), and leave it to the API to evaluate and calculate the results when of course given the proper values. In addition the developer may store said 36 expression in the aforementioned converter database for future use or allow other developers to use it too. In turn, he/she can choose to use already implemented expressions in a developing application. The following functions are included:  createexpression(String id, String exp, String desc, String varlist), invokes the command to insert a new entry in the database with the given arguments. The id may be a unique name chosen to differentiate expressions. exp refers to the expression itself and for parsing purpose should be surrounded by the character ‘$’ for example, $x+2*y$. desc is a short description of the expressions purpose. Finally varlist is contains a list of comma separated variables used in the expression ($x,y$). This additional list was chosen in order to more quickly assess the number of variables and check whether they match the ones passed as arguments in other functions.  checkifexist(String id), check if a given id of an expression is already present in the database or not;  removeexpression(String id), remove and existing expression from the database, given an id;  buildlist(), this provides an easy way for the developer to access the list of expressions already present in the database. It does so by first requesting the server a list of expression id’s plus their description. Then it processes the message and stores the results in a Map of two strings. The first one will contain the expression id and the second will contain the description. public Map<String,String> buildlist(){ String command = "node socketclient convertershowlist"; ArrayList<String> res = Scripts.scriptcaller(command); //We map each expression "id" with its respective "description Map <String, String> pairs = new HashMap<String, String>(); for(int i =0; i<res.size(); i++){ if(res.get(i).contains(" id: ")) { String id = res.get(i).split("'")[1]; String desc = res.get(i).split("'")[3]; pairs.put(id, desc); } } return pairs; } Listings 12: Converter’s buildlist method  calculate(String id, double… vars),the core function that takes an expression and a number of variables returns the result. The first step in this process is to retrieve the expression itself by communicating with the server. Then the answer is 37 processed and the expression and list of variables are extracted. After it verifies if the number of variables passed as argument (which in itself is varies in size) matches the number of variables present in the expression by matching the respective list of variables. Finally in order to use one of the expression builders from exp4j it maps the variables with the values passed as arguments in Map of string and double. public double calculate(String id, double... vars) throws UnknownFunctionException, UnparsableExpressionException{ String command = "node socketclient convertergetexp " + id; ArrayList<String> res = Scripts.scriptcaller(command); System.out.println(res); String exp = Scripts.newget_result_by_field("expression", res); String varlist = Scripts.newget_result_by_field("varlist", res); String[] vararray = varlist.split(","); int n_vars = vars.length; Map<String,Double>pairs = new HashMap<String,Double>(); if(n_vars != vararray.length) { System.err.println("Number of vars mismatch"); } else { for(int i = 0; i<n_vars; i++) pairs.put(vararray[i], vars[i]); } System.out.println(pairs.toString()); Calculable calc = new ExpressionBuilder(exp).withVariables(pairs).build(); double result=calc.calculate(); System.out.println(result); return result; } Listings 13: Converter’s calculate method 5.1.3 Utility classes The scripts class is a collection of function that aid in the API-script communication as well as the processing of the results from the response from the server. Scriptcaller(String command) which is used in several of the aforementioned functions, is used to take in the 38 command string and execute said command using Java’s ability to interface with the environment in which the application is running using the getRuntime() function. It used two string arrays to store the captured output of the two buffered readers, one for the actual output and one for error output if necessary. public static ArrayList<String> scriptcaller(String command){ ArrayList<String> out = new ArrayList<String>(); ArrayList<String> errors = new ArrayList<String>(); BufferedReader bri, bre; try { String line; Process p = Runtime.getRuntime().exec(command); bri = new BufferedReader (new InputStreamReader(p.getInputStream())); bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { out.add(line); } bri.close(); while ((line = bre.readLine()) != null) { errors.add(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } return out; } Listings 14: Script’s Scriptcaller method Get_result_by_field(String field, ArrayList<String> results) is often used to parse the results array obtained by the scriptcaller function and extract only the information relevant to the field chosen. Finally newget_result_by_field(String field, ArrayList<String> results) servers 39 the same purpose, however, it is more specific and used towards the expression parsing portion of the converters class. 5.2 Client-side script As mentioned before, the communication over the web itself is handled by the Node.js components of the application. Whenever a function that requires communication is used a script is invoked that will establish said connection through the use of websockets, namely the socket.io library. When paired with node.js it allows for very fast communication on a commonly used language that may be present both on the client and server side. The first step after creating the socket is parsing the command invoked in order to know which message must be sent to the server-side script that is running on the other end. After that it is a matter is establishing and maintaining listeners for different types of message and sending the appropriate message. A listener example would be the following: the script as a variable in which it stores the unique id it is given by the server. The server tells the client this information on a “greetings” type message. That means that on the client-side there is a listener waiting for a message with that tag that will saved wtih the id accompanying the message. socket.on('greetings', function (event) { myid = event.id; console.log('Personal identifier: '+myid); }); Listings 15: Example of a listener on client side Since, unlike the server, the client socket has a short uptime, after receiving and handling the “greetings” message from the server it will resort to choosing one of the several options of messages available. Once again this will depend on the type of parameter passed when the script was invoked. For example, using one of the above mentioned functions, assume the client API calls the function check_if_exist(string username, String password) from the User class. This would mean that the invoked command within the function would have the following format: String command = “node socketclient usercheckifexist username password” When parsed by the client script it would note that “usercheckifexist is the message that must be sent to the server and that there is additional data that must accompany said message, in this case “username password”. The message type is stored in the variable “type” and a switchcase statement upon the variable will mean the when the type is “usercheckifexist” the client will compose a message whose type is “usercheckifexist” and that has additional data accompanying it which had previously been stored in the databody variable. 40 Switch(type) { case 'usercheckifexist': console.log('Params passed in <' + type + '>: ' + databody.toString()); socket.emit('usercheckifexist', {data: databody}); break; Listings 16: Example of instance of the switch-case statement for message type The server would then answer with a message labelled “result”. This is the result that the client will process in order to be captured by the API’s scriptcaller function. Upon listening to the result message the client-side scripts job is complete and it sends an “exit” message with its personal id to server letting it know it wants to disconnect. The server responds with “goodbye” which triggers the client socket’s disconnection and process end. socket.on('goodbye', function (event) { // server emitted a message console.log('Good to leave? ',event); var out = setTimeout(function(){socket.disconnect();},45); var exit = setTimeout(function(){process.exit(0);},50); }); Listings 17: Client script closing listener 5.3 Server-side script Just like the client script, on the server side some initial setup and preparation is required before starting proper communication. First of all it requires both the HTTP module already present within node.js and the socket.io module, for obvious reasons. Next since the server will handle the extra step of communicating with the database it must require the respective module and setup the connection. The example below shows a connection to a MySQL database: var mysql = require('mysql'); var connection = mysql.createConnection({ host : examplehost.net', database : 'example', user : 'userexample', 47 The script here states that in the event of clicking the right mouse button (RButton) or left mouse button (LButton) it will increase the KeyCount variable by one. The same is then done for the other keys that are to be monitored. The second one on the other hand is only run periodically and will look into the Windows’ Task Manager and register which windows are open and their status. It will extract the windows class followed by -1 if it is minimized, 1 if it is maximized and 0 if it is simply open but neither minimized nor maximized. The output of each script is saved into a text file. In here the main key is using the function WinGet which allows retrieving several properties about the one or more windows. For example:  WinGet, all, list This allows retrieving all the details of all currently running windows and stores it in the all variable in the form of a list.  WinGetClass , WClass, %”ahk_id” all%A_Index% This allows getting the window class of the process with the identifier (ahk_id ) present in the current element of the list.  WinGet, status, MinMax, %”ahk_id” all%A_Index% This allows retrieving the status of a process’ window and save it in the status variable. MinMax is simply an optional parameter used when invoking the function in order to retrieve only the window status. The main Java class is responsible for handling the core of the application. It creates and displays the menus for the user as well as the listeners for the events within the menus. Said events include logging in with the given credentials, registering oneself in the system for the first time, remembering the credentials for future use so that the user does not need to input its username and password every time he runs the application and redirecting users to the leader board website. Figure 16: Application menus While the main class handles mostly the interface, data processing and parsing is delegated to other classes that make direct use of the GAP functionalities. A login class handles the process of validation and/or insertion of credentials in the database using the functions check_if_exist(username,password) and create(user) from GAP’s User class. The creation of a new user is, of course, only possible if he is not already present in 48 the database. Additionally upon logging in it is also checked if the user chose to save its credentials and if true the application will create a text file in the application folder with the user’s credentials that is read the next time the user runs the application. The data collection is done in a predefined interval of time defined in seconds by the variable TIMEVAR. This variable is used to schedule tasks to run in an instance of Java’s TIMER class. These tasks are classes that extend Timerschedule which when properly created with a run() function will execute said function according to the parameters used when the class is instantiated. For example the class Clickparse, which is responsible for parsing the text file containing the output of the counter script, is created the following way: Clickparse parse = new Clickparse(user); Timer.schedule(parse, 20, miltime); Listing 22: Using Timer to schedule a task This means the task will be scheduled to run on an interval defined by miltime which in turn is the variable TIMERVAR in milliseconds, and every time it will use the provider class from GAP to send the raw data (clicks) to the database: Prov.insert( username, “clicks”, Integer.toString(clicks)); Listing 23: Using GAP to provide data Another task used with the Timer is Activityparse which is responsible for invoking the newget script, parse its output and for each window detected send the information to the database. The final task is pointschedule, responsible for calculating the points based on the collected data and send them to the database. The points are calculated according to the following formula: Points = (v1*(m/M)) * (v2*P) * (v3*Prod) Where: -V1,v2,v3: represent the weight of each component, by default 1.0; -m: is the number of minimized windows; -M: is number of non-minimized windows; -P: is the value of point awarded per minimized window; -Prod: productivity multiplier which can take the values of 0.5, 1 or 1.5 depending on the registered clicks. If in 30 seconds there are more than 25 clicks Prod takes the value of 1.5, if there are less than 5 clicks it takes the value of 0.5, any other case it takes the value of 1. 49 6.4 Results There were 10 people registered of which only 6 provided data. Of these, 4 were active contributing with frequent data while the other 2 were recorded only for 1 day. From the 4 active people, 3 chose to only use the application during work hours. Note: Henceforth, in order to respect the people involved and their privacy all usernames used will be replaced with placeholder names. Figure 17: Points gained per day Figure 18: Points gained per day (without user 1) As it can be seen from figures 17 and 18 there seems to be a great disparity between one of the users and the rest. Also, contrary to what was previously expected, the participants were fairly irregular on the usage i.e. they did not activate the application every day, in fact the most active users, user 2 and 3 used the application only during 6 and 7 days respectively. When questioned after the experiment, most people stated that in some days they forgot to use or simply it was not possible during the day. This is an interesting fact because 3 of the irregular 50 participants who answered thus also stated before the experiment they would rather choose when to activate the application rather than it run automatically, namely users 3, 4 and 5. This lead to believe that a better approach would have been to have the application run automatically from the beginning despite the people’s concerns and explain to them more thoroughly about how there were no risks. Incidentally, two of the users, user 4 and 5 stated that despite using the application exclusively at work during their job (both were teachers at an English school) the usage of the computer was sporadic, which may have lead to the regular days without using the application. On the other hand, users 2 and 3 (who were a student and a secretary) show a slightly more consistent usage when compared to the previous two. Possibly due to the fact they could more easily stay in front of the computer for longer periods of time. Note that on figures 18 and 19 there is an evident pattern in the behavior of high peak in the beginning of their experiment followed by a decline that leads to a rise. This is visible in users 2, 3 and 4 as we can see in figure 19 below. Figure 19: Points gained per day (users 2, 3, 4) 6.5 Comparision with opinion The most important question in the questionnaire was how often people believed they minimized their windows. This was asked in order to compare their perceived notion to what the system registered to evaluate if there was in fact an effect having them play along the experiment. The options for this question are correlated with the approximate percentage of minimized windows in the table below. 51 Option Percentage of minimized windows Never 0%-25% Sometimes 25%-50% Frequently 50%-75% Always 75%-100% Of the 6 people who contribute with data, their answers were the following: User Answer 1 Sometimes 2 Sometimes 3 Sometimes 4 Sometimes 5 Never 6 Always Table 2: Answers to how often participants minimize windows on computer First of all it is interesting to note that user 5 who contribute for only 1 day answered “never”. User 5 actually made the effort to earn points by minimizing windows by at least minimizing the application’s window. On the other hand user 6 who said to always minimize its windows stayed true to itself by showing an average of 83% windows minimized, however this was only recorded for 1 day of work. The rest of the participants demonstrated a small evolution along the days they were active. All four started with less than 50 % windows minimized, putting them in conformity with their answers. However on the later days, and on par with what the points eluded to, this average started to increase ever so slightly. In fact user 2 who started the experiment with only 16% windows minimized (254/1651) by the 3rd day had this metric increased to 20% (1654/7906). A similar increased was noted on user 4 despite being active for only four days going from an average of 21% (25/121) to 28% (650/2303). 6.6 The case of user 1 The case for user 1 is a bit different because in the end it was clear that said user could be profiled as a “power gamer” as it is colloquially known in the gaming community, that is, someone that will try his hardest to have the best chances of winning by utilizing every possible aspect to its full potential. For example, what this user did was simply guarantee that he could 52 win the first place prize by exploiting the experiments mechanics. To that end during the days he was active he would open several windows and just leave them minimized and only have 1 window in use during most of the work day. This would allow him to earn a lot of points while still abiding by the rules of the experiment. The database data gathered supported this by showing that, for example, during his most active day he had on average 37% more minimized windows and also he was the user who managed to have the application open the longest per day. When questioned after the experiment, user 1 stated that by his 3rd day he felt he had secured the first place hence the decline in usage. He also said that by then should anyone else new show up for the experiment he doubted they could earn as much in what little time was left of the experiment. Figure 20: Points per day (user 1) It is important to note that despite its massive point gain, user 1 did not have a much higher average of minimized windows when compared to its opponents. As stated above on its peak he had an average of 37% windows minimized. This matches his answer in the questionnaire (“sometimes”). The biggest impact in its victory was the fact that he managed to have the application open for longer periods of time. 6.7 Final remarks Bearing in mind the restrictions of time and poor activity from the participants it is safe to say that the main objectives were attained. With a simple experiment it was rather easy to gamifiy an often overlooked aspect from a person’s daily work. By instructing the experiment’s participants to basically compete among each other it was possible to see their habits slowling change even on a small time frame. In general people developed the tendency to acquire points more efficiently despite them not using the experiment application full time. It is impossible to 53 properly quantify how significant was the impact of having a prize for the winners but there was conclusive evidence that people did change their behavior patterns. At the very least one participant did all he could by maxing out the points he could gather each day exploiting the experiments rules to its fullest. This proves that even with simple incentives people can change their behavior patterns, even if they do not perceive said changes on a greater scale, placing them in indirect competition with others can be a trigger for such. This of course varies from person to person and not everyone will cling to the thrill of competition and reward the same way. It was no surprise that the youngest participants were more willing to dedicate time to activave the application more often. On the other side the oldest participants often would not even active the application either on their own accord or because they were not as invested. It is worthy noting that most people chose to use the application only during work hours and some even raised concernes if their information was compromised which shows that when dealing with sensitive subjects and information it is best to always demonstrate transparency, putting people at ease showing them which information will be gathered and how it will be used. 54 Chapter 7 Conclusion and future work Harnessing the concepts of gamification and alternate reality games is becoming more relevant with the rise in the video games industry; using principles and aspect of video games in real world scenarios is a common practice all around even if sometimes very subtle. Developers seek to create applications that ever more compelling and make use of these ideas, driving people to create communities and being able increase customer loyalty. In order to do this, many technologies have risen to help the process; they ease the flow of data necessary between all the involved parties, favoring rapid and scalable data messages instead of more complex and protocols. As such two technologies that fit such profile were Node.js and socket.io which when used together allows to easily develop server and web service solutions. With this in mind the project successfully developed a solution to ease the process for developers. The application included a Java API that both developers and data providers could use to start the data flow. This data, which originated from the end users real life actions, could then be processed and fed back to the system allowing to use it to reward users based on their habits. The communication with a server and database, done through scripting in Node.js, would not have to concern the developer at all freeing him to focus on other points of his application. In the end, as proof of concept, a real world experiment was conducted in order to create an application that made use of the GAP API. It served to evaluate the ease of usage of the API and how the people would actually react upon having a small aspect of their daily life’s gamified . Something as simple as monitoring the number of minimized windows and rewarding people for doing it. Even with a small group it was possible to identify different patterns of behavior among the participants. How frequent they were willing to use the application and how intensively showed how much they wanted to win the prize in the end of the experiment. In fact most participants slightly improve their performance along the way while some cases tried to 55 maximize their results to reach prize as soon as possible, thus demonstrating that a small incentive on daily lives can easily influence one’s habits and if this can be done to something as simple as minimizing unused windows, the same can be done to other, more alluring, metrics to positively influence a person’s life. In terms of ease of use of the GAP API, as stated before during the development of the application, the use and integration of the API functions was rather straightforward. Often, no more than a line of code was needed, and all the communication was handled by the API. From a developer standpoint this translates into saved time. Additionally the API was able to adapt to a different environment as initially it was developed with energy data in mind but the experiment was developed using different real-life indicators. 7.1 Future work Unfortunately due to time constrains it was not possible to carry out a fully fledged behavioural study with a bigger population, ideally it would need to be done over at least two month depending of course if the same real life indicators are used or not, more convoluted options might required long periods of time. From a development standpoint the main caveat would be the integration of the communication solution with other platforms that might not use Java. For this project Java was chosen for is familiarity but the idea can and should be able to cover other alternatives. Additionally it is necessary to cover the security aspect during the communication in order to prevent code injection, should the application be put to use in the future. 56 References [1] K. Tuite, N. Snavely, D.-Y. Hsiao, A. M. Smith, and Z. Popovic, "Reconstructing the world in 3D: Bringing games with a purpose outdoors," in 5th International Conference on the Foundations of Digital Games, FDG 2010, June 19, 2010 - June 21, 2010, Monterey, CA, United states, 2010, pp. 232-239. [2] J. Kim, E. Lee, T. Thomas, and C. Dombrowski, Storytelling in new media: The case of alternate reality games, 2001–2009, 2009. [3] S. Stewart. Beyond the Fourth Wall. Available: http://www.seanstewart.org/interactive/args/ [4] J. Y. Kim, J. P. Allen, and E. Lee, "Alternate reality gaming," Communications of the ACM, vol. 51, pp. 36-42, 2008. [5] N. Whitton, "Alternate Reality Games for Developing Student Autonomy and Peer Learning," 2008. [6] M. Nayak. (2013, July 5, 2013). FACTBOX - A look at the $66 billion video-games industry. Available: http://in.reuters.com/article/2013/06/10/gameshow-e- idINDEE9590DW20130610 [7] S. Deterding, D. Dixon, R. Khaled, and L. Nacke, "From game design elements to gamefulness: Defining "gamification"," in 15th International Academic MindTrek Conference: Envisioning Future Media Environments, MindTrek 2011, September 28, 2011 - September 30, 2011, Tampere, Finland, 2011, pp. 9-15. [8] J. F. Portnow, Daniel, "Extra Credits: The Skinner Box ", ed. Penny-Arcade.com: Extra Credits, 2008. [9] Bunchball, "Gamification 101: An Introduction to the Use of Game Dynamics to Influence Behavior," ed: Bunchball, Inc, 2010. [10] (2012, July 11). Nike+. Available: http://nikeplus.nike.com/plus/ [11] R. Pahari. (2005, July 10). Bunchball. Available: http://www.bunchball.com/ [12] K. Comée and K. Duggan. (2010, July 10). Badgeville. Available: http://badgeville.com/ [13] K. Smith and J. Malek. (2009, July 10). Bigdoor. Available: http://www.bigdoor.com/ [14] D. Booth, H. Haas, and F. McCabe, "Web Services Architecture," ed. World Wide Web Consortium: W3C Web Services Architecture Working Group, 2004. [15] G. Glass. (2002, July 6). The Evolution of Web Services. Available: http://www.informit.com/articles/article.aspx?p=27295 [16] C. Finkelstein. (2003, July 6). Web Services Evolution. Available: http://www.tdan.com/view-articles/5085 using the scriptcaller method from the Script class. The results are stored in res. Results are then parsed in order to retrieve the value itself. Parameters: user - Username for the user being searched. Returns: Returns a double with the sum of all data values. getcount public double getcount(java.lang.String user) getcounttimestp public double getcounttimestp(java.lang.String user, java.lang.String init, java.lang.String end) dev Class Points java.lang.Object dev.Points public class Points extends java.lang.Object Author: Rui Almeida Class responsible for retrieving and inserting the information about the points values in the database. Constructor Summary Constructor and Description Points() Method Summary Modifier and Type Method and Description double get_last_insert(java.lang.String user) Method responsible for getting the last points entry into the database for the user passed. double get_sum_timestp(java.lang.String user, java.lang.String init, java.lang.String end) Method responsible for getting the sum of points values inserted in a given time frame. double get_total(java.lang.String user) This method retrieves the total sum of all points values input for a given user. void insert_points(java.lang.String user, double value) Method that inserts a points entry to the database for a given user. void remove_timestp(java.lang.String user, java.lang.String init, java.lang.String end) Method that removes entries on the points database based on the given username and a time frame defined by the initial and end string dates. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructors Methods Constructor Detail Points public Points() Method Detail get_last_insert public double get_last_insert(java.lang.String user) Method responsible for getting the last points entry into the database for the user passed. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. Results are then parsed in order to retrieve the value itself. Parameters: user - Username for the user being searched. Returns: A double with the value of points last inserted. get_sum_timestp public double get_sum_timestp(java.lang.String user, java.lang.String init, java.lang.String end) Method responsible for getting the sum of points values inserted in a given time frame. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. Results are then parsed in order to retrieve the value itself. Parameters: user - Username for the user being searched. init - Initial timestamp. Uses the following format: yyyy-mm-dd hh:mm:ss. Second part is not mandatory. end - Final timestamp. Uses the following format: yyyy-mm-dd hh:mm:ss. Second part is not mandatory. Returns: Returns a double with the sum of the points values within the time frame given by the 2 timestamps. get_total public double get_total(java.lang.String user) This method retrieves the total sum of all points values input for a given user. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. Results are then parsed in order to retrieve the value itself. Parameters: user - Username for the user being searched. Returns: Returns a double with the sum of all points values. insert_points public void insert_points(java.lang.String user, double value) Method that inserts a points entry to the database for a given user. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. Parameters: user - Username whose points entry belong to. value - Value of points being inserted. remove_timestp public void remove_timestp(java.lang.String user, java.lang.String init, java.lang.String end) Method that removes entries on the points database based on the given username and a time frame defined by the initial and end string dates. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. Parameters: user - Username for the user having their entries deleted. init - Initial timestamp. Uses the following format: yyyy-mm-dd hh:mm:ss. Second part is not mandatory. end - Final timestamp. Uses the following format: yyyy-mm-dd hh:mm:ss. Second part is not mandatory. dev Class User java.lang.Object dev.User public class User extends java.lang.Object Author: Rui Almeida Class responsible for creating and handling user information locally. Constructor Summary Constructor and Description User(java.lang.String username, java.lang.String password) Basic constructor for creating a user locally based on a given username and password. Method Summary Modifier and Type Method and Description boolean check_if_exist(java.lang.String username, java.lang.String password) Checks whether the tuple of username plus password is already present in the database. void create(User user) High danger method that creates an already instantiated user, in the database. java.lang.String getID() java.lang.String getpass() Points getPoints() void inputpoints(double val) Method that inserts an entry into the points database for the user being called upon. void remove() Method for removing a user and all its entries form the database WARNING> all points entries will be removed from the database in this process. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructors Methods Constructor Detail User public User(java.lang.String username, java.lang.String password) Basic constructor for creating a user locally based on a given username and password. Its points will be an instance of the Points class which in turn allows to fetch said points from the database. Parameters: username - String of the name of the user being created password - String of the password for the user being created. Method Detail check_if_exist public boolean check_if_exist(java.lang.String username, java.lang.String password) Checks whether the tuple of username plus password is already present in the database. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. The results are then parsed to check for the tags userID and pass. Then 3 cases are considered, if both are not null then the pair exists, if both are null the pair does not exist, if either is null while the other is not the registration is not complete. On the first case the answer is true, on the last it is false. Parameters: username - The string with name of the user being searched password - String with the password of the user being searched Returns: boolean. True if both username and pass are returned in the query result (not null), false if not. create public void create(User user) High danger method that creates an already instantiated user, in the database. Parameters: user - An already instantiated user. Its ID and upass will be used to create the base entry in the database. It starts with NULL points remove public void remove() Method for removing a user and all its entries form the database WARNING> all points entries will be removed from the database in this process. The method creates a string with command to be called using the scripcaller method from the Script class. The results are stored in res. inputpoints public void inputpoints(double val) Method that inserts an entry into the points database for the user being called upon. It uses the insert points mehtod from the Points class. Parameters: val - Double value of the new points entry being input, regarding the user. getID public java.lang.String getID() Returns: Returns the String of the user ID getpass public java.lang.String getpass() Returns: Return the string of the user password getPoints public Points getPoints() Returns: Return the class points associated with user. dev Class Milestone java.lang.Object dev.Milestone public class Milestone extends java.lang.Object Author: Rui Almeida Class responsible for creating and keeping track of milestones based on points progression. Method Summary Modifier and Type Method and Description double checkprogress() Method that checks the percentage of completion of a milestone. boolean iscomplete() Method that checks if the milestone has been completed by checking whether the current value is equal or greater than the target value. void setprogress(double value) Method that updates the current value of the milestone thus updating its progress. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Method Detail checkprogress public double checkprogress() Method that checks the percentage of completion of a milestone. Checks the difference between the milestone`s target and initial values and divides the current value by said difference. Returns: Return a double with the percentage of the completion. setprogress Methods public void setprogress(double value) Method that updates the current value of the milestone thus updating its progress. Parameters: value - Double value to update the milestone`s current value. iscomplete public boolean iscomplete() Method that checks if the milestone has been completed by checking whether the current value is equal or greater than the target value. Returns: Boolean. True if milestone is complete, false if not. convert Class Converter java.lang.Object convert.Converter public class Converter extends java.lang.Object Author: Rui Almeida Constructor Summary Constructor and Description Converter() Basic constructor Method Summary Modifier and Type Method and Description java.util.Map<java.lang.String,java.lang.String> buildlist() Method that maps the available expression "ids" and "descriptions" stored in the database at the moment. double calculate(java.lang.String id, double... vars) Method that calculates the the value for a given expression id with the given variable values. boolean checkifexist(java.lang.String id) Method for checking whether the given expression id already exists in the database. void createexpression(java.lang.String id, java.lang.String exp, java.lang.String desc, java.lang.String varlist) Method for inserting an expression into the database following the proper format. void removeexpression(java.lang.String id) Methode to remove an expression from the database given its id. Methods inherited from class java.lang.Object equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Constructors Methods