Dynamically removing movieclips - arrays

First time poster, long time reader.
I've been having a problem with figuring this out. I've been stuck in my game for 4 hours now, googling and trying to figure out how to do it.
I have a game where i add some cartoonish ants, that when they are clicked, they need to be removed from stage. There are 4 differend kinds of ants, so im doing a Math.random for picking which one to add. (ant 1+2+3 have 50% chance to spawn and 4th 50%)
rnd_nbr = (Math.random() * 5)+1;
I have a timer doing 10 tick, and i reset the timer to make neverending.
Then i have a math random and if sentences adding mc' to the stage with movement from Tweener, and event listeners for clicks.
But i cant figure out how to remove them when clicked.
I have done alot of failed tries right inside the click_candy_anty function.
I've left them commented out.
I apologize for abit messy coding, but it will be cleaned up when(hopefully) it gets working.
Help is highly appreciated.
import caurina.transitions.Tweener;
var ant_index:Array = new Array(10); //index for ants
var ant_number:int;
var ant_temp:int;
var rnd_nbr:int; //var for rnd number
var score:int = 0;
var score_update:String;
var reset_timer:Boolean = false;
var antTimer:Timer = new Timer(800,10); //timer
antTimer.addEventListener(TimerEvent.TIMER, create_ant);
var anty0_:anty_0; //creating ant vars for all 5 kind
var anty1_:anty_1;
var anty2_:anty_2;
var anty3_:anty_3;
var anty4_:anty_4;
var screen_number:int = 0;
var antyArray:Array = new Array(10);
var main:main_mc = new main_mc;
main.x = 0; //0,0
main.y = 0;
addChild(main);
var score_format:TextFormat = new TextFormat();
score_format.size = 25;
score_format.align = TextFormatAlign.CENTER;
var score_txt:TextField = new TextField();
score_txt.defaultTextFormat = score_format;
score_txt.text = "" + score;
score_txt.x = 600;
score_txt.y = 20;
score_txt.border = true;
score_txt.autoSize = TextFieldAutoSize.LEFT ;
score_txt.height = 40;
addChild(score_txt);
var score_txt_update:TextField = new TextField();
score_txt_update.defaultTextFormat = score_format;
score_txt_update.text = "0";
score_txt_update.x = 550;
score_txt_update.y = 20;
score_txt_update.border = true;
score_txt_update.autoSize = TextFieldAutoSize.LEFT ;
score_txt_update.height = 40;
score_txt_update.alpha = 0;
addChild(score_txt_update);
function click_candy_anty(event:MouseEvent):void{
if (score < 20){
//trace("evt: " + evt);
//this.removeChild();
//this.removeChild(this);
//removeChild(evt.currentTarget);
//removeChild(evt.target.name.substr(7));
//removeChild(this);
//removeChild(evt.currentTarget.name);
// trace("The " + evt.target.label + " button was clicked");
// trace(evt.type)
score++;
score_txt.text = "" + score;
//score_update = "+1";
score_txt_update.text = "+1";
//ori position x:570 y:20
score_txt_update.y = -30;
Tweener.addTween(score_txt_update, {y: 20, alpha: 1, time: 0.8, transition:"linear", onComplete:score_txt_update_fade});
}
else {
stop_game();
trace("48");
}
}
function score_txt_update_fade(Event = null){
Tweener.addTween(score_txt_update, {y: 50, alpha: 0, time: 0.4, transition:"linear"});
}
function click_leaf_anty(Event = null):void{
if (score > 0 && score < 20){
score--;
score_txt.text = "" + score;
score_txt_update.text = "-1";
score_txt_update.y = 50;
Tweener.addTween(score_txt_update, {y: 20, alpha: 1, time: 0.4, transition:"linear", onComplete:score_txt_update_fade_neg});
trace("12 wrong");
}
/* else {
stop_game();
trace("12");
trace("score: " + score + ", ");
}*/
}
function score_txt_update_fade_neg(Event = null){
Tweener.addTween(score_txt_update, {y: -30, alpha: -1, time: 0.8, transition:"linear"});
}
//screen1();
start_timer();
function screen1(Event = null):void {
screen_number = 2;//slet når event listener til scr1 kommer
if (screen_number == 2){
}
else {
screen_number = 2;
}
}
function screen2(Event = null):void {
if (screen_number == 3){
}
else {
screen_number = 3;
}
start_timer();
}
function start_timer(Event = null):void {
if (score < 20) {
if (reset_timer == false){
antTimer.start();
//trace("antTimer initialized");
}
if (reset_timer == true){
antTimer.reset();
antTimer.start();
//trace("antTimer RESETTED & initialized");
}
}
else {
stop_game();
trace("57");
}
}
function stop_game(Event = null):void {
if (screen_number != 2){
screen_number = 2;
trace("Game completed - launching end screen");
// move to next screen
for (var i:Number=0; i<=9;i++){
ant_temp = ant_number;
if (ant_temp < 9) {
//trace("ant_temp er lavere end 9::: " + ant_temp );
ant_temp++;
}
else if (ant_temp == 9) {
//trace("ant_temp lig med 9::: " + ant_temp );
ant_temp = 0;
}
if (ant_index[ant_temp] == 1){
//removeChild(anty1_);
if ("anty1_" + ant_temp != null){
removeChild(getChildByName("anty1_" + (ant_temp)));
}
}
if (ant_index[ant_temp] == 2){
//removeChild(anty2_);
if ("anty2_" + ant_temp != null){
removeChild(getChildByName("anty2_" + (ant_temp)));
}
}
if (ant_index[ant_temp] == 3){
//removeChild(anty3_);
if ("anty3_" + ant_temp != null){
removeChild(getChildByName("anty3_" + (ant_temp)));
}
}
else if (ant_index[ant_temp] == 4){
//removeChild(anty4_);
if ("anty4_" + ant_temp != null){
removeChild(getChildByName("anty4_" + (ant_temp)));
}
}
}//for loop end
screen3();
}
}
function screen3 (Event = null):void{
var end:end_mc = new end_mc;
end.x = 0; //0,0
end.y = 0; //
addChild(end);
}
function create_ant(Event = null):void {
//trace("antTimer triggered");
if (score < 20) {
rnd_nbr = (Math.random() * 5)+1;
ant_index[ant_number] = rnd_nbr;
trace("ant_number" + ant_number);
//trace("ant_index[" + ant_number + "]: " + ant_index[ant_number]);
if (ant_index[ant_number] == 1){
anty1_ = new anty_1();
anty1_.name = "anty1_" + (ant_number);
anty1_.height = 118;
anty1_.width = 102;
anty1_.x = 100;
anty1_.y = 300;
addChild(anty1_);
Tweener.addTween(anty1_, {x: 541, time: 3, transition:"linear"});
anty1_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty1_" + ant_number);
//trace("" + anty_1[ant_number].name);
}
if (ant_index[ant_number] == 2){
anty2_ = new anty_2();
anty2_.name = "anty2_" + (ant_number);
anty2_.height = 118;
anty2_.width = 102;
anty2_.x = 100;
anty2_.y = 300;
addChild(anty2_);
Tweener.addTween(anty2_, {x: 541, time: 3, transition:"linear"});
anty2_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty2_" + ant_number);
}
if (ant_index[ant_number] == 3){
anty3_ = new anty_3();
anty3_.name = "anty3_" + (ant_number);
anty3_.height = 118;
anty3_.width = 102;
anty3_.x = 100;
anty3_.y = 300;
addChild(anty3_);
Tweener.addTween(anty3_, {x: 541, time: 3, transition:"linear"});
anty3_.addEventListener(MouseEvent.MOUSE_DOWN, click_candy_anty);
//trace("anty3_" + ant_number);
}
else if (ant_index[ant_number] > 3 && ant_index[ant_number] < 7){
anty4_ = new anty_4();
anty4_.name = "anty4_" + (ant_number);
anty4_.height = 118;
anty4_.width = 102;
anty4_.x = 100;
anty4_.y = 300;
addChild(anty4_);
Tweener.addTween(anty4_, {x: 541, time: 3, transition:"linear"});
anty4_.addEventListener(MouseEvent.MOUSE_DOWN, click_leaf_anty);
//trace("anty4_" + ant_number);
}
ant_temp = ant_number;
if (ant_temp < 9) {
//trace("ant_temp er lavere end 9::: " + ant_temp );
ant_temp++;
}
else if (ant_temp == 9) {
//trace("ant_temp lig med 9::: " + ant_temp );
ant_temp = 0;
}
if (ant_index[ant_temp] == 1){
//removeChild(anty1_);
removeChild(getChildByName("anty1_" + (ant_temp)));
}
if (ant_index[ant_temp] == 2){
//removeChild(anty2_);
removeChild(getChildByName("anty2_" + (ant_temp)));
}
if (ant_index[ant_temp] == 3){
//removeChild(anty3_);
removeChild(getChildByName("anty3_" + (ant_temp)));
}
else if (ant_index[ant_temp] == 4){
//removeChild(anty4_);
removeChild(getChildByName("anty4_" + (ant_temp)));
}
/* if (ant_number == 9) { //resets the ant_number - being the end of the 10th ant
ant_number = 0;
start_timer(); // launches the timer again
trace("Timer resetted");
for (var i:Number=0; i<=9;i++){
if (ant_index[i] == 1){
//removeChild(anty1_);
removeChild(getChildByName("anty1_" + (i)));
}
if (ant_index[i] == 2){
//removeChild(anty2_);
removeChild(getChildByName("anty2_" + (i)));
}
if (ant_index[i] == 3){
//removeChild(anty3_);
removeChild(getChildByName("anty3_" + (i)));
}
else if (ant_index[i] == 4){
//removeChild(anty4_);
removeChild(getChildByName("anty4_" + (i)));
}
}//for loop end
}//ends if=9 reset*/
if (ant_number == 9) { //resets the ant_number at 10th ant, and restarts the timer
ant_number = 0;
reset_timer = true;
start_timer();
}
else {
ant_number++;
}
/*else {
ant_number++;
}*/
}
else if (score >= 20 && screen_number != 2){
stop_game();
trace("14");
}
} //create_ant func end

You can also use:
removeChild( evt.currentTarget as DisplayObject );
Or
var clicked_ant:DisplayObject = evt.currentTarget as DisplayObject;
removeChild( clicked_ant );

Let's say that you've created a Ant class, you could have something like this
private function init():void
{
this.addEventListener( MouseEvent.CLICK , clickHandler );
}
private function clickHandler( event:MouseEvent ):void
{
this.removeEventListener( MouseEvent.CLICK , clickHandler );
if( this.parent != null )
this.parent.removeChild( this );
}

Related

How to loop audio playlist?

I really love this pen https://codepen.io/himalayasingh/pen/QZKqOX and have been having lots of fun tinkering around with this audio player, but I can't for the life of me seem to get it to loop through the playlist properly. after every track the audio stops, I've been able to get the selected track to loop but not loop through the entire playlist. any insight?
$(function()
{
var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, albumName = $('#album-name'), trackName = $('#track-name'), albumArt = $('#album-art'), sArea = $('#s-area'), seekBar = $('#seek-bar'), trackTime = $('#track-time'), insTime = $('#ins-time'), sHover = $('#s-hover'), playPauseButton = $("#play-pause-button"), i = playPauseButton.find('i'), tProgress = $('#current-time'), tTime = $('#track-length'), seekT, seekLoc, seekBarPos, cM, ctMinutes, ctSeconds, curMinutes, curSeconds, durMinutes, durSeconds, playProgress, bTime, nTime = 0, buffInterval = null, tFlag = false, albums = ['Dawn','Me & You','Electro Boy','Home','Proxy (Original Mix)'], trackNames = ['Skylike - Dawn','Alex Skrindo - Me & You','Kaaze - Electro Boy','Jordan Schor - Home','Martin Garrix - Proxy'], albumArtworks = ['_1','_2','_3','_4','_5'], trackUrl = ['https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/2.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/1.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/3.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/4.mp3','https://raw.githubusercontent.com/himalayasingh/music-player-1/master/music/5.mp3'], playPreviousTrackButton = $('#play-previous'), playNextTrackButton = $('#play-next'), currIndex = -1;
function playPause()
{
setTimeout(function()
{
if(audio.paused)
{
playerTrack.addClass('active');
albumArt.addClass('active');
checkBuffering();
i.attr('class','fas fa-pause');
audio.play();
}
else
{
playerTrack.removeClass('active');
albumArt.removeClass('active');
clearInterval(buffInterval);
albumArt.removeClass('buffering');
i.attr('class','fas fa-play');
audio.pause();
}
},300);
}
function showHover(event)
{
seekBarPos = sArea.offset();
seekT = event.clientX - seekBarPos.left;
seekLoc = audio.duration * (seekT / sArea.outerWidth());
sHover.width(seekT);
cM = seekLoc / 60;
ctMinutes = Math.floor(cM);
ctSeconds = Math.floor(seekLoc - ctMinutes * 60);
if( (ctMinutes < 0) || (ctSeconds < 0) )
return;
if( (ctMinutes < 0) || (ctSeconds < 0) )
return;
if(ctMinutes < 10)
ctMinutes = '0'+ctMinutes;
if(ctSeconds < 10)
ctSeconds = '0'+ctSeconds;
if( isNaN(ctMinutes) || isNaN(ctSeconds) )
insTime.text('--:--');
else
insTime.text(ctMinutes+':'+ctSeconds);
insTime.css({'left':seekT,'margin-left':'-21px'}).fadeIn(0);
}
function hideHover()
{
sHover.width(0);
insTime.text('00:00').css({'left':'0px','margin-left':'0px'}).fadeOut(0);
}
function playFromClickedPos()
{
audio.currentTime = seekLoc;
seekBar.width(seekT);
hideHover();
}
function updateCurrTime()
{
nTime = new Date();
nTime = nTime.getTime();
if( !tFlag )
{
tFlag = true;
trackTime.addClass('active');
}
curMinutes = Math.floor(audio.currentTime / 60);
curSeconds = Math.floor(audio.currentTime - curMinutes * 60);
durMinutes = Math.floor(audio.duration / 60);
durSeconds = Math.floor(audio.duration - durMinutes * 60);
playProgress = (audio.currentTime / audio.duration) * 100;
if(curMinutes < 10)
curMinutes = '0'+curMinutes;
if(curSeconds < 10)
curSeconds = '0'+curSeconds;
if(durMinutes < 10)
durMinutes = '0'+durMinutes;
if(durSeconds < 10)
durSeconds = '0'+durSeconds;
if( isNaN(curMinutes) || isNaN(curSeconds) )
tProgress.text('00:00');
else
tProgress.text(curMinutes+':'+curSeconds);
if( isNaN(durMinutes) || isNaN(durSeconds) )
tTime.text('00:00');
else
tTime.text(durMinutes+':'+durSeconds);
if( isNaN(curMinutes) || isNaN(curSeconds) || isNaN(durMinutes) || isNaN(durSeconds) )
trackTime.removeClass('active');
else
trackTime.addClass('active');
seekBar.width(playProgress+'%');
if( playProgress == 100 )
{
i.attr('class','fa fa-play');
seekBar.width(0);
tProgress.text('00:00');
albumArt.removeClass('buffering').removeClass('active');
clearInterval(buffInterval);
}
}
function checkBuffering()
{
clearInterval(buffInterval);
buffInterval = setInterval(function()
{
if( (nTime == 0) || (bTime - nTime) > 1000 )
albumArt.addClass('buffering');
else
albumArt.removeClass('buffering');
bTime = new Date();
bTime = bTime.getTime();
},100);
}
function selectTrack(flag)
{
if( flag == 0 || flag == 1 )
++currIndex;
else
--currIndex;
if( (currIndex > -1) && (currIndex < albumArtworks.length) )
{
if( flag == 0 )
i.attr('class','fa fa-play');
else
{
albumArt.removeClass('buffering');
i.attr('class','fa fa-pause');
}
seekBar.width(0);
trackTime.removeClass('active');
tProgress.text('00:00');
tTime.text('00:00');
currAlbum = albums[currIndex];
currTrackName = trackNames[currIndex];
currArtwork = albumArtworks[currIndex];
audio.src = trackUrl[currIndex];
nTime = 0;
bTime = new Date();
bTime = bTime.getTime();
if(flag != 0)
{
audio.play();
playerTrack.addClass('active');
albumArt.addClass('active');
clearInterval(buffInterval);
checkBuffering();
}
albumName.text(currAlbum);
trackName.text(currTrackName);
albumArt.find('img.active').removeClass('active');
$('#'+currArtwork).addClass('active');
bgArtworkUrl = $('#'+currArtwork).attr('src');
bgArtwork.css({'background-image':'url('+bgArtworkUrl+')'});
}
else
{
if( flag == 0 || flag == 1 )
--currIndex;
else
++currIndex;
}
}
function initPlayer()
{
audio = new Audio();
selectTrack(0);
audio.loop = false;
playPauseButton.on('click',playPause);
sArea.mousemove(function(event){ showHover(event); });
sArea.mouseout(hideHover);
sArea.on('click',playFromClickedPos);
$(audio).on('timeupdate',updateCurrTime);
playPreviousTrackButton.on('click',function(){ selectTrack(-1);} );
playNextTrackButton.on('click',function(){ selectTrack(1);});
}
initPlayer();
});

