Wednesday, November 6, 2013

Game implemented as an app for SharePoint in SharePoint 2013

http://code.msdn.microsoft.com/office/SharePoint-2013-Game-4048c85b
vs2012->file->new->project c# ->office/SharePoint->apps->apps for SharePoint 2013-> "SP_SharePointGame_js"
Click on 'Ok' Button
 Click on 'Validate' button. after 'Sign-in' click on 'Finish' button.
SP_SharePointGame_js -> Content -> App.css
add below css
.blank {
    cursor:pointer;
    background-image:url(../images/blank.png);
    width:96px;
    height:96px;
    margin:2px;
    float:left;
}
.nought {
    cursor:default;
    background-image:url(../images/nought.png);
    width:96px;
    height:96px;
    margin:2px;
    float:left;
}
.cross {
    cursor:default;
    background-image:url(../images/cross.png);
    width:96px;
    height:96px;
    margin:2px;
    float:left;

}

SP_SharePointGame_js -> Images -> add -> existing item -> add 'blank.png, cross.png, nought.png' images

SP_SharePointGame_js -> Right click -> Add -> New Item -> List -> 'Score'
 Click on 'Add' Button
Click on 'Finish' Button

SP_SharePointGame_js -> double click on 'Score' List (if any popup window open click on 'Yes')

SP_SharePointGame_js -> Pages -> Default.aspx 
add this script to 'PlaceHolderMain' of the Default.aspx page.
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div>
        <p id="message">
            initializing...
        </p>
    </div>
    <h1>SharePoint vs. You!</h1>
    <div id="currentScores" style="float: none;"></div>
    <div id="gameArea" style="width: 300px; height: 300px; float: none;">
        <div id="square1" onclick="square_click(1);" class="blank" style=""></div>
        <div id="square2" onclick="square_click(2);" class="blank"></div>
        <div id="square3" onclick="square_click(3);" class="blank"></div>
        <div id="square4" onclick="square_click(4);" class="blank"></div>
        <div id="square5" onclick="square_click(5);" class="blank"></div>
        <div id="square6" onclick="square_click(6);" class="blank"></div>
        <div id="square7" onclick="square_click(7);" class="blank"></div>
        <div id="square8" onclick="square_click(8);" class="blank"></div>
        <div id="square9" onclick="square_click(9);" class="blank"></div>
    </div>
    <input type="button" id="resetGame" onclick="resetNow();" runat="server" value="Restart Game" />

</asp:Content>

SP_SharePointGame_js -> Scripts -> App.js
add below script to App.js file
'use strict';

var context;
var web;
var list;
var listItems;
var listItem;
var user;
var existingPlayer = false;
var playerListId;
var currentWins = 0;
var currentLosses = 0;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

$(document).ready(function () {
    getUserName();
    start();
});

function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

function start() {
    context = SP.ClientContext.get_current();
    web = context.get_web();
    list = web.get_lists().getByTitle('Score');
    user = web.get_currentUser();
    context.load(user);

    context.executeQueryAsync(function () {
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>"
            + user.get_title()
            + "</Value></Eq></Where></View>");
        listItems = list.getItems(camlQuery);
        context.load(listItems, 'Include(Title, Wins, Losses)');
        context.executeQueryAsync(
            function () {
                showScore();
            },
            function (sender, args) {
                var dataArea = document.getElementById("currentScores");
                while (dataArea.hasChildNodes()) {
                    dataArea.removeChild(dataArea.lastChild);
                }
                dataArea.appendChild(document.createTextNode("Failed to get score data. Error: "
                    + args.get_message()));
            });
    },
    function () {
        var dataArea = document.getElementById("currentScores");
        while (dataArea.hasChildNodes()) {
            dataArea.removeChild(dataArea.lastChild);
        }
        dataArea.appendChild(document.createTextNode("Failed to get user name. Error: "
            + args.get_message()));
    });
}

function showScore() {
    var tableArea = document.getElementById("currentScores");
    while (tableArea.hasChildNodes()) {
        tableArea.removeChild(tableArea.lastChild);
    }
    var listItemEnumerator = listItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var listItem = listItemEnumerator.get_current();
        var playerName = listItem.get_fieldValues()["Title"];
        var playerWins = listItem.get_fieldValues()["Wins"];
        var playerLosses = listItem.get_fieldValues()["Losses"];
        if ((isNaN(playerWins)) || (IsNullOrUndefined(playerWins))) {
            playerWins = 0;
        }
        if ((isNaN(playerLosses)) || (IsNullOrUndefined(playerLosses))) {
            playerLosses = 0;
        }
        tableArea.appendChild(document.createTextNode("Welcome " + user.get_title() + "! You have won " + playerWins + " times, and lost " + playerLosses + " times!"));
        existingPlayer = true;
    }
    if (!existingPlayer) {
        tableArea.appendChild(document.createTextNode("Welcome " + user.get_title() + "! You have won 0 times, and lost 0 times!"));
    }
}

function square_click(number) {
    var square = document.getElementById("square" + number);
    if (square.getAttribute("class") == "blank") {
        square.setAttribute("class", "nought")
        if (checkWin('User')) {
            recordScore('Wins');
        }
        else {
            SharePointTurn();
        }
    }
}

function SharePointTurn() {
    if (hasGameEnded()) {
        recordScore('Draw');
    }
    else {
        setTimeout(function () { SharePointPlay(); }, 250);
    }
}

