Hadi Biraz Oyun Oynayalım…
Selamlar;
Geçenlerde http://code.org/ adlı bir site gözüme çarptı. Gençlere programcılığı sevdirip, code yazdırmayı aşılıyor. Bunu da çeşitli oyunlarla destekliyor. Ben de buradan yola çıkarak seminerlere gittiğim zaman, programcılığın ne kadar orjinal bir iş olabileceğini göstermek amaçlı benzer bir uygulama geliştirmeye karar verdim.Şimdi biraz da uygulama hakkında konuşalım.
Yukarıda görüldüğü gibi uygulamada Lucky adlı bir köpeğimiz var. Benim eski köpeğimin adı:)
5 x 5’lik kare bir playground içinde lucky’e çeşitli komutlar vererek hareket ettiricez.Bol bol javascript yazıcaz:)Tabi boşu boşuna hareket ettirmiyicez.
Playground içinde random bir kordinat’da bir top çıkacak.Ve biz belirli bir sürede, random olarak belirlenen belli bir komut sayısında lucky’i topa vardırmaya çalışıcaz.
Eğer lucky topa vardığında hala yazmamız gereken komut var ise yada lucky daha topa varmadan süre biter ise kaybedicez. Süre bitmeden tam belirlenen komut sayısında lucky’i topla buluşturur isek kazanacaz. Kazanma veya kaybeyme durumunda geri sayan süre bitene kadar bekledikten sonra; top yeni bir kordinata gelecek ve yeni komut sayısı ile lucky başladığı yere geri dönücek. Bu arada süre tekrardan geri saymaya başlıyacak. Kısaca yeni bir oyuna başlamış olucaz. Bir de açtığımız session’a göre log tutucaz. Yani kaçkere yendik, kaç kere kaybettik, nekadar sürede bittirdik ve kaç komut satırı girdik gibi.
Burada önemli bir nokta da, süre oyuna giren herkes için aynı olması yani ben oyunda 47. sn de isem, oyuna yeni giren biri için de geri sayım 47. saniyeden devam edecek.Bir de random olarak belirlenen topun yeri ve girilmesi gereken kordinat sayısı herkes için aynı olucak.Bunun için signalR teknolojisini kullanıcaz.Bir çeşit aynı anda toplu yapılan onlien sınav olucak.
Ugulamamızı Mvc ortamında ve codefirst kullanarak yazıcaz.Dilerseniz şimdi koda geçelim.
Öncelikle Css’leri aradan çıkaralım.Aşağıda görüldüğü gibi lucky’nin, buttonlarımızın, ball’un, komut girilecek kutucuğun, geri sayacak counter’ın style’ları belirlenmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
<style> div.block { position: absolute; background-image: url('../img/luckyRight.jpg'); left: 20px; width: 80px; height: 80px; margin: 5px; top: 300px; z-index: 2; } div.ball { position: absolute; background-image: url('../img/ball3.png'); left: 20px; width: 50px; height: 50px; margin: 5px; top: 300px; z-index: 1; } button.run { background-color: #5BB75B; background-image: -moz-linear-gradient(center top, #62C462, #51A351); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); border-radius: 5px 5px 5px 5px; font-size: 15px; color: white; line-height: normal; padding: 9px 14px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } button.reset { border-radius: 5px 5px 5px 5px; font-size: 13px; line-height: normal; padding: 9px 14px; background-color: #F5F5F5; background-image: -moz-linear-gradient(center top, #FFFFFF, #E6E6E6); background-repeat: repeat-x; border-color: #CCCCCC #CCCCCC #B3B3B3; border-image: none; border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); color: #333333; cursor: pointer; display: inline-block; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } button.list { background-color: #49AFCD; background-image: -moz-linear-gradient(center top, #5BC0DE, #2F96B4); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); color: #FFFFFF; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 5px 5px 5px 5px; font-size: 15px; line-height: normal; padding: 9px 14px; } div.counter { color: orange; font-weight: bold; font-size: 180px; } td.counter { vertical-align: text-top; color: rgb(71, 156, 213); font-weight: bold; font-size: 30px; } i.counter { color: rgb(213, 71, 207); font-weight: bold; font-size: 80px; } i.counter2 { color: red; font-size: 45px; } td.counter2 { vertical-align: text-top; color: black; font-weight: bold; font-size: 30px; width: 100%; display: none; } </style> |
Şimdi Index.chtml’deki görsel’in html’ini yazalım:
Aşağıdaki html code’da görüldüğü gibi bir tablo içine önce playground’ın resmi, komutların girileceği bir textarea ve süre ile kalan toplam komut sayısını gösteren kolonlar eklendi.
Alt satıra yukardaki buttonlar kondu.Buttonlara basılınca çağrılan functionları yazının devamında irdeliyecez.
- Run buttonu:Girilen komutları çalıştırılacağı function’ı çağrırı.
- Reset butonu:Lucky’i başlangıç konumuna getirir.
- See Lucky’s Command:Lucky için girilebilecek komutları gösterir.
Lucky’yi için block divi ve top için ball div’leri aşağıda görüldüğü gibi konulmuştur. Kazanınca melodi çalmaktadır. Ses için de sound id’li bir span kullanılmaktadır .Böylece görsel taraf ile ilgili çalışmamız aşağıda yazıldığı şekli ile bitmiştir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<body> <table> <tr> <td> <div style="background-image: url(/img/bgPicture.png); height: 409px; width: 409px;"></div> </td> <td> <div> <textarea style="height: 400px; width: 350px" id="command"></textarea> </div> </td> <td class="counter">Catch The Ball exactly <i class="counter" id="counter"></i>moves in above the seconds. <div id="Time" class="counter"></div> </td> <td id="resultTD" class="counter2"> <img id="resulImg" src="/img/winner.jpg"/><br/> Next match will start in <i id="Time2" class="counter2"></i> seconds. </td> </tr> <tr> <td></td> <td> <button class="run" id="run" onclick="RunCommand();">⇒ Run</button> <button class="reset" id="Reset" onclick="Reset();"> <img widht="20px" height="20px" src="/img/1381595059_101924.ico"></img>Reset </button> <button class="list" id="list" onclick="ShowList();"> <img widht="20px" height="20px" src="/img/1381601741_53599.ico"> See Lucky's Command </button> </td> </tr> </table> <div class="block"></div> <div class="ball"></div> <span id="sound"></span> <div id="divList" style="background-image: url(/img/commandList.png); position: absolute; height: 259px; width: 401px; top: 165px; left: 580px; display: none"></div> </body> |
HomeController’da Index() Action’ımıza oradan da Index view’ımıza gidelim:
1 2 3 4 5 6 7 |
public class HomeController : Controller { public ActionResult Index() { return View(); } } |
Index View’ımızda scriptleri oluşturmaya başlıyalım:
Öncelikle nuget’den signalR package ve EntityFramework inidirilmelidir. Aşağıda görüldüğü gibi önce jquery ve signalR javascriptleri include edilmiştir. Daha sonra önceki signalR makalemde de bahsettiğim gibi magic script olan /signalr/hubs’ı Index view’a konulmuştur.
Yine aşağıda görüldüğü gibi $.connection.serverTime; ile signalR teknolojisi ile server side tarafındaki Hub classından türemiş serverTime class’ına erişilmiştir. settime() functionından dönen random zaman(t),toplam command sayısı(moves) ve topun random oluşan kordinatları(top,left) alınmıştır. Sonra html’deki ilgili alanlar bu değerlerle doldurulmuştur. Süre 90 sn ise yani yeniden başlanmış ise result yani kazandık veya kaybettik mesajı temizlenip, zamanlıyıcı tekrardan gösterilmiştir. Ayrıca Run butonun’un css kodları ve tıklanınca çağrılacak RunCommand() belirlenmiştir. Ve lucky başlangıç noktasına(20,300) getirilmiştir.
Aşağıda, $(document).ready’de timeout_init() function’ı çağrılmıştır. Bu function ile counter değişkeni temizlenmiştir ve messagehub.server.startTime() ile yine signalR teknolojisi kullanılarak server side tarafındaki herkes için aynı olan geri sayılan zaman değeri çekilmiştir. Ayrıca $(document).ready’de commad textarea ile ilgili işlemler yapılmıştır. Burada herhangi bir tuşa basılınca textarea’daki methodlar “()” sembolüne göre ayrıştırılıp toplam sayı alınmıştır. Burada önemli olan bu sayı kullanılmak için belirlenen komut sayısından fazla ise Run button‘unun işlevi kaldırılır.Yani bir çeşit passive edilir.Örneğin 5 komutta lucky’nin topu alması gerekirken 6. komut girilirse Run button’u pasive hale getirilir. Ayrıca textarea’ya her yeni komut girildikçe, kullanılması gereken komut sayısı bir azalarak bize yardımcı olur.İlgili kod parçaçığı yandadır.$(“#counter”).html((commandServerCounter – commandLength)); Tabi girilen bir komutun silinmesi durumunda da, kullanılması gereken kod bir artar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<script src="@Url.Content("~/Scripts/jquery-2.0.3.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.signalR-2.0.0-rc1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var wait; var commandServerCounter; var commandLength var messagehub = $.connection.serverTime; messagehub.client.settime = function (t, moves, top, left) { $("#Time").html(t); $("#Time2").html(t); if (commandLength == 0 || commandLength == undefined) { $("#counter").html(moves); commandServerCounter = moves; } $(".ball").css({ "left": left, "top": top }); if (t == 90) { $("#resultTD").hide(); //$("#Time").show(); $(".counter").show(); $("#run").attr('onclick', 'RunCommand();'); $("#run").css('background-color', '#5BB75B'); clearInterval(wait); $(".block").css({ "left": "20px", "top": "300px" }); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); $("#command").val(''); $("#counter").html(moves); commandServerCounter = moves; } }; var check = null; function timeout_init() { clearInterval(check); check = setInterval(function () { messagehub.server.startTime(); clearInterval(check); }, 1000); } $.connection.hub.start(); $(document).ready(function () { timeout_init(); var wait; $("#command").focus(); $("#command").keyup(function (e) { if ($("#command").val().trim() != "") { commandLength = $("#command").val().split("();").length - 1; console.log(commandLength); $("#counter").html((commandServerCounter - commandLength)); if ((commandServerCounter - commandLength) < 0) { $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); } else { $("#run").attr('onclick', 'RunCommand();'); $("#run").css('background-color', '#5BB75B'); } } else { $("#counter").html(commandServerCounter); } }); }); </script> |
Şimdi de server side tarafında, yukarıda kullanılan serverTime class’ını ve startTime methodunu inceleyelim.
İlgili kod bloğu aşağıdadır.serverTime class’ının construction’ında fillCordinates() methodu çağrılmıştır. Bu yaratılan kordinatlar içinden bir tanesi random olarak belirlenir.Ve yakalanacak olan topun, kordinatı olarak atanır. Ayrıca geri sayılacak zaman değeri olan count‘a 90 değeri atanmıştır.
startTime() method’unda dikkat ederseniz, bir thread açılmıştır ve write() methodu çağrılmıştır.Thread açılmasındaki amaç zamanın geri sayımı arkaplanda çalışıp, yapılacak diğer işlemlerden etkilenmemesini sağlamaktır.Write() method’unda sonsuz döngü içinde 1sn aralılar ile count değeri azaltılmış. Ve signalR teknolojisi sayesinde client’ların settime() function’ına şu anki süre, random seçilen topun kordinatları ve random seçilen toplam komut sayısı yollanmıştır.Bu işlem 1 sn’lik bekleme süreleri ile tekrarlanmaktadır.Süre dolduğunda tekrardan 90 değeri atanıp; top için yeni kordinatlar çekilir.Yani süre sıfırlandığı için yeni bir oyun başlamış olur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
public class serverTime : Hub { List<Tuple<int, int>> cordinates = new List<Tuple<int, int>>(); public void fillCordinates() { cordinates.Add(new Tuple<int, int>(345, 340)); cordinates.Add(new Tuple<int, int>(345, 260)); cordinates.Add(new Tuple<int, int>(345, 180)); cordinates.Add(new Tuple<int, int>(345, 100)); cordinates.Add(new Tuple<int, int>(345, 20)); cordinates.Add(new Tuple<int, int>(185, 340)); cordinates.Add(new Tuple<int, int>(185, 260)); cordinates.Add(new Tuple<int, int>(185, 180)); cordinates.Add(new Tuple<int, int>(185, 100)); cordinates.Add(new Tuple<int, int>(185, 20)); cordinates.Add(new Tuple<int, int>(265, 20)); cordinates.Add(new Tuple<int, int>(265, 100)); cordinates.Add(new Tuple<int, int>(265, 180)); cordinates.Add(new Tuple<int, int>(265, 260)); cordinates.Add(new Tuple<int, int>(265, 340)); cordinates.Add(new Tuple<int, int>(105, 340)); cordinates.Add(new Tuple<int, int>(105, 260)); cordinates.Add(new Tuple<int, int>(105, 180)); cordinates.Add(new Tuple<int, int>(105, 100)); cordinates.Add(new Tuple<int, int>(105, 20)); //cordinates.Add(new Tuple<int, int>(25, 340)); cordinates.Add(new Tuple<int, int>(25, 260)); cordinates.Add(new Tuple<int, int>(25, 180)); cordinates.Add(new Tuple<int, int>(25, 100)); cordinates.Add(new Tuple<int, int>(25, 20)); } int count =90; int moves,top,left; Random rndElement; public serverTime() { fillCordinates(); rndElement = new Random(); moves = rndElement.Next(8, 15); var cor = cordinates[rndElement.Next(cordinates.Count)]; left = cor.Item1; top = cor.Item2; cor = null; } public void startTime() { if ((int)System.Web.HttpContext.Current.Application["Counter"] == 90) { System.Web.HttpContext.Current.Application["Counter"] = 89; Thread thread = new Thread(write); thread.Start(); } } public void write() { while (true) { //Clients.All.settime(DateTime.Now.ToString()); Clients.All.settime(count--, moves,top,left); Thread.Sleep(1000); if (count <= 0) { moves=rndElement.Next(8, 15); var cor = cordinates[rndElement.Next(cordinates.Count)]; left = cor.Item1; top = cor.Item2; cor = null; count = 90; } } } |
Şimdi de Index.chtml’de kullanılan 3 button’da çağrılan RunCommand(); ShowList(); ve Reset(); javascript functionlarını inceleyelim.
İlgili javascript kodlar görüldüğü gibi aşağıdadır. Reset() function’ı lucky’i başlangı konumuna getirir.ShowList() lucky’i haraket ettiren komutları gösterir.
Burada esas önemli function RunCommand()’dir. Textarea’ya girdiğimiz komutları tek tek işletir. Şimdi daha detaylı inceleyelim. Enter karakterine göre tüm komutlar bir diziye atılır. Komutlar bir döngü içinde çalıştırılırken hareket animasyonları bir problem ile karşılaşılması durumunda tekrardan çağrılması amaçlı ikiyüz milisaniyelik wait=setInterval(function(){ ‘ı içinde çağrılmaktadır. Girilen komuta göre lucky hareket etmektedir. Her hareketten önce lucky’de hareket var mı diye bakılır. Var ise bir önceki komut halen çalışıyor diye işlem yapılmaz. Buna da if (!$(“.block”).is(“:animated”)) { şeklinde bakılmaktadır. Bir sonraki Interval zamanında commandList dizisindeki ilk sıradaki komut tekrardan çağrılır ve çalıştırılır. Eğer bir sorun yok ise komut çalıştırılmaya başlandığı an diziden çalıştırılan komut commandList.splice(0, 1) ile çıkarılır. Böylece bir sonraki Interval zamanında aynı komut bir daha çağrılmaz ve çalıştırılmaz. Daha sonra lucky’nin yapacağı hareket ile, playground sınırları içinde kalınıp kalınmadığı kontrol edilir. Örnek move() komutu için if ((pos.left + 75) < 350) şeklinde kontrol yapılmaktadır. Eğer sonuç olumlu ise lucky animasyon şeklinde ilgili komutun hareketini yapar ve ensonunda checkCordinate() function’ı ile lucky’nin topu alıp alamadığı, aldı ise ve tam istenen komut sayısı içinde yapıp yapmadığına bakılır. İşlem sonunda server taraftaki messagehub.server.resultRecord(true, $(“#Time”).html()) methodu tetiklenir ve sonuç database kaydedilir. Tek kaybetme yolu tam istenen komutsayısına erişmeden lucky’nin topu yakalamasıdır. Bunu commandServerCounter – commandLength şeklinde kontrol edilir. Sonuç olumsuz ise kaybetti mesajı çıkartılıp, bir sonraki oyun için sürenin dolması beklenir. resultRecord() methodunu ilerde inceleyeceğiz.Birde süre dolar ise kaybetme yazısı olmadan oyun resetlenir.
Yukarıda görüldüğü gibi kazanma işleminden sonra başarı müziği çalınır ve winner resmi gösterilir.Kaybetme işleminde de loser resmi gösterilir. Ayrıca Run buttonu pasif hale getirilip, süre tamamlanana kadar bir sonraki oyun beklenir.
Bu işlem adımları tüm komutlar için aynıdır.İlgisi javascript kodları aşağıdadır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
function playSound(url) { document.getElementById("sound").innerHTML = "<embed src='" + url + "' hidden=true autostart=true loop=false>"; } function Reset() { $(".block").css({ "left": "20px", "top": "300px" }); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); clearInterval(wait); } function ShowList() { if ($("#divList").css('display') == 'none') { $("#divList").animate({ "opacity": "toggle" }, "slow"); } else { $("#divList").hide(1000); } } function RunCommand() { commandList = $("#command").val().split("\n"); wait = setInterval(function () { console.log('length:' + commandList.length) if (commandList.length == 0 || commandList[0].trim() == "") { console.log('stop'); clearInterval(wait); } for (i = 0; i < commandList.length; i++) { console.log("command:" + commandList[i]); if (!$(".block").is(":animated")) { console.log('not animated'); var pos = $(".block").offset(); switch (commandList[i]) { case 'move();': commandList.splice(0, 1); if ((pos.left + 75) < 350) { console.log('move'); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); $(".block").animate({ "left": "+=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "left": "=" + pos.left + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'left();': commandList.splice(0, 1); if ((pos.left - 75) > 20) { console.log('left'); $(".block").css('background-image', 'url(../img/luckyLft.png)'); $(".block").animate({ "left": "-=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "left": "=" + pos.left + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'up();': commandList.splice(0, 1); if ((pos.top - 75) > 0) { console.log('up'); $(".block").css('background-image', 'url(../img/luckyU.png)'); $(".block").animate({ "top": "-=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "top": "=" + pos.top + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'down();': commandList.splice(0, 1); if ((pos.top + 75) < 310) { console.log('down'); $(".block").css('background-image', 'url(../img/luckyDwn.png)'); $(".block").animate({ "top": "+=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "top": "=" + pos.top + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; default: } } else { console.log('animated'); } } }, 200); } function checkCordinate() { var dog = $(".block"); var positionDog = dog.position(); var ball = $(".ball"); var positionBall = ball.position(); console.log("ball:" + positionBall.left + "," + positionBall.top); console.log("dog:" + positionDog.left + "," + positionDog.top); console.log("dog80:" + (positionDog.left + 80) + "," + (positionDog.top + 80)); if ((positionDog.left + 40 >= positionBall.left && positionDog.left + 40 <= positionBall.left + 50) && (positionDog.top + 40 >= positionBall.top && positionDog.top + 40 <= positionBall.top + 50)) { console.log("Cordinate:true"); if ((commandServerCounter - commandLength) == 0) { messagehub.server.resultRecord(true, $("#Time").html()); $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); return true; } else { $(".counter").hide(); $("#resultTD").show(); $("#resulImg").attr("src", "/img/lost.jpg"); $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); messagehub.server.resultRecord(false, $("#Time").html()); return false; } } else { console.log("Cordinate:false"); return false; } } |
Database’e kaydedilecek LogModel kodu aşağıdadır:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LuckyPlay.Controllers { public class LogModel { public int ID { get; set; } public string SessionID { get; set; } public int Win { get; set; } public int Lost { get; set; } public int MoveCount { get; set; } public int Counter { get; set; } public bool IsMobile { get; set; } public string MobileDeviceType { get; set; } public string BrowserType { get; set; } public DateTime Time { get; set; } } } |
LogContext yani codefirst context’imiz aşağıdaki gibidir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System.Data.Entity; using System.Data.Entity.ModelConfiguration; namespace LuckyPlay.Controllers { public class LogContext : DbContext { public DbSet<LogModel> tblLogRecord { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new PartsTypeConfiguration()); base.OnModelCreating(modelBuilder); } } public class PartsTypeConfiguration : EntityTypeConfiguration<LogModel> { public PartsTypeConfiguration() { ToTable("tblLogRecord"); } } } |
İlgili tabloda aşağıdaki gibidir.
HomeController’daki resultRecord() methodu aşağıdaki gibidir. Burada işlem başarılı yada başarısız olduğu durumda ilgili session’daki user bulunup yok ise yeni yaratılıp, browser tipi, mobile’den mi girdi, mobil ise cihaz modeli, geçerli zaman, işelmin sonlandığı andaki counter değeri, toplam girilen komut sayısı ve son olarak toplam kazanma veya kaybetme sayıları kaydedilir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
public void resultRecord(bool result,int Counter) { try { using (LogContext dbContext = new LogContext()) { if(dbContext.tblLogRecord.Where(l => l.SessionID == HttpContext.Current.Session.SessionID).FirstOrDefault()==null) { LogModel data = new LogModel(); data.SessionID = HttpContext.Current.Session.SessionID; data.BrowserType = HttpContext.Current.Request.Browser.Type; data.IsMobile = HttpContext.Current.Request.Browser.IsMobileDevice; data.MobileDeviceType = HttpContext.Current.Request.Browser.MobileDeviceModel; data.Time = DateTime.Now; data.Counter = Counter; data.MoveCount = moves; if (result) { data.Win = 1; data.Lost = 0; } else { data.Win = 0; data.Lost = 1; } dbContext.tblLogRecord.Add(data); dbContext.SaveChanges(); } else { LogModel model = dbContext.tblLogRecord.Where(l => l.SessionID == HttpContext.Current.Session.SessionID).FirstOrDefault(); if (result) model.Win++; else model.Lost++; model.Counter = Counter; model.MoveCount = moves; model.Time = DateTime.Now; dbContext.SaveChanges(); } } } catch (Exception ex) { int i = 0; } } |
Tüm Index.cshtm kodu Aşağıdadır:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
@{ ViewBag.Title = "Index"; } <header> <meta charset="utf-8"> <title>animate demo</title> <style> div.block { position: absolute; background-image: url('../img/luckyRight.jpg'); left: 20px; width: 80px; height: 80px; margin: 5px; top: 300px; z-index: 2; } div.ball { position: absolute; background-image: url('../img/ball3.png'); left: 20px; width: 50px; height: 50px; margin: 5px; top: 300px; z-index: 1; } button.run { background-color: #5BB75B; background-image: -moz-linear-gradient(center top, #62C462, #51A351); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); border-radius: 5px 5px 5px 5px; font-size: 15px; color: white; line-height: normal; padding: 9px 14px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } button.reset { border-radius: 5px 5px 5px 5px; font-size: 13px; line-height: normal; padding: 9px 14px; background-color: #F5F5F5; background-image: -moz-linear-gradient(center top, #FFFFFF, #E6E6E6); background-repeat: repeat-x; border-color: #CCCCCC #CCCCCC #B3B3B3; border-image: none; border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); color: #333333; cursor: pointer; display: inline-block; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } button.list { background-color: #49AFCD; background-image: -moz-linear-gradient(center top, #5BC0DE, #2F96B4); background-repeat: repeat-x; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); color: #FFFFFF; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; border-style: solid; border-width: 1px; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 5px 5px 5px 5px; font-size: 15px; line-height: normal; padding: 9px 14px; } div.counter { color: orange; font-weight: bold; font-size: 180px; } td.counter { vertical-align: text-top; color: rgb(71, 156, 213); font-weight: bold; font-size: 30px; } i.counter { color: rgb(213, 71, 207); font-weight: bold; font-size: 80px; } i.counter2 { color: red; font-size: 45px; } td.counter2 { vertical-align: text-top; color: black; font-weight: bold; font-size: 30px; width: 100%; display: none; } </style> <script src="@Url.Content("~/Scripts/jquery-2.0.3.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.signalR-2.0.0-rc1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/signalr/hubs")"></script> <script> var wait; var commandServerCounter; var commandLength var messagehub = $.connection.serverTime; messagehub.client.settime = function (t, moves, top, left) { $("#Time").html(t); $("#Time2").html(t); if (commandLength == 0 || commandLength == undefined) { $("#counter").html(moves); commandServerCounter = moves; } $(".ball").css({ "left": left, "top": top }); if (t == 90) { $("#resultTD").hide(); //$("#Time").show(); $(".counter").show(); $("#run").attr('onclick', 'RunCommand();'); $("#run").css('background-color', '#5BB75B'); clearInterval(wait); $(".block").css({ "left": "20px", "top": "300px" }); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); $("#command").val(''); $("#counter").html(moves); commandServerCounter = moves; } }; var check = null; function timeout_init() { clearInterval(check); check = setInterval(function () { messagehub.server.startTime(); clearInterval(check); }, 1000); } $.connection.hub.start(); function playSound(url) { document.getElementById("sound").innerHTML = "<embed src='" + url + "' hidden=true autostart=true loop=false>"; } function Reset() { $(".block").css({ "left": "20px", "top": "300px" }); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); clearInterval(wait); } function ShowList() { if ($("#divList").css('display') == 'none') { $("#divList").animate({ "opacity": "toggle" }, "slow"); } else { $("#divList").hide(1000); } } function RunCommand() { commandList = $("#command").val().split("\n"); wait = setInterval(function () { console.log('length:' + commandList.length) if (commandList.length == 0 || commandList[0].trim() == "") { console.log('stop'); clearInterval(wait); } for (i = 0; i < commandList.length; i++) { console.log("command:" + commandList[i]); if (!$(".block").is(":animated")) { console.log('not animated'); var pos = $(".block").offset(); switch (commandList[i]) { case 'move();': commandList.splice(0, 1); if ((pos.left + 75) < 350) { console.log('move'); $(".block").css('background-image', 'url(../img/luckyRight.jpg)'); $(".block").animate({ "left": "+=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "left": "=" + pos.left + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'left();': commandList.splice(0, 1); if ((pos.left - 75) > 20) { console.log('left'); $(".block").css('background-image', 'url(../img/luckyLft.png)'); $(".block").animate({ "left": "-=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "left": "=" + pos.left + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'up();': commandList.splice(0, 1); if ((pos.top - 75) > 0) { console.log('up'); $(".block").css('background-image', 'url(../img/luckyU.png)'); $(".block").animate({ "top": "-=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "top": "=" + pos.top + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; case 'down();': commandList.splice(0, 1); if ((pos.top + 75) < 310) { console.log('down'); $(".block").css('background-image', 'url(../img/luckyDwn.png)'); $(".block").animate({ "top": "+=75px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } else { $(".block").animate({ "top": "=" + pos.top + "px" }, "slow", function () { if (checkCordinate()) { playSound('../img/ok.wav'); //$("#Time").hide(); $(".counter").hide(); $("#resulImg").attr("src", "/img/winner.jpg"); $("#resultTD").show(); } }); } break; default: } } else { console.log('animated'); } } }, 200); } $(document).ready(function () { timeout_init(); var wait; $("#command").focus(); $("#command").keyup(function (e) { if ($("#command").val().trim() != "") { commandLength = $("#command").val().split("();").length - 1; console.log(commandLength); $("#counter").html((commandServerCounter - commandLength)); if ((commandServerCounter - commandLength) < 0) { $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); } else { $("#run").attr('onclick', 'RunCommand();'); $("#run").css('background-color', '#5BB75B'); } } else { $("#counter").html(commandServerCounter); } }); }); function checkCordinate() { var dog = $(".block"); var positionDog = dog.position(); var ball = $(".ball"); var positionBall = ball.position(); console.log("ball:" + positionBall.left + "," + positionBall.top); console.log("dog:" + positionDog.left + "," + positionDog.top); console.log("dog80:" + (positionDog.left + 80) + "," + (positionDog.top + 80)); if ((positionDog.left + 40 >= positionBall.left && positionDog.left + 40 <= positionBall.left + 50) && (positionDog.top + 40 >= positionBall.top && positionDog.top + 40 <= positionBall.top + 50)) { console.log("Cordinate:true"); if ((commandServerCounter - commandLength) == 0) { messagehub.server.resultRecord(true, $("#Time").html()); $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); return true; } else { $(".counter").hide(); $("#resultTD").show(); $("#resulImg").attr("src", "/img/lost.jpg"); $("#run").attr('onclick', ''); $("#run").css('background-color', 'gray'); messagehub.server.resultRecord(false, $("#Time").html()); return false; } } else { console.log("Cordinate:false"); return false; } } </script> </header> <body> <table> <tr> <td> <div style="background-image: url(/img/bgPicture.png); height: 409px; width: 409px;"></div> </td> <td> <div> <textarea style="height: 400px; width: 350px" id="command"></textarea> </div> </td> <td class="counter">Catch The Ball exactly <i class="counter" id="counter"></i>moves in above the seconds. <div id="Time" class="counter"></div> </td> <td id="resultTD" class="counter2"> <img id="resulImg" src="/img/winner.jpg"/><br/> Next match will start in <i id="Time2" class="counter2"></i> seconds. </td> </tr> <tr> <td></td> <td> <button class="run" id="run" onclick="RunCommand();">⇒ Run</button> <button class="reset" id="Reset" onclick="Reset();"> <img widht="20px" height="20px" src="/img/1381595059_101924.ico"></img>Reset </button> <button class="list" id="list" onclick="ShowList();"> <img widht="20px" height="20px" src="/img/1381601741_53599.ico"> See Lucky's Command </button> </td> </tr> </table> <div class="block"></div> <div class="ball"></div> <span id="sound"></span> <div id="divList" style="background-image: url(/img/commandList.png); position: absolute; height: 259px; width: 401px; top: 165px; left: 580px; display: none"></div> </body> |
Tüm HomeControl kodu aşağıdadır:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.SignalR; namespace LuckyPlay.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } public class serverTime : Hub { List<Tuple<int, int>> cordinates = new List<Tuple<int, int>>(); public void fillCordinates() { cordinates.Add(new Tuple<int, int>(345, 340)); cordinates.Add(new Tuple<int, int>(345, 260)); cordinates.Add(new Tuple<int, int>(345, 180)); cordinates.Add(new Tuple<int, int>(345, 100)); cordinates.Add(new Tuple<int, int>(345, 20)); cordinates.Add(new Tuple<int, int>(185, 340)); cordinates.Add(new Tuple<int, int>(185, 260)); cordinates.Add(new Tuple<int, int>(185, 180)); cordinates.Add(new Tuple<int, int>(185, 100)); cordinates.Add(new Tuple<int, int>(185, 20)); cordinates.Add(new Tuple<int, int>(265, 20)); cordinates.Add(new Tuple<int, int>(265, 100)); cordinates.Add(new Tuple<int, int>(265, 180)); cordinates.Add(new Tuple<int, int>(265, 260)); cordinates.Add(new Tuple<int, int>(265, 340)); cordinates.Add(new Tuple<int, int>(105, 340)); cordinates.Add(new Tuple<int, int>(105, 260)); cordinates.Add(new Tuple<int, int>(105, 180)); cordinates.Add(new Tuple<int, int>(105, 100)); cordinates.Add(new Tuple<int, int>(105, 20)); //cordinates.Add(new Tuple<int, int>(25, 340)); cordinates.Add(new Tuple<int, int>(25, 260)); cordinates.Add(new Tuple<int, int>(25, 180)); cordinates.Add(new Tuple<int, int>(25, 100)); cordinates.Add(new Tuple<int, int>(25, 20)); } int count =90; int moves,top,left; Random rndElement; public serverTime() { fillCordinates(); rndElement = new Random(); moves = rndElement.Next(8, 15); var cor = cordinates[rndElement.Next(cordinates.Count)]; left = cor.Item1; top = cor.Item2; cor = null; } public void startTime() { if ((int)System.Web.HttpContext.Current.Application["Counter"] == 90) { System.Web.HttpContext.Current.Application["Counter"] = 89; Thread thread = new Thread(write); thread.Start(); } } public void write() { while (true) { //Clients.All.settime(DateTime.Now.ToString()); Clients.All.settime(count--, moves,top,left); Thread.Sleep(1000); if (count <= 0) { moves=rndElement.Next(8, 15); var cor = cordinates[rndElement.Next(cordinates.Count)]; left = cor.Item1; top = cor.Item2; cor = null; count = 90; } } } public void resultRecord(bool result,int Counter) { try { using (LogContext dbContext = new LogContext()) { if(dbContext.tblLogRecord.Where(l => l.SessionID == HttpContext.Current.Session.SessionID).FirstOrDefault()==null) { LogModel data = new LogModel(); data.SessionID = HttpContext.Current.Session.SessionID; data.BrowserType = HttpContext.Current.Request.Browser.Type; data.IsMobile = HttpContext.Current.Request.Browser.IsMobileDevice; data.MobileDeviceType = HttpContext.Current.Request.Browser.MobileDeviceModel; data.Time = DateTime.Now; data.Counter = Counter; data.MoveCount = moves; if (result) { data.Win = 1; data.Lost = 0; } else { data.Win = 0; data.Lost = 1; } dbContext.tblLogRecord.Add(data); dbContext.SaveChanges(); } else { LogModel model = dbContext.tblLogRecord.Where(l => l.SessionID == HttpContext.Current.Session.SessionID).FirstOrDefault(); if (result) model.Win++; else model.Lost++; model.Counter = Counter; model.MoveCount = moves; model.Time = DateTime.Now; dbContext.SaveChanges(); } } } catch (Exception ex) { int i = 0; } } } } |
Yukarıda görüldüğü üzere çeşitli komutlar girerek bir objeye yön verdik. Dikkat ederseniz syntax çok önemlidir. Yani hem sona açılır kapanır parantez hemde noktalı virgül koymak şarttır.Örnek move();
Böylece programcılığın havası tatırılmak istenmiş ve kodlanarak computer’a bir şeyler yaptırılmıştır. Kullanılan algoritmalar ve karşımıza çıkabilecek durumlara göre önceden öngörülü olmak, yazılımcığın ruhuna bir dokunuştur. A yrıca süre,topun konumu ve toplam komut hakkı her giren oyuncu için aynıdır. Bu da online bir sınav için aynı anda başlayıp aynı anda biten süre anlamında çok güzel bir örnektir. Altyapı olarak signalR teknolojisi kullanılmıştır.Herbir user için detaylı loglama yapılmıştır.Amaç bir istatislik yapmak olabilir.Saat kaçta daha çok mobilden giriyolar. Hangi model cihazlar daha çok kullanılıyor. Kazanma değerleri yüksek olan userlara çeşitli eğitim borşürleri yada indirim kuponları gönderme.Kısaca data sonsuz güçtür.Ve programcılık sonu olmayan engin bir deniz gibidir.
Bu özlü sözlerden sonra, geldik bir makalenin daha sonuna.
Yeni bir makalede görüşmek üzere hoşçakalın.
Source Code: https://github.com/borakasmer/LuckyPlays
Örnek Url(İptal): http://luckyplay.azurewebsites.net/
Son Yorumlar