Is there any way to replace text in ChromiumBrowser like Chrome already has?

I'm making a web editor application using CefSharp WinForms library, but I couldn't find a way to replace text from CefSharp API.
There is a find method in WebBrowserExtensions but no replace method.
Question 1:
Does anyone know where replacing text method is in CefSharp?
Or there is no way to replace text in CefSharp? If yes, I need to find a detour for it.
Question 2:
There are yellow blocks marked found words when I try Find method, but those blocks are not a part of selection range of window object in HTML. Are those blocks made by native not web browser?
Answer:
I made "find and replace" function by myself using javascript, so if someone tries to do something like me then you can use below codes:
var lastsearchedNodeIndex = -1;
var lastSearchedTextIndex = -1;
var lastRange = null;
function getTextLengthFromStartTo(targetNodeIndex) {
var childNodes = editor.childNodes;
var textLength = 0;
if (targetNodeIndex >= childNodes.length) {
return editor.textContent.length;
}
for (var i = 0; i < targetNodeIndex; i++) {
if (childNodes[i].textContent != null) {
textLength += childNodes[i].textContent.length;
}
}
return textLength;
}
function getCurrentCaretIndex() {
var currentCaretIndex = 0;
var doc = editor.ownerDocument || editor.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(editor);
preCaretRange.setEnd(range.endContainer, range.endOffset);
currentCaretIndex = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(editor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
currentCaretIndex = preCaretTextRange.text.length;
}
return currentCaretIndex;
}
function getCurrentNodeIndexAtCaret(caretIndex) {
if (caretIndex == 0) {
return 0;
}
var currentNodeIndex = -1;
for (var i = 0; i < editor.childNodes.length; i++) {
var frontTextLength = getTextLengthFromStartTo(i);
var backTextLength = getTextLengthFromStartTo(i + 1);
if (caretIndex > frontTextLength && caretIndex <= backTextLength) {
currentNodeIndex = i;
break;
}
}
return currentNodeIndex;
}
function getCurrentTextIndexInNodexAtCaret(nodeIndex, caretIndex) {
var textLength = getTextLengthFromStartTo(nodeIndex);
var textIndex = caretIndex - textLength;
return (textIndex < 0) ? 0 : textIndex;
}
function clearSelection() {
if (window.getSelection().rangeCount > 0) {
if (lastRange != null) {
window.getSelection().removeAllRanges();
lastRange.collapse(true);
window.getSelection().addRange(lastRange);
}
}
}
function getTextNodesIn(node) {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function setSelectionRange(el, start, end) {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(el);
var textNodes = getTextNodesIn(el);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount && (start < endCharCount || (start == endCharCount && i <= textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
lastRange = range;
sel.anchorNode.parentElement.scrollIntoView();
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd("character", end);
textRange.moveStart("character", start);
textRange.select();
}
}
function findText(text, caseSensitive) {
var currentCaretIndex = getCurrentCaretIndex();
clearSelection();
var regex;
if (caseSensitive) {
regex = text;
} else {
regex = new RegExp(text, "gi");
}
var childNodes = editor.childNodes;
var startNodeIndex = getCurrentNodeIndexAtCaret(currentCaretIndex);
var endNodeIndex = childNodes.length;
var startTextIndex = 0;
if (window.getSelection().focusOffset == 1) {
startTextIndex = lastSearchedTextIndex + 1;
} else {
startTextIndex = getCurrentTextIndexInNodexAtCaret(startNodeIndex, currentCaretIndex);
}
var searchedTextIndex = -1;
var searchedNodeIndex = 0;
var searchTargetSentence = null;
var searchLoopCount = 0;
if (currentCaretIndex == editor.textContent.length) {
startNodeIndex = 0;
startTextIndex = 0;
}
do
{
for (var i = startNodeIndex; i < endNodeIndex; i++) {
if (typeof (childNodes[i].textContent) == undefined || childNodes[i].textContent == null) {
startTextIndex = 0;
continue;
}
if (startTextIndex == childNodes[i].textContent.length) {
startTextIndex = 0;
continue;
}
if (startTextIndex > 0) {
searchTargetSentence = childNodes[i].textContent.substring(startTextIndex, childNodes[i].textContent.length);
} else {
searchTargetSentence = childNodes[i].textContent;
}
searchedTextIndex = searchTargetSentence.search(regex);
if (searchedTextIndex > -1) {
searchedTextIndex += startTextIndex;
searchedNodeIndex = i;
break;
}
startTextIndex = 0;
}
if (searchedTextIndex == -1) {
endNodeIndex = startNodeIndex + 1;
startNodeIndex = 0;
searchLoopCount++;
}
} while (searchLoopCount < 2 && searchedTextIndex == -1);
lastsearchedNodeIndex = searchedNodeIndex;
lastSearchedTextIndex = searchedTextIndex;
if (searchedNodeIndex > -1 && searchedTextIndex > -1) {
var textStartIndex = getTextLengthFromStartTo(searchedNodeIndex) + searchedTextIndex;
setSelectionRange(editor, textStartIndex, textStartIndex + text.length);
return true;
} else {
return false;
}
}
function replaceText(textToFind, textToReplace, caseSensitive) {
if (findText(textToFind, caseSensitive) == true) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(textToReplace));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = textToReplace;
}
return true;
} else {
return false;
}
}
There are no replace text method in CefSharp.
I think you have two options
Implement in javascript/html in the browser (DIY or something
like Tiny)
Manipulating the html from C# using GetSourceAsync and LoadHtml (Documentation)
Second question - I think you may be able to at least read the hits using the FindHandler. Have not tested this myself.

