Search Results

Search found 15634 results on 626 pages for 'foreach loop container'.

Page 9/626 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Loop over array and set all vars to false or true in javascript

    - by Sixfoot Studio
    Hi All, I need to loop over my array and set all the vars to false or true. I have tried numerous options, none of which are working and it's clearly my lack of javascript syntax knowledge..Please take a look at this: var closeAllCells = [IncomeOpen = "false", RehabOpen = "false", AttendantCareOpen = "false", HomeMaintenanceOpen = "false", DependantCareOpen = "false", IndexationOpen = "false", DeathFuneralOpen = "false", ComprehensiveOpen = "false", CollisionOpen = "false", LiabilityOpen = "false", DCPDOpen = "false"]; So my thinking is that I can just loop over this as follows for (var i=0;i<closeAllCells.length;i++) { closeAllCells[i] = true; // or false if I wished }

    Read the article

  • Python how to convert this for loop into a while loop

    - by user1690198
    I have this for a for loop which I made I was wondering how I would write so it would work with a while loop. def scrollList(myList): negativeIndices=[] for i in range(0,len(myList)): if myList[i]<0: negativeIndices.append(i) return negativeIndices So far I have this def scrollList2(myList): negativeIndices=[] i= 0 length= len(myList) while i != length: if myList[i]<0: negativeIndices.append(i) i=i+1 return negativeIndices

    Read the article

  • How to Loop through LINQ results (VB.NET)

    - by rockinthesixstring
    I've got some code to try and loop through LINQ results, but it doesn't seem to be working. HERE'S THE CODE Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest ' the page contenttype is plain text' HttpContext.Current.Response.ContentType = "text/plain" ' store the querystring as a variable' Dim qs As Nullable(Of Integer) = Integer.TryParse(HttpContext.Current.Request.QueryString("ID"), Nothing) ' use the RegionsDataContext' Using RegionDC As New DAL.RegionsDataContext 'create a (q)uery variable' Dim q As Object ' if the querystring PID is not blank' ' then we want to return results based on the PID' If Not qs Is Nothing Then ' that fit within the Parent ID' q = (From r In RegionDC.bt_Regions _ Where r.PID = qs _ Select r.Region).ToArray ' now we loop through the array' ' and write out the ressults' For Each item As DAL.bt_Region In q HttpContext.Current.Response.Write(item.Region & vbCrLf) Next End If End Using End Sub HERE'S THE ERROR Public member 'Region' on type 'String' not found. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMemberException: Public member 'Region' on type 'String' not found. Source Error: Line 33: ' and write out the ressults Line 34: For Each item In q Line 35: HttpContext.Current.Response.Write(item.Region & vbCrLf) Line 36: Next Line 37: Source File: E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb Line: 35 Stack Trace: [MissingMemberException: Public member 'Region' on type 'String' not found.] Microsoft.VisualBasic.CompilerServices.Container.GetMembers(String& MemberName, Boolean ReportErrors) +509081 Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) +222 BT.Handlers.RegionsAutoComplete.ProcessRequest(HttpContext context) in E:\Projects\businesstrader\App_Code\Handlers\RegionsAutoComplete.vb:35 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 Can anyone tell me what I'm doing wrong?

    Read the article

  • Java For-Each Loop to Deal to multiple Hands

    - by qwertyRocker
    I'm trying to find a good way to 'deal' cards to 4 difference hands. System.out.println("Deal to 4 Hands: "); Hand hand1 = new Hand(); Hand hand2 = new Hand(); Hand hand3 = new Hand(); Hand hand4 = new Hand(); hand1.addSingleCard(Deck.deal()); hand2.addSingleCard(Deck.deal()); hand3.addSingleCard(Deck.deal()); hand4.addSingleCard(Deck.deal()); hand1.addSingleCard(Deck.deal()); hand2.addSingleCard(Deck.deal()); hand3.addSingleCard(Deck.deal()); hand4.addSingleCard(Deck.deal()); System.out.println("Cards left in deck: " + Deck.size()); System.out.println("Player 1's Hand: \n" + hand1.getHand()); System.out.println("Player 2's Hand: \n" + hand2.getHand()); System.out.println("Player 3's Hand: \n" + hand3.getHand()); System.out.println("Player 4's Hand: \n" + hand4.getHand()); Is there an easier way to deal to hands? For example using a For-Each loop? I tried this: but it doesn't work. I haven't really used this type of loop very must... for(Hand card : hand1){ System.out.println("Player 1's Hand: \n" + hand1); } By the way, this deals 2 cards to 4 difference hands, then prints each hand.

    Read the article

  • Sum Values in Multidimensional Array

    - by lemonpole
    Hello all. I'm experimenting with arrays in PHP and I am setting up a fake environment where a "team's" record is held in arrays. $t1 = array ( "basicInfo" => array ( "The Sineps", "December 25, 2010", "lemonpole" ), "overallRecord" => array ( 0, 0, 0, 0 ), "overallSeasons" => array ( "season1.cs" => array (0, 0, 0), "season2.cs" => array (0, 0, 0) ), "matches" => array ( "season1.cs" => array ( "week1" => array ("12", "3", "1"), "week2" => array ("8", "8" ,"0"), "week3" => array ("8", "8" ,"0") ), "season2.cs" => array ( "week1" => array ("9", "2", "5"), "week2" => array ("12", "2" ,"2") ) ) ); What I am trying to achieve is to add all the wins, loss, and draws, from each season's week to their respective week. So for example, the sum of all the weeks in $t1["matches"]["season1.cs"] will be added to $t1["overallSeasons"]["season1.cs"]. The result would leave: "overallSeasons" => array ( "season1.cs" => array (28, 19, 1), "season2.cs" => array (21, 4, 7) ), I tried to work this out on my own for the past hour and all I have gotten is a little more knowledge of for-loops and foreach-loops :o... so I think I now have the basics down such as using foreach loops and so on; however, I am still fairly new to this so bear with me! I can get the loop to point to $t1["matches"] key and go through each season but I can't seem to figure out how to add all of the wins, loss, and draw, for each individual week. For now, I'm only looking for answers concerning the overall seasons sum since I can work from there once I figure out how to achieve this. Any help will be much appreciated but please, try and keep it simple for me... or comment the code accordingly please! Thanks!

    Read the article

  • friendship and operator overloading help

    - by sil3nt
    hello there, I have the following class #ifndef Container_H #define Container_H #include <iostream> using namespace std; class Container{ friend bool operator==(const Container &rhs,const Container &lhs); public: void display(ostream & out) const; private: int sizeC; // size of Container int capacityC; // capacity of dynamic array int * elements; // pntr to dynamic array }; ostream & operator<< (ostream & out, const Container & aCont); #endif and this source file #include "container.h" /*----------------------------********************************************* note: to test whether capacityC and sizeC are equal, must i add 1 to sizeC? seeing as sizeC starts off with 0?? */ Container::Container(int maxCapacity){ capacityC = maxCapacity; elements = new int [capacityC]; sizeC = 0; } Container::~Container(){ delete [] elements; } Container::Container(const Container & origCont){ //copy constructor? int i = 0; for (i = 0; i<capacityC; i++){ //capacity to be used here? (*this).elements[i] = origCont.elements[i]; } } bool Container::empty() const{ if (sizeC == 0){ return true; }else{ return false; } } void Container::insert(int item, int index){ if ( sizeC == capacityC ){ cout << "\n*** Next: Bye!\n"; return; // ? have return here? } if ( (index >= 0) && (index <= capacityC) ){ elements[index] = item; sizeC++; } if ( (index < 0) && (index > capacityC) ){ cout<<"*** Illegal location to insert--"<< index << ". Container unchanged. ***\n"; }//error here not valid? according to original a3? have i implemented wrong? } void Container::erase(int index){ if ( (index >= 0) && (index <= capacityC) ){ //correct here? legal location? int i = 0; while (i<capacityC){ //correct? elements[index] = elements[index+1]; //check if index increases here. i++; } sizeC=sizeC-1; //correct? updated sizeC? }else{ cout<<"*** Illegal location to be removed--"<< index << ". Container unchanged. ***\n"; } } int Container::size()const{ return sizeC; //correct? } /* bool Container::operator==(const Container &rhs,const Container &lhs){ int equal = 0, i = 0; for (i = 0; i < capacityC ; i++){ if ( rhs.elements[i] == lhs.elements[i] ){ equal++; } } if (equal == sizeC){ return true; }else{ return false; } } ostream & operator<< (ostream & out, const Container & aCont){ int i = 0; for (i = 0; i<sizeC; i++){ out<< aCont.elements[i] << " " << endl; } } */ I dont have the other functions in the header file (just a quikie). Anyways, the last two functions in "/* */" I cant get to work, what am I doing wrong here? the first function is to see whether the two arrays are equal to one another

    Read the article

  • dynamic naming of UIButtons within a loop - objective-c, iphone sdk

    - by von steiner
    Dear Members, Scholars. As it may seem obvious I am not armed with Objective C knowledge. Levering on other more simple computer languages I am trying to set a dynamic name for a list of buttons generated by a simple loop (as the following code suggest). Simply putting it, I would like to have several UIButtons generated dynamically (within a loop) naming them dynamically, as well as other related functions. button1,button2,button3 etc.. After googling and searching Stackoverlow, I haven't arrived to a clear simple answer, thus my question. - (void)viewDidLoad { // This is not Dynamic, Obviously UIButton *button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button0 setTitle:@"Button0" forState:UIControlStateNormal]; button0.tag = 0; button0.frame = CGRectMake(0.0, 0.0, 100.0, 100.0); button0.center = CGPointMake(160.0,50.0); [self.view addSubview:button0]; // I can duplication the lines manually in terms of copy them over and over, changing the name and other related functions, but it seems wrong. (I actually know its bad Karma) // The question at hand: // I would like to generate that within a loop // (The following code is wrong) float startPointY = 150.0; // for (int buttonsLoop = 1;buttonsLoop < 11;buttonsLoop++){ NSString *tempButtonName = [NSString stringWithFormat:@"button%i",buttonsLoop]; UIButton tempButtonName = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [tempButtonName setTitle:tempButtonName forState:UIControlStateNormal]; tempButtonName.tag = tempButtonName; tempButtonName.frame = CGRectMake(0.0, 0.0, 100.0, 100.0); tempButtonName.center = CGPointMake(160.0,50.0+startPointY); [self.view addSubview:tempButtonName]; startPointY += 100; } }

    Read the article

  • Loop with a while

    - by ookla
    Very basic question.. but I'm missing the point.. I have this data on my table: ID SITEID SECTION 1 1 posts 2 2 posts 3 1 aboutme 4 1 contact 5 2 questions The output is an array. I can't change it. I want to make this output on php with a single for loop with that array: <h1> sections for site 1 </h1> posts aboutme contact <h1>sections for site 2 </h1> posts questions I'm trying to do something like this, where $sectionsArray is my output. And I want to check if siteid is the same, then make a loop.. for ($j=0;$j<sizeof($sectionsArray);$j++) { while (siteid==1){ echo "<h1>'.$sectionsArray['siteid'].'</h1>'; } echo "<A href='section.php?id='.$sectionsArray['id'].' '">'.$sectionsArray['section'].'</a>; } But I don't get the logic of "grouping" the results with a while.. INSIDE a loop. Any light will be welcome. Thanks

    Read the article

  • Text Hints with JQuery and JavaScript for loop

    - by lpdahito
    Hey guys! I'm developing a small app where i ask users to put some info. I want to show text hints in the input fields. I do this in a for loop... When the page is loaded, the hints are displayed correctly but nothing happens on 'focus' and 'blur' events... I'm wondering why since when I don't use a 'for loop' in my js code, everything works find... By the way the reason I use a for loop is because I don't want to repeat myself following 'DRY' principles... Thx for your help! LP Here's the code: <script src="/javascripts/jquery.js" type="text/javascript"></script> <script type="text/javascript"> var form_elements = ['#submission_url', '#submission_email', '#submission_twitter'] var text_hints = ['Website Address', 'Email Address', 'Twitter Username (optional)'] $(document).ready(function(){ for(i=0; i<3; i++) { $(form_elements[i]).val(text_hints[i]); $(form_elements[i]).focus(function(i){ if ($(this).val() == text_hints[i]) { $(this).val(''); } }); $(form_elements[i]).blur(function(i){ if ($(this).val() != text_hints[i]) { $(this).val(text_hints[i]); } }); } }); </script>

    Read the article

  • Basic syntax for an animation loop?

    - by Moshe
    I know that jQuery, for example, can do animation of sorts. I also know that at the very core of the animation, there must me some sort of loop doing the animation. What is an example of such a loop? A complete answer should ideally answer the following questions: What is a basic syntax for an effective animation recursion that can animate a single property of a particular object at a time? The function should be able to vary its target object and property of the object. What arguments/parameters should it take? What is a good range of reiterating the loop? In milliseconds? (Should this be a parameter/argument to the function?) REMEMBER: The answer is NOT necessarily language specific, but if you are writing in a specific language, please specify which one. Error handling is a plus. {Nothing is more irritating (for our purposes) than an animation that does something strange, like stopping halfway through.} Thanks!

    Read the article

  • Having a different action for each button dynamically created in a loop

    - by Oliver
    Hi, use this website a lot but first time posting. My program creates a number of buttons depending on the number of records in a file. E.g. 5 records, 5 buttons. The buttons are being created but i'm having a problem with the action listener. If add the action listener in the loop every button does the same thing; but if I add the action listener outside the loop it just adds the action listener to last button. Any ideas? Here is what I have code-wise (I've just added the for loop to save space): int j=0; for(int i=0; i<namesA.size(); i++) { b = new JButton(""+namesA.get(i)+""); conPanel.add(b); conFrame.add(conPanel); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae2){ System.out.println(namesA.get(j)); } }}); j++; } Much Appreciated

    Read the article

  • Python: For loop problem

    - by James
    I have a PSP page with html embedded. I need to place another for loop so i can insert another %s next to background-color: which will instert a appropriate colour to colour in the html table. For example i need to insert for z in colours so it can loop over the colours list and insert the correct colour. Where ever i try to insert the for loop it doesnt seem to work it most commonly colours each cell in the table 60 times then moves onto the next cell and repeats itself and crashes my web browser. The colours are held in a table called colours. code below: <table> <% s = ''.join(aa[i] for i in table if i in aa) for i in range(0, len(s), 60): req.write('<tr><td><TT>%04d</td>' % (i+1)); for k in s[i:i+60]: req.write('<TT><td><TT><font style="background-color:">%s<font></td>' % (k)); req.write('</TT></tr>') #end %> </table>

    Read the article

  • Problem with for-loop in python

    - by Protean
    This code is supposed to be able to sort the items in self.array based upon the order of the characters in self.order. The method sort runs properly until the third iteration, unil for some reason the for loop seems to repeat indefinitely. What is going on here? class sorting_class: def __init__(self): self.array = ['ca', 'bd', 'ac', 'ab'] #An array of strings self.arrayt = [] self.globali = 0 self.globalii = 0 self.order = ['a', 'b', 'c', 'd'] #Order of characters self.orderi = 0 self.carry = [] self.leave = [] self.sortedlist = [] def sort(self): for arrayi in self.arrayt: #This should only loop for the number items in self.arrayt. However, the third time this is run it seems to loop indefinitely. print ('run', arrayi) #Shows the problem if self.order[self.orderi] == arrayi[self.globali]: self.carry.append(arrayi) else: if self.globali != 0: self.leave.append(arrayi) def srt(self): self.arrayt = self.array my.sort() #First this runs the first time. while len(self.sortedlist) != len(self.array): if len(self.carry) == 1: self.sortedlist.append(self.carry) self.arrayt = self.leave self.leave = [] self.carry = [] self.globali = 1 self.orderi = 0 my.sort() elif len(self.carry) == 0: if len(self.leave) != 0: #Because nothing matches 'aa' during the second iteration, this code runs the third time" self.arrayt = self.leave self.globali = 1 self.orderi += 1 my.sort() else: self.arrayt = self.array self.globalii += 1 self.orderi = self.globalii self.globali = 0 my.sort() self.orderi = 0 else: #This is what runs the second time. self.arrayt = self.carry self.carry = [] self.globali += 1 my.sort() my = sorting_class() my.srt()

    Read the article

  • using a While loop to control the value of a keyframe in a timeline in Javafx

    - by dragoknight
    i want to create an animation where the ball will move in one of the 4 sectors of a circle randomly.this will happen 5 times.so,i create a while loop(i<5) and call the random function.i then create an if loop and attach some x and y values according to the random fn value.i then create an timeline object inside the while loop and in the key frame value,i use these x and y values.but when i run the program,what happens is that all the values are being created(x and y values seen through println) but only the last x and y value(for i=5)is being rendered in the screen.the animations for the previous values(1<=i<=4)are not being rendered.Please advise where have i gone wrong? public function run(args:String[]) { var i=0; while(i<5) { var z=gety(); println(z); // var relativeTime:Duration=0s; if(z==1) {xbind=120; ybind=80; } else if(z==2) {xbind=120; ybind=120; } else if(z==3) { xbind=80; ybind=120; } else if(z==4) { xbind=80; ybind=80; } var t:Timeline=Timeline{ //time: bind pos with inverse; repeatCount: Timeline.INDEFINITE autoReverse: true keyFrames: [ KeyFrame{ time: 0s values: [ x => 100.0,y => 100.0]}, KeyFrame{time: 2s values:[x => xbind tween Interpolator.LINEAR, y => ybind tween Interpolator.LINEAR,] }, ] }//end timeline i++; t.play(); Thread.sleep(2000); }//end while }

    Read the article

  • Internal loop only runs once, containing loop runs endlessly

    - by Mark
    noob question I'm afraid. I have a loop that runs and rotates the hand of a clock and an internal loop that checks the angle of the hand if it is 90, 180, 270 and 360. On these 4 angles the corresponding div is displayed and its siblings removed. The hand loops and loops eternally, which is what I want, but the angle check only runs the loop once through the whole 360. As the hand passes through the angles it is correctly displaying and removing divs but is doesn't continue after the first revolution of the clock. I've obviously messed up somewhere and there is bound to be a more efficient way of doing all this. I am using jQueryRotate.js for my rotations. Thanks for your time. jQuery(document).ready(function(){ var angle = 0; setInterval(function(){ jQuery("#hand").rotate(angle); function movehand(){ if (angle == 90) { jQuery("#intervention").fadeIn().css("display","block").siblings().css("display","none"); } else if (angle == 180) { jQuery("#management").fadeIn().css("display","block").siblings().css("display","none"); } else if (angle == 270) { jQuery("#prevention").fadeIn().css("display","block").siblings().css("display","none"); } else if (angle == 360) { jQuery("#reaction").fadeIn().css("display","block").siblings().css("display","none"); } else {movehand;} }; movehand(); angle+=1; },10); });

    Read the article

  • How to parse (infinite) nested object notation?

    - by kyogron
    I am currently breaking my head about transforming this object hash: "food": { "healthy": { "fruits": ['apples', 'bananas', 'oranges'], "vegetables": ['salad', 'onions'] }, "unhealthy": { "fastFood": ['burgers', 'chicken', 'pizza'] } } to something like this: food:healthy:fruits:apples food:healthy:fruits:bananas food:healthy:fruits:oranges food:healthy:vegetables:salad food:healthy:vegetables:onions food:unhealthy:fastFood:burgers food:unhealthy:fastFood:chicken food:unhealthy:fastFood:pizza In theory it actually is just looping through the object while keeping track of the path and the end result. Unfortunately I do not know how I could loop down till I have done all nested. var path; var pointer; function loop(obj) { for (var propertyName in obj) { path = propertyName; pointer = obj[propertyName]; if (pointer typeof === 'object') { loop(pointer); } else { break; } } }; function parse(object) { var collection = []; }; There are two issues which play each out: If I use recurse programming it looses the state of the properties which are already parsed. If I do not use it I cannot parse infinite. Is there some idea how to handle this? Regards

    Read the article

  • How to approach ninject container/kernel in inheritance situation

    - by Bas
    I have the following situation: class RuleEngine {} abstract class RuleImplementation {} class RootRule : RuleImplementation {} class Rule1 : RuleImplementation {} class Rule2 : RuleImplementation {} The RuleEngine is injected by Ninject and has a kernel at it's disposal, the role of the RuleEngine is to fire off the root rule, which on it's turn will load all the other rules also using Ninject, but using a different Module and creating a new Kernel. Now my question is, some of the rules require some dependencies which I want to inject using Ninject. What would be the best way to create the kernel for these rules and also still do proper unit testing with it? (the kernel shouldn't become a real pain in my tests) I've been thinking of the following possibilitys: The kernel that I use in the RuleEngine class could be tossed around to RuleImplementation and thus be available for every rule. But tossing around Kernels isn't really something I wish to do. When creating the rules, I could give the kernel (which creates the rules) as a constructor argument for each rule. I could create a method inside the RuleImplementation which creates a kernel and makes it possible for the rules to retrieve the kernel using a get() in the abstract class Whats the convention of passing around/creating kernels? Just create new kernels, or reuse them?

    Read the article

  • How to make sure the value is reset in foreach loop in PHP

    - by kwokwai
    Hi all, I was writing a simple PHP page and a few foreach loops were used. Here are the scripts: $arrs = array("a", "b", "c"); foreach ($arrs as $arr) { if(substr($arr,0,1)=="b") { echo "This is b"; } } // ends of first foreach loop and I didn't use ifelse here And when this foreach ends, I wrote another foreach loop in which all the values in the foreach loop was the same as previous foreach. foreach ($arrs as $arr) { if(substr($arr,0,1)=="c") { echo "This is c"; } } I am not sure if it is a good practice to have two foreach loops with same values and keys. Will the values get overwritten in the first foreach loop?

    Read the article

  • How could I easily pack a directory to an ext4 loop partition image?

    - by Alvin Wong
    I would like to pack the content of a directory into an ext4 partition image easily, without mounting a loop device. Background: I am building a version of Android which will mount system partitions as a loop device for ARM. Though I can create those partition images by hand using loop devices, it is very troublesome. I want to use an sh script to automatically do the work, and without needing to loop mount the dd-created image and use cp -rp. The best is to directly pack the files into an image file. Question: Is there any simple command-line tools without needing loop mount and root permission that can pack files into an ext4 partition image?

    Read the article

  • Correct For Loop Design

    - by Yttrill
    What is the correct design for a for loop? Felix currently uses if len a > 0 do for var i in 0 upto len a - 1 do println a.[i]; done done which is inclusive of the upper bound. This is necessary to support the full range of values of a typical integer type. However the for loop shown does not support zero length arrays, hence the special test, nor will the subtraction of 1 work convincingly if the length of the array is equal to the number of integers. (I say convincingly because it may be that 0 - 1 = maxval: this is true in C for unsigned int, but are you sure it is true for unsigned char without thinking carefully about integral promotions?) The actual implementation of the for loop by my compiler does correctly handle 0 but this requires two tests to implement the loop: continue: if not (i <= bound) goto break body if i == bound goto break ++i goto continue break: Throw in the hand coded zero check in the array example and three tests are needed. If the loop were exclusive it would handle zero properly, avoiding the special test, but there'd be no way to express the upper bound of an array with maximum size. Note the C way of doing this: for(i=0; predicate(i); increment(i)) has the same problem. The predicate is tested after the increment, but the terminating increment is not universally valid! There is a general argument that a simple exclusive loop is enough: promote the index to a large type to prevent overflow, and assume no one will ever loop to the maximum value of this type.. but I'm not entirely convinced: if you promoted to C's size_t and looped from the second largest value to the largest you'd get an infinite loop!

    Read the article

  • Delaying a Foreach loop half a second

    - by Sigh-AniDe
    I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a foreach loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help this is what i tried : The foreach runs inside the update method DateTime dt = DateTime.Now; foreach ( string commandDirection in ghostMovements ) { int mapX = ( int )( ghostPostition.X / scalingFactor ); int mapY = ( int )( ghostPostition.Y / scalingFactor ); // If the dt is the same as current time if ( dt == DateTime.Now ) { if ( commandDirection == "left" ) { switch ( ghostDirection ) { case ghostFacingUp: angle = 1.6f; ghostDirection = ghostFacingRight; Program.form.direction = ""; dt.AddMilliseconds( 500 );// add half a second to dt break; case ghostFacingRight: angle = 3.15f; ghostDirection = ghostFacingDown; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingDown: angle = -1.6f; ghostDirection = ghostFacingLeft; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; case ghostFacingLeft: angle = 0.0f; ghostDirection = ghostFacingUp; Program.form.direction = ""; dt.AddMilliseconds( 500 ); break; } } } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >