server/ui/js/arena.js

149 lines
3.7 KiB
JavaScript

var savebot = function(name, callback){
data = {
"id": $("#robot_picker").val(),
"code": editor.getValue()
};
if (name){
data.name = name;
}
$.ajax({
method:"POST",
data: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
url:"/api/v1/bot/" + $("#robot_picker").val() + "/",
success: function(data){
var d = new Date();
$("#lastsave").html("Saved at " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
if (callback){
callback();
}
}
});
};
var newbot = function(){
data = {
"code": editor.getValue(),
};
$.ajax({
method:"POST",
data: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
url:"/api/v1/bot/" + $("#robot_picker").val() + "/",
success: function(data){
console.log(data);
if (data.id){
$("#robot_picker").val(data.id);
}
// I'm lazy
set_current_bot(data.id);
location.reload();
}
});
};
var set_current_bot = function(name){
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
queryParameters['bot'] = name;
history.pushState(null, null, "?"+ $.param(queryParameters));
};
$(document).ready(function(){
$("#error").hide();
editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
function resizeAce() {
return $('#editor').height($(window).height() - $("#editor").offset().top - 20);
};
$(window).resize(resizeAce);
resizeAce();
var gorobots = gorobots_init({}, true);
$("#robot_picker").change(function(e){
$.ajax({
url:"/api/v1/bot/" + $("#robot_picker").val(),
success: function(data){
editor.setValue(data.code);
set_current_bot($("#robot_picker").val());
}
});
});
$("#save").click(function(e){
savebot();
});
$("#new").click(function(e){
newbot();
});
var renaming = false;
$("#rename").click(function(e){
if (renaming){
// POST new name to server
savebot($("#newname").val(), function(){
// BE LAZY
location.reload();
});
$("#rename-block").hide();
$("#rename").html("Rename Bot");
renaming = false;
} else {
$("#rename-block").show();
$("#rename").html("Ok");
renaming = true;
}
});
$.ajax({
url:"/api/v1/bot/1/",
success: function(data){
editor.setValue(data.code);
$("#robot_picker").val(1);
}
});
$('#starter').click(function() {
savebot();
$('#tabs a[href="#arena"]').tab('show');
var url = "ws://{{ server.hostname }}:8666/ws/";
gorobots.set_spectator(false);
gorobots.set_server(
url,
"{{ game }}"
);
});
$('#watch').click(function() {
savebot();
$('#tabs a[href="#arena"]').tab('show');
var url = "ws://{{ server.hostname }}:8666/ws/";
gorobots.set_spectator(true);
gorobots.set_server(
url,
"{{ game }}"
);
});
$('#tabs a[href="#code"]').tab('show');
});