convert amount in words in angularjs

I need to convert amount in words. For example, the amount I will get it from service is 9876, I need to display in a table "Nine Thousand Eight Hundred and Seventy Six" in a table.
I need to do this using angularjs. Please help me how can I do this.
JSFIDDLE
function convertNumberToWords(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
}
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=convertNumberToWords(this.value)" />
<div id="word"></div>
I refered this javascript fiddle. But I want to it in a angularjs.
I used this for Angular 8.
Input : 123456789.09 Output : twelve crore thirty four lakh fifty six thousand seven eighty nine point zero nine
n: string;
a = ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
ngOnInit(): void {
console.log(this.inWords(123456789.09));
}
inWords (num): string {
num = Math.floor(num * 100);
if ((num = num.toString()).length > 11) { return 'overflow'; }
let n;
n = ('00000000' + num).substr(-11).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})(\d{1})(\d{1})$/);
if (!n) { return; } let str = '';
// tslint:disable-next-line:triple-equals
str += (n[1] != 0) ? (this.a[Number(n[1])] || this.b[n[1][0]] + ' ' + this.a[n[1][1]]) + 'crore ' : '';
// tslint:disable-next-line:triple-equals
str += (n[2] != 0) ? (this.a[Number(n[2])] || this.b[n[2][0]] + ' ' + this.a[n[2][1]]) + 'lakh ' : '';
// tslint:disable-next-line:triple-equals
str += (n[3] != 0) ? (this.a[Number(n[3])] || this.b[n[3][0]] + ' ' + this.a[n[3][1]]) + 'thousand ' : '';
// tslint:disable-next-line:triple-equals
str += (n[4] != 0) ? (this.a[Number(n[4])] || this.b[n[4][0]] + ' ' + this.a[n[4][1]]) : 'hundred';
// tslint:disable-next-line:triple-equals
str += (n[5]) ? (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' + this.a[n[5][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[6]) ? ((str != '') ? 'point ' : '') + (this.a[Number(n[6])] || this.b[n[6][0]] + ' ' + this.a[n[6][1]]) : '';
// tslint:disable-next-line:triple-equals
str += (n[7] != 0) ? (this.a[Number(n[7])] || this.b[n[7][0]] + ' ' + this.a[n[7][1]]) : '';
return str;
}
Define a filter to convert number to word such as following code:
angular.module('myModuleName')
.filter('convertToWord', function() {
return function(amount) {
var words = new Array();
words[0] = '';
words[1] = 'One';
words[2] = 'Two';
words[3] = 'Three';
words[4] = 'Four';
words[5] = 'Five';
words[6] = 'Six';
words[7] = 'Seven';
words[8] = 'Eight';
words[9] = 'Nine';
words[10] = 'Ten';
words[11] = 'Eleven';
words[12] = 'Twelve';
words[13] = 'Thirteen';
words[14] = 'Fourteen';
words[15] = 'Fifteen';
words[16] = 'Sixteen';
words[17] = 'Seventeen';
words[18] = 'Eighteen';
words[19] = 'Nineteen';
words[20] = 'Twenty';
words[30] = 'Thirty';
words[40] = 'Forty';
words[50] = 'Fifty';
words[60] = 'Sixty';
words[70] = 'Seventy';
words[80] = 'Eighty';
words[90] = 'Ninety';
amount = amount.toString();
var atemp = amount.split(".");
var number = atemp[0].split(",").join("");
var n_length = number.length;
var words_string = "";
if (n_length <= 9) {
var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
var received_n_array = new Array();
for (var i = 0; i < n_length; i++) {
received_n_array[i] = number.substr(i, 1);
}
for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
n_array[i] = received_n_array[j];
}
for (var i = 0, j = 1; i < 9; i++, j++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
if (n_array[i] == 1) {
n_array[j] = 10 + parseInt(n_array[j]);
n_array[i] = 0;
}
}
}
value = "";
for (var i = 0; i < 9; i++) {
if (i == 0 || i == 2 || i == 4 || i == 7) {
value = n_array[i] * 10;
} else {
value = n_array[i];
}
if (value != 0) {
words_string += words[value] + " ";
}
if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Crores ";
}
if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Lakhs ";
}
if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
words_string += "Thousand ";
}
if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
words_string += "Hundred and ";
} else if (i == 6 && value != 0) {
words_string += "Hundred ";
}
}
words_string = words_string.split(" ").join(" ");
}
return words_string;
};
});
Then in your templates (views) use this filter as follow:
{{amount | converToWord}}
For example to show inserted value in an input field:
<input type="text" name="number" placeholder="Number OR Amount" ng-model="myValue" />
<div id="word">{{myValue | convertToWord}}</div>

How to do numeric iterators in angularjs?

I have to convert Java code to angularjs ..In java i used while loop for numeric iterator something like below and in angularjs i tried ng-repeat but its not worked as loop sometime increase by +1 or +2 etc.Can someone please guide ho to do numeric iteration in angularjs?
int curretPos = 0;
String namePattern ="SOmeValue";
while (curretPos < namePattern.length()) {
String featureName = "";
if (Constants.namePatternformat.charAt(0) == namePattern.charAt(curretPos)
&& Constants.namePatternformat.charAt(1) == namePattern.charAt(curretPos + 1)) { // name pattern
curretPos = curretPos + 2;
int nextPos = namePattern.indexOf(Constants.namePatternformat.charAt(2), curretPos);
if (nextPos != -1) {
featureName = namePattern.substring(curretPos, nextPos);
curretPos = nextPos;
if (features.containsKey(featureName)) {
name = name.concat(String.valueOf(features.get(featureName)));
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else if (Constants.namePatternParent.charAt(0) == namePattern.charAt(curretPos)
&& (Character.toLowerCase(Constants.namePatternParent.charAt(1)) == Character.toLowerCase(namePattern.charAt(curretPos + 1)))) { // parent name pattern
if((namePattern.length() - curretPos) >= Constants.namePatternParent.length()) {
if (!Constants.namePatternParent.equals(namePattern.substring(curretPos, (curretPos+Constants.namePatternParent.length())))) {
throw SomeException;
}
}else{
throw SomeException;
}
curretPos = curretPos + (Constants.namePatternParent.length() - 1);
if(null != parent){
name = name.concat(parent);
}
} else if (Constants.namePatternIncrement.charAt(0) == namePattern.charAt(curretPos)
&& (Character.toLowerCase(Constants.namePatternIncrement.charAt(1)) == Character.toLowerCase(namePattern.charAt(curretPos + 1)))) { // increment name pattern
if((namePattern.length() - curretPos) > Constants.namePatternIncrement.length()) {
if (!Constants.namePatternIncrement.substring(0, 5).equals(namePattern.substring(curretPos, curretPos+5))) {
throw SomeException;
}
}else{
throw SomeException;
}
curretPos = curretPos + (Constants.namePatternIncrement.length() - 2) + 1;
int nextPos =
namePattern.indexOf(Constants.namePatternIncrement
.charAt(Constants.namePatternIncrement.length() - 1), curretPos);
if (nextPos != -1) {
featureName = namePattern.substring(curretPos, nextPos);
curretPos = nextPos;
if (features.containsKey(featureName)) {
if (null != features.get(featureName)
&& features.get(featureName).matches("^-?\\d+$")) {
int currentInstance = Integer.valueOf(features.get(featureName)) + (instance-1);
name = name.concat(String.valueOf(currentInstance));
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else {
name = name.concat(String.valueOf(namePattern.charAt(curretPos)));
}
curretPos = curretPos + 1;
}

Program built using Unity3D Freezing PC - Sporadic

My program that I built using Unity3D sporadically freezes, and this action freezes my computer. I'm unable to pinpoint the root cause. I had placed logs all over my project, but the game failed to freeze.
Has any Unity3D developer experience their apps sporadically freeze in the manner in which I am describing? Does anyone have any ideas or suggestions?
Due to a 30K character limit, the below object has been modified slightly. This is the object I believe contains a flaw, but I am unable to identify this flaw.
public class gamePlayController : MonoBehaviour {
void Start () {
int i = 0;
int selectedPlayers = PlayerPrefs.GetInt("TotalPlayers");
foreach( GameObject touchable in GameObject.FindGameObjectsWithTag("Touchable") )
{
touchable.SetActive(false);
touchable.AddComponent(typeof(PlayerCollisionDispatcher));
PlayerCollisionDispatcher nextDispatcher = touchable.GetComponent<PlayerCollisionDispatcher>();
nextDispatcher.currentGameObject = touchable;
nextDispatcher.gameObject.AddComponent("AudioSource");
for(i = 0; i < this.m_Players.Count; i++)
{
if(string.Compare(touchable.name, this.m_Players[i].name) < 0)
{
break;
}
}
if(i < this.m_Players.Count)
{
this.m_Players.Insert(i, touchable);
}
else
{
this.m_Players.Add(touchable);
}
}
while(this.m_Players.Count > selectedPlayers)
{
this.m_Players.RemoveRange(selectedPlayers, this.m_Players.Count - selectedPlayers);
}
this.restartGame();
}
void OnGameTimer(object sender, ElapsedEventArgs e)
{
}
void Update() {
Vector3 vector = m_ArialCamera.camera.transform.position;
vector.x = Mathf.Abs((1500 * this.m_ArialView.x) - 1500) + 250;
vector.y = (600 * this.m_ArialView.y) + 100;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
if(this.m_IsGameOver)
{
Application.LoadLevel("Replay Screen");
}
else if(this.m_SimulateCamera)
{
this.SimulateCamera();
}
else if(m_AutoPluck)
{
this.AutoPluck();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectStop)
{
this.determineTurnOutcome();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectMove)
{
this.m_Dispatcher.trackMovementProgress();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher
&& this.m_Players[this.m_PlayerIndex].rigidbody.velocity.magnitude > 15.0f
&& this.m_Dispatcher.didPluck)
{
this.m_Dispatcher.didObjectMove = true;
}
}
void restartGame()
{
this.m_PlayerIndex = -1;
foreach( GameObject touchable in this.m_Players)
{
GameObject startField = GameObject.FindWithTag ("StartField");
touchable.SetActive(false);
touchable.rigidbody.useGravity = false;
touchable.rigidbody.velocity = Vector3.zero;
touchable.rigidbody.AddForce(Vector3.zero);
touchable.rigidbody.AddTorque(Vector3.zero);
if(startField)
{
Vector3 nextPoint = startField.renderer.bounds.center;
nextPoint.y = 11.0f;
touchable.transform.position = nextPoint;
}
touchable.rigidbody.useGravity = true;
}
this.startNextPlayer();
}
void startNextPlayer()
{
bool isActivePlayerReady = true;
do{
if(this.m_PlayerIndex != -1)
{
audioPlayer.PlayAudio("Audio/Next Player");
}
this.m_PlayerIndex = (this.m_PlayerIndex + 1)%this.m_Players.Count;
this.m_Dispatcher = this.m_Players[this.m_PlayerIndex].GetComponent<PlayerCollisionDispatcher>();
if(this.m_Dispatcher && !this.m_Dispatcher.isGameOver && !this.m_Dispatcher.didEnterMud)
{
if(!this.m_Players[this.m_PlayerIndex].activeSelf)
{
this.m_Dispatcher.startGame();
this.m_Players[this.m_PlayerIndex].SetActive(true);
}
this.m_Dispatcher.startTurn();
}
}
while(!isActivePlayerReady);
Vector3 vector = this.m_Players[this.m_PlayerIndex].transform.position;
vector.x = (1500 * this.m_ArialView.x) + 250;
vector.y = 300;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
this.setAnnouncement("Player " + this.m_Players[this.m_PlayerIndex].name + "'s Turn");
if(this.m_PlayerIndex != 0)
{
this.m_IsSimulating = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
this.m_IsSimulating = 1;
}
else
{
this.m_IsSimulating = 0;
}
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
}
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
if(mo)
{
mo.DoFreeze = true;
}
}
else
{
if(mo)
{
mo.DoFreeze = false;
}
}
}
void StartSimulation()
{
System.Random random = new System.Random();
StringBuilder sb = new StringBuilder();
int randomNumber = 0;
//determine either the player object or the next block
if(this.m_Dispatcher.isKiller)
{
m_SimulateToObject = this.m_Players[randomNumber%this.m_Players.Count];
randomNumber = random.Next(0, 100);
}
else
{
sb.AppendFormat("{0:D2}", this.m_Dispatcher.targetScore);
Debug.Log("target score=" + sb.ToString());
foreach(GameObject scoreField in GameObject.FindGameObjectsWithTag("ScoreField"))
{
if(scoreField.name == sb.ToString())
{
m_SimulateToObject = scoreField;
break;
}
}
}
this.m_IsTargetInitiallyVisible = false;
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerCameraSimulation);
this.m_SimulationTimer.Interval=2500;
this.m_SimulationTimer.Enabled=true;
}
void TriggerCameraSimulation(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_SimulateCamera = true;
}
void SimulateCamera()
{
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
if(!this.m_IsTargetInitiallyVisible)
{
mo.IsManualMove = true;
mainCamera.transform.position = this.m_Players[this.m_PlayerIndex].transform.position;
mainCamera.transform.LookAt(this.m_SimulateToObject.transform, Vector3.up);
this.m_IsTargetInitiallyVisible = true;
}
else if(this.m_SimulateCamera)
{
if(mo.getDistance() >= 10.0f)
{
this.m_SimulateCamera = false;
}
mo.setDistance(-0.001f);
}
}
if(!this.m_SimulateCamera)
{
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerSimulatedPluck);
this.m_SimulationTimer.Interval=2000;
this.m_SimulationTimer.Enabled=true;
}
}
void TriggerSimulatedPluck(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_AutoPluck = true;
}
void AutoPluck()
{
System.Random random = new System.Random();
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
float applyForce = 0.0f;
float slope = 0.00028648399272739457f;
float y_int = 0.2908366193449838f;
Vector3 vTorque = Vector3.zero;
int simulateId = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
int seed = (5 * ((int)(SimulationOptions.Pro) - simulateId));
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
int sign = random.Next(1, 1000)%2;
int range = random.Next(1, 1000)%seed;
int myValue = 0;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
mo.IsManualMove = false;
}
this.m_AutoPluck = false;
if(simulateId >= 1)
{
float distance = Vector3.Distance(this.m_Players[this.m_PlayerIndex].transform.position,
this.m_SimulateToObject.transform.position);
if(simulateId != (int)(SimulationOptions.Pro))
{
myValue = random.Next(1, 6);
seed = (int)(myValue * ((int)(SimulationOptions.Pro) - simulateId));
sign = random.Next(1, 2);
range = random.Next(1, seed);
if(random.Next(1, 1000)%3 == 0)
{
distance += (sign == 1 ? range : -range);
}
}
vTorque.x = (float)(random.Next(1, 90));
vTorque.y = (float)(random.Next(1, 90));
vTorque.z = (float)(random.Next(1, 90));
applyForce = (slope * distance) + y_int;
this.m_Dispatcher.pluckObject(applyForce, vTorque);
}
}
void determineTurnOutcome()
{
int number = -1;
bool canActivePlayerContinue = false;
bool isAutoReward = false;
bool didElinimatePlayer = false;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(nextObject.activeSelf && !nextDispatcher.isGameOver && !nextDispatcher.isActive)
{
if(nextDispatcher.currentScore == nextDispatcher.targetScore)
{
nextDispatcher.totalScore = nextDispatcher.targetScore;
int.TryParse(nextDispatcher.name, out number);
nextDispatcher.targetScore++;
if(nextDispatcher.totalScore >= 13 || nextDispatcher.targetScore > 13)
{
nextDispatcher.totalScore = 13;
nextDispatcher.targetScore = 13;
nextDispatcher.isKiller = true;
this.setMaterial(nextDispatcher.renderer, "killers", nextDispatcher.name);
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
else if(nextDispatcher.didKillerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
this.setMaterial(nextDispatcher.renderer, "eliminated", nextDispatcher.name);
nextDispatcher.isGameOver = true;
didElinimatePlayer = true;
}
else if(nextDispatcher.didPlayerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
if(int.TryParse(nextDispatcher.name, out number))
{
nextDispatcher.targetScore = 1;
nextDispatcher.totalScore = 0;
}
}
else if(nextDispatcher.didEnterMud)
{
this.setMaterial(nextDispatcher.renderer, "mudd", nextDispatcher.name);
nextDispatcher.isKiller = false;
}
else if(nextDispatcher.isInMud && !nextDispatcher.didEnterMud)
{
isAutoReward = true;
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
nextDispatcher.transferStates();
}
if(this.m_Dispatcher.isKiller && !didElinimatePlayer)
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
this.m_Dispatcher.totalScore = 0;
this.m_Dispatcher.targetScore = 1;
this.m_Dispatcher.isKiller = false;
}
else if(this.m_Dispatcher.didEnterMud)
{
this.setMaterial(this.m_Dispatcher.renderer, "mud", this.m_Dispatcher.name);
}
else if(this.m_Dispatcher.currentScore == this.m_Dispatcher.targetScore || isAutoReward)
{
this.m_Dispatcher.totalScore = this.m_Dispatcher.targetScore;
canActivePlayerContinue = true;
this.m_Dispatcher.consecutivePops++;
int.TryParse(this.m_Dispatcher.name, out number);
this.m_Dispatcher.targetScore++;
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
else
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
this.isWinnerAnnounced();
if(!this.m_IsGameOver && !canActivePlayerContinue)
{
this.m_Dispatcher.endTurn();
this.startNextPlayer();
}
else if(canActivePlayerContinue)
{
this.m_Dispatcher.transferStates();
this.m_Dispatcher.isActive = true;
this.m_Dispatcher.didObjectMove = false;
this.m_Dispatcher.didObjectStop = false;
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
}
}
this.m_ForceValue = 0.0f;
}
void isWinnerAnnounced()
{
StringBuilder sb = new StringBuilder();
int totalPlayers = 0;
string winner = string.Empty;
int number = -1;
int totalPlayersInMud = 0;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(!nextDispatcher.isGameOver)
{
totalPlayers++;
winner = nextObject.name;
}
if(nextDispatcher.isInMud)
{
totalPlayersInMud++;
}
}
if(totalPlayers == 1)
{
if(winner != string.Empty && int.TryParse(winner, out number))
{
sb.AppendFormat("Congratulations Player {0}", number);
PlayerPrefs.SetString("WinningPlayer", sb.ToString());
}
else
{
PlayerPrefs.SetString("WinningPlayer", "Congratulations");
}
this.m_IsGameOver = true;
}
else if(totalPlayersInMud == this.m_Players.Count)
{
PlayerPrefs.SetString("WinningPlayer", "All players are stuck in the mud!");
this.m_IsGameOver = true;
}
}
void setMaterial(Renderer renderer, string state, string playerId)
{
StringBuilder sbNextImage = new StringBuilder();
sbNextImage.AppendFormat("Materials/playerObjects/{0}/{1}", state, playerId);
Material newMat = Resources.Load(sbNextImage.ToString(), typeof(Material)) as Material;
if(newMat)
{
renderer.material = newMat;
}
else
{
Debug.Log("FAILED to set material: " + sbNextImage.ToString());
}
}
void setAnnouncement(string text)
{
this.m_IsAnnouncement = true;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
this.m_AnnouncementText = text;
}
void OnGUI() {
GUIStyle labelStyle = GUI.skin.label;
int number = -1;
StringBuilder scoreDetails = new StringBuilder();
StringBuilder turnDetails = new StringBuilder();
float x = 0;
float y = 0;
float w = 64.0f;
float h = 32.0f;
float alpha = 1.0f;
if(this.m_IsAnnouncement)
{
this.displayAnnouncement();
}
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();
labelStyle.normal.background = texture;
if(this.m_DoShowScore)
{
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
int.TryParse(nextDispatcher.name, out number);
if(nextDispatcher.isGameOver)
{
scoreDetails.AppendFormat("\tPlayer {0}: Game Over\n", number);
}
else if(nextDispatcher.didEnterMud)
{
scoreDetails.AppendFormat("\tPlayer {0}: In The Mudd\n", number);
}
else if(nextDispatcher.isKiller)
{
scoreDetails.AppendFormat("\tPlayer {0}: Killer\n", number);
}
else
{
scoreDetails.AppendFormat("\tPlayer {0}: {1}\n", number, nextDispatcher.totalScore);
}
}
GUI.Label (new Rect (0, 0, 225, 100), scoreDetails.ToString());
}
w = 64.0f;
h = 32.0f;
x = Screen.width - w;
y = Screen.height - h;
if(GUI.Button (new Rect (x, y, w, h), "Menu"))
{
audioPlayer.PlayAudio("Audio/Click");
this.m_IsMenuShowing = !this.m_IsMenuShowing;
}
if(this.m_IsMenuShowing)
{
w = (64.0f * this.m_MenuText.Length);
h = 32.0f;
x = Screen.width - w - 64.0f;
y = Screen.height - h;
int selOption = GUI.Toolbar(new Rect(x, y, w, h), this.m_MenuOption, this.m_MenuText);
if(selOption != this.m_MenuOption)
{
audioPlayer.PlayAudio("Audio/Click");
this.m_MenuOption = -1;
this.m_IsMenuShowing = !this.m_IsMenuShowing;
switch(selOption)
{
case (int)(MenuOptions.ArialViewOption): //arial
this.m_ArialCamera.SetActive(!this.m_ArialCamera.activeSelf);
break;
case (int)(MenuOptions.VolumeOption): //mute
int muteVolume = PlayerPrefs.GetInt("MuteVolume");
muteVolume = (muteVolume + 1)%2;
PlayerPrefs.SetInt("MuteVolume", muteVolume);
if(muteVolume == 0)
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Mute";
}
else
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Volume";
}
break;
case (int)(MenuOptions.PauseOption): //pause
if(Time.timeScale == 0.0f)
{
this.setAnnouncement("Continuing Game Play");
Time.timeScale = this.m_Speed;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Pause";
}
else
{
this.setAnnouncement("Game Is Paused");
Time.timeScale = 0.0f;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Play";
}
break;
case (int)(MenuOptions.ScoresOption): //scores
this.m_DoShowScore = !this.m_DoShowScore;
break;
case (int)(MenuOptions.RestartOption): //restart
Time.timeScale = this.m_Speed;
this.restartGame();
break;
case (int)(MenuOptions.QuitOption): //quit
Application.LoadLevel("Opening Screen");
break;
default:
break;
}
}
}
if(this.m_ArialCamera.activeSelf)
{
x = Screen.width * 0.7f - 10.0f;
y = 0;
w = 10.0f;
h = Screen.height * 0.3f;
this.m_ArialView.z = GUI.VerticalSlider (new Rect(x, y, w, h), this.m_ArialView.z, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.x = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.x, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f + 12.0f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.y = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.y, 1.0f, 0.0f);
}
int.TryParse(this.m_Players[this.m_PlayerIndex].name, out number);
turnDetails.AppendFormat("\tPlayer {0}'s Turn\n", number);
turnDetails.AppendFormat("\tNext Goal: {0}\n", this.m_Dispatcher.targetScore);
GUI.Label (new Rect (0, Screen.height - 100, 225, 100), turnDetails.ToString());
if(!this.m_Dispatcher.didObjectMove && m_IsSimulating == 0)
{
x = 250.0f;
y = Screen.height - 190.0f;
w = 30.0f;
h = 150.0f;
this.m_ForceValue = GUI.VerticalSlider (new Rect(x, y, w, h), m_ForceValue, 1.0f, 0.0f);
x = 250.0f;
y = Screen.height - 30.0f;
w = 100.0f;
h = 30.0f;
if(GUI.Button (new Rect(x, y, w, h), "Pluck!"))
{
System.Random random = new System.Random();
Vector3 vTorque = Vector3.zero;
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
xSeed = (random.Next(1, 45));
ySeed = (random.Next(1, 45));
zSeed = (random.Next(1, 45));
vTorque = new Vector3(xSeed, ySeed, zSeed);
this.m_Dispatcher.pluckObject(this.m_ForceValue, vTorque);
}
}
}
void displayAnnouncement()
{
float x = 0;
float y = 0;
float w = 0;
float h = 0;
float alpha = 1.0f;
GUIStyle announcementStyle = null;
GUIStyle labelStyle = null;
announcementStyle = new GUIStyle();
labelStyle = GUI.skin.label;
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
x = (int)(Screen.width * 0.25);
y = (int)m_AnnouncementHeight;
w = (int)(Screen.width * 0.5);
h = 100;
alpha = (float)m_AnnouncementHeight/(float)(Screen.height * 0.5);
announcementStyle.fontSize = 32;
announcementStyle.alignment = TextAnchor.MiddleCenter;
announcementStyle.fontStyle = FontStyle.BoldAndItalic;
announcementStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
GUI.Label (new Rect (x, y, w, h), this.m_AnnouncementText, announcementStyle);
if(Time.timeScale != 0.0f)
{
if((this.m_AnnouncementHeight + h) <= 0)
{
this.m_IsAnnouncement = false;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
}
else
{
this.m_AnnouncementHeight -= 1;
}
}
}
}
-----------
I believe I have narrowed the freezing down. Simulated testing results is leading me to believe that my problem is inside the OnGUI() method. I have commented that method out all together, and my app is operating smoothly. I'll figure this out, unless someone beats me to the root cause and solution.
I solved it...
My initial suspicions were correct: the problem did lie within the OnGUI() method. I moved the following source code to the Start() method. It made sense, since I'm only building a transparent background texture once.:
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();

Resources