function hasGameEnded() {
    var gameEnded = true;
    for (var squareCounter = 1; squareCounter <= 9; squareCounter++) {
        var square = document.getElementById("square" + squareCounter);
        if (square.getAttribute("class") == "blank") {
            gameEnded = false;
        }
    }
    return (gameEnded);
}

function SharePointPlay() {
    var randomNumber;
    var availableSquare = false;
    while (!availableSquare) {
        randomNumber = Math.floor(Math.random() * 9) + 1;
        var square = document.getElementById("square" + randomNumber);
        if (square.getAttribute("class") == "blank") {
            square.setAttribute("class", "cross")
            availableSquare = true;
        }
    }
    if (checkWin('SharePoint')) {
        recordScore('Losses');
    }
}

function checkWin(player) {
    var retVal = false;
    var square1 = document.getElementById("square1").getAttribute("class");
    var square2 = document.getElementById("square2").getAttribute("class");
    var square3 = document.getElementById("square3").getAttribute("class");
    var square4 = document.getElementById("square4").getAttribute("class");
    var square5 = document.getElementById("square5").getAttribute("class");
    var square6 = document.getElementById("square6").getAttribute("class");
    var square7 = document.getElementById("square7").getAttribute("class");
    var square8 = document.getElementById("square8").getAttribute("class");
    var square9 = document.getElementById("square9").getAttribute("class");
    if (player == "User") {
        if ((square1 == "nought") && (square2 == "nought") && (square3 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square1 == "nought") && (square4 == "nought") && (square7 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square1 == "nought") && (square5 == "nought") && (square9 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square2 == "nought") && (square5 == "nought") && (square8 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square3 == "nought") && (square6 == "nought") && (square9 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square3 == "nought") && (square5 == "nought") && (square7 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square4 == "nought") && (square5 == "nought") && (square6 == "nought")) {
            retVal = true;
            return (retVal);
        }
        if ((square7 == "nought") && (square8 == "nought") && (square9 == "nought")) {
            retVal = true;
            return (retVal);
        }
    }
    else {
        if ((square1 == "cross") && (square2 == "cross") && (square3 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square1 == "cross") && (square4 == "cross") && (square7 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square1 == "cross") && (square5 == "cross") && (square9 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square2 == "cross") && (square5 == "cross") && (square8 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square3 == "cross") && (square6 == "cross") && (square9 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square3 == "cross") && (square5 == "cross") && (square7 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square4 == "cross") && (square5 == "cross") && (square6 == "cross")) {
            retVal = true;
            return (retVal);
        }
        if ((square7 == "cross") && (square8 == "cross") && (square9 == "cross")) {
            retVal = true;
            return (retVal);
        }
    }
    return (retVal);
}

function recordScore(state) {
    for (var squareCounter = 1; squareCounter <= 9; squareCounter++) {
        var square = document.getElementById("square" + squareCounter);
        square.disabled = true;
    }
    if (existingPlayer) {
        if (state == "Wins") {
            alert("Hurrah! You are smarter than SharePoint!");
            listItem = list.getItemById(playerListId);
            context.load(listItem);
            context.executeQueryAsync(function () { incrementWins(); }, function () { alert("Current score could not be retrieved"); });
        }
        if (state == "Draw") {
            alert("Not Bad: You and SharePoint are evenly matched...");
        }
        if (state == "Losses") {
            alert("Erm, I don't know how to break this to you, but you've been beaten by a random number generator...");
            listItem = list.getItemById(playerListId);
            context.load(listItem);
            context.executeQueryAsync(function () { incrementLosses(); }, function () { alert("Current score could not be retrieved"); });
        }
    }
    else {
        if (state == "Wins") {
            alert("Hurrah! You are smarter than SharePoint!");
            var itemCreateInfo = new SP.ListItemCreationInformation();
            listItem = list.addItem(itemCreateInfo);
            listItem.set_item("Title", user.get_title());
            listItem.set_item("Wins", 1);
            listItem.set_item("Losses", 0);
            listItem.update();
            context.load(listItem);
            context.executeQueryAsync(function () { playerListId = listItem.get_id(); },
                function () { alert('Score could not be stored'); });
        }
        if (state == "Draw") {
            alert("Not Bad: You and SharePoint are evenly matched...");
        }
        if (state == "Losses") {
            alert("Erm, I don't know how to break this to you, but you've been beaten by a random number generator...");
            var itemCreateInfo = new SP.ListItemCreationInformation();
            listItem = list.addItem(itemCreateInfo);
            listItem.set_item("Title", user.get_title());
            listItem.set_item("Wins", 0);
            listItem.set_item("Losses", 1);
            listItem.update();
            context.load(listItem);
            context.executeQueryAsync(function () { playerListId = listItem.get_id(); },
                function () { alert('Score could not be stored'); });
        }
    }
}

function incrementWins() {
    currentWins = listItem.get_fieldValues()["Wins"];
    listItem.set_item("Wins", parseInt(currentWins) + 1);
    listItem.update();
    context.executeQueryAsync(null, function () { alert("Score could not be updated"); });
}

function incrementLosses() {
    currentLosses = listItem.get_fieldValues()["Losses"];
    listItem.set_item("Losses", parseInt(currentLosses) + 1);
    listItem.update();
    context.executeQueryAsync(null, function () { alert("Score could not be updated"); });
}

function resetNow() {
    for (var squareCounter = 1; squareCounter <= 9; squareCounter++) {
        var square = document.getElementById("square" + squareCounter);
        square.setAttribute("class", "blank");
        square.disabled = false;
    }
    start();

}

SP_SharePointGame_js -> Right Click -> Deploy
Thank You.

No comments:

Post a Comment

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   ...

Popular posts