Search Results

Search found 25 results on 1 pages for 'soulbeaver'.

Page 1/1 | 1 

  • Circular Bullet Spread not Even

    - by SoulBeaver
    I'm creating a bullet shooter much in the style of Touhou. Right now I want to have a very simple circular shot being fired from the enemy. See this picture: As you can see, the spacing is very uneven, which isn't very good if you want to survive. The code I'm using is this: private function shoot() : void { const BULLETS_PER_WAVE : int = 72; var interval : Number = BULLETS_PER_WAVE / 360; for (var i : int = 0; i < BULLETS_PER_WAVE; ++i { var xSpeed : Number = GameConstants.BULLET_NORMAL_SPEED_X * Math.sin(i * interval); var ySpeed : Number = GameConstants.BULLET_NORMAL_SPEED_Y * Math.cos(i * interval); BulletFactory.createNormalBullet(bulletColor_, alice_.center, xSpeed, ySpeed); } canShoot_ = false; cooldownTimer_.start(); } I imagine my mistake is in the sin, cos functions, but I'm not entirely sure what's wrong.

    Read the article

  • How to Implement Complex Form Data?

    - by SoulBeaver
    I'm supposed to implement a relatively complex form that looks like follows, but has at least four more pages requiring the user to fill in all necessary information for the tracks: This data will need to be sent to the server, which is implemented using Dropwizard. I'm looking for best practices on how to upload and send such a complex form with potentially dozens of songs to the server. The simplest available solution I have seen is a simple multipart/form-data request with the following form schema (Source): Client <html> <body> <h1>File Upload with Jersey</h1> <form action="rest/file/upload" method="post" enctype="multipart/form-data"> <p> Select a file : <input type="file" name="file" size="45" /> </p> <input type="submit" value="Upload It" /> </form> </body> </html> Server @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadTrack(final FormDataMultiPart multiPart) { List<FormDataBodyPart> artists = multiPart.getFields("artist"); StringBuffer output = new StringBuffer(); for (FormDataBodyPart artist : artists) output.append(artist.getValueAs(String.class)); List<FormDataBodyPart> tracks = multiPart.getFields("track"); for (FormDataBodyPart track : tracks) writeToFile(track.getValueAs(InputStream.class), "Foo"); return Response.status(200).entity(output.toString()).build(); } Then I have also read about file uploads via Ajax or Formdata (Mozilla HttpRequest) which allows for Posts in the formats application/x-www-form-urlencoded, multipart/form-data, or text/plain. I don't know which approach, if any, is best. An ideal solution would be to utilize Jackson to convert a json string into my data objects, but I don't get the impression that this is possible with binary data.

    Read the article

  • Is Java's ElementCollection Considered a Bad Practice?

    - by SoulBeaver
    From my understanding, an ElementCollection has no primary key, is embedded with the class, and cannot be queried. This sounds pretty hefty, but it allows me the comfort of writing an enum class which also helps with internationalization (using the enum key for lookup in my ResourceBundle). Example: We have a user on a media site and he can choose in which format he downloads the files @Entity @Table(name = "user") public class User { /* snip other fields */ @Enumerated @ElementCollection( targetClass = DownloadFilePreference.class, fetch = FetchType.EAGER ) @CollectionTable(name = "download_file_preference", joinColumns = @JoinColumn(name = "user_id") ) @Column(name = "name") private Set<DownloadFilePreference> downloadFilePreferences = new HashSet<>(); } public enum DownloadFilePreference { MP3, WAV, AIF, OGG; } This seems pretty great to me, and I suppose it comes down to "it depends on your use case", but I also know that I'm quite frankly only an initiate when it comes to Database design. Some best practices suggest to never have a class without a primary key- even in this case? It also doesn't seem very extensible- should I use this and gamble on the chance I will never need to query on the FilePreferences?

    Read the article

  • Interesting Topics in Comp. Sci. for New Students?

    - by SoulBeaver
    I hope this is the right forum to ask this question. Last friday I was in a discussion with my professors about the students' lack of motivation and interest in the field of Computer Science. All of the students are enrolled, but through questionnaires and other questions that my professor posed it was revealed that over 90% of all enrolled students are just in it for the reward of getting a job sometime in the future (since it's a growing field with high job potential) I asked my professor for the permission to take over the first couple of lectures and try and motivate, interest and inspire students for the field of Computer Science and programming in particular (this is the Intro to Programming course). This request was granted and I now have a week to come up with a lecture topic for my professor's five groups. My main goal isn't to teach, I just want to get students to be as interested in the field as I am. I want to show them what's possible, what awesome magical things have been done in the field, the future we are heading towards using programming and Comp. Sci. Therefore, I would like to pose this question: I have a few topics, materials and sample projects that I would like to talk about: -- Grace Hopper (It is my hope to interest the female programmers in the class. There are never more than two or three per group and they, more than males, are prone to jumping ship and abandoning Comp. Sci.) -- The Singularity Institute -- Alan Turing -- Robotics -- Programming not as a chore or a must, but the idea that we are, at our core, the nexus to which anything anybody does in the digital world is connected to. We are the problem solvers; we assemble all the parts together and we are the ones that, essentially, make the vision a reality. -- Give them an idea for a programming project which, through the help of the professor, could be significant to every student (I want students to not only feel interested in the topic, but they should feel important, that what they do here makes a difference) Do you have interesting topics worthy of discussion, something I can tell the students which they can get interested about? How would you approach the lecture? If you had 90 minutes worth of time to try and get students interested in the project, what would you do?

    Read the article

  • Turn-Based RPG Battle Instance Layout For Larger Groups

    - by SoulBeaver
    What a title, eh? I'm currently designing a videogame; a turn-based RPG like Final Fantasy (because everybody knows Final Fantasy). It's a 2D sprite game. These are my ideas for combat: -The player has a group of 15 members (main character included) -During battle, five of the group are designated as active, and appear in the battle. -These five may be switched out at leisure, or when one of the five die. -At any time, the Waiting members can cast buffs, be healed by the active members, or perform special attacks. -Battles should contain 10+ monsters at least. I'm aiming for 20, but I'm not sure if that's possible yet. -Battles should feel larger than normal due to the interaction of Waiting members, active members and the increased amount of monsters per battle. -The player has two rows in which to put the Active members: front and back. -Depending on the implementation, I might allow comboing of player attacks and skills. These are just design ideas, so beware! I have not been able to test this out yet- I have no idea yet if any of these ideas bunched together will make for a compelling game. What sounds good on paper doesn't necessarily have to be good in practice! What I'm asking now is how to create the layout for this. My starting point are the battles in Final Fantasy VI, with up to 5-6 monsters on the left and the characters on the right- monsters on both sides if it's a pincer attack. However, this view would not work feasible with my goal of 20 monsters and 5 characters. All the monsters on the left would appear cluttered unless I scale them far far back. If I create a pincer-like map, then there would be no real pincer-attack possible. If I space the monsters out I force the player to scroll the screen- a game mechanic I've come across and not enjoyed imho. My question is: does anybody have any layouts or guides for designing battle maps in turn-based RPGs, especially with a larger number of enemies taken into consideration? How should it look? I am not asking for specific combat mechanics, just the layout for the moment.

    Read the article

  • How to Effectively Create Bullet Patterns

    - by SoulBeaver
    I'm currently creating a top-down shooter like Touhou. The most important factor of the game is that there are many diverse patterns and ways at which bullets are generated and shot at the player, see this video: http://www.youtube.com/watch?v=4Nb5Ohbt1Sg#start=0:60;end=9:53; At the moment, I'm using a class "Pattern" which has a series of steps on moving and shooting. However, I feel this method is quite laborous as I have to create a new Pattern for each attack and perhaps new Bullet classes that will implement a certain behavior. This question received a comment suggesting I should look into BulletML for easy creation and storage of bullets with a specific pattern. It looks decent, but it led me to wonder, what other solutions do you have that I should take into consideration? Update My current design is as follows: An example of an implemented pattern: My GigasPattern first executes a teleport which moves Alice to a certain point (X, Y) on the screen. After this is completed, the pattern starts using the Mover to move the sprite around (whereas teleporting has separate effects and animation). These are of no concern, really, as they are quite simple. The Shooter also creates various Attacks, which are classes again that the Shooter can use to create various patterns of bullets, much like the one in the question I posted. Once the Mover has reached it's destination, both it and the shooter stop and return to an inactive state. The pattern completes, is removed by the AI and a new one gets chosen.

    Read the article

  • When can you call yourself good at language X?

    - by SoulBeaver
    This goes back to a conversation I've had with my girlfriend. I tried to tell her that I simply don't feel adequate enough in my programming language (C++) to call myself good. She then asked me, "Well, when do you consider yourself good enough?" That's an interesting question. I didn't know what to tell her. So I'm asking you. For any programming language, framework or the like, when do you reach a point were you sit back, look at what you've done and say, "Hey, I'm actually pretty good at this."? How do you define "good" so that you can tell others, honestly, "Yeah, I'm good at X". Additionally, do you reach these conclusions by comparing what others can do? Additional Info I have read the canonical paper on how it takes ten-thousand hours before you are an expert on the field. (Props to anybody that knows what this paper is called again) I have also read various articles from Coding Horror about interviewing people. Some people, it was said, "Cannot function outside of a framework." So they may be "good" for that framework, but not otherwise in the language. Is this true?

    Read the article

  • How to Create a Grid for a 2D Game?

    - by SoulBeaver
    So I'm currently writing the engine for my videogame. I've almost integrated Tiled (I think) so I should have a map-creator here soon. My question is, how do I actually make the grid? I'm really confused here. If I create a large map with, say, 20x20 grids the size of 32x32 (screen size 640x640), then what do I do with it? Let's say I have the code for creating a window, and then place a player sprite that I can move with input, that's fine. If I use one map that's as big as the screen, then every pixel on the map is also a pixel on the game screen. The mapping is exact. Now what happens if I have a 2000x2000 map, for example? My character would have to keep moving and move the map around (or rather the camera focused on the player moves). Then I can no longer say that the screen maps exactly to the pixel position of the map. I tried making a Grid class that maps out the screen area to 32x32 tiles, but I'm not sure if that makes any sense. Once the map moves each tile would have to update its information, or something. I'm just really confused here. How do I actually make the tiles and a grid and map them to the data I get from tiled, or that I make myself? Are there any good examples of source code that I could look at?

    Read the article

  • Did I Inadvertently Create a Mediator in my MVC?

    - by SoulBeaver
    I'm currently working on my first biggish project. It's a frontend facebook application that has, since last Tuesday, spanned some 6000-8000 LOC. I say this because I'm using the MVC, an architecture I have never rigidly enforced in any of my hobby projects. I read part of the PureMVC book, but I didn't quite grasp the concept of the Mediator. Since I didn't understand and didn't see the need for it, my project has yet to use a single mediator. Yesterday I went back to the design board because of some requirement changes and noticed that I could move all UI elements out of the View and into its own class. The View essentially only managed the lifetime of the UI and all events from the UI or Model. Technically, the View has now become a 'Mediator' between the Model and UI. Therefore, I realized today, I could just move all my UI stuff back into the View and create a mediator class that handles all events from the view and model. Is my understanding correct in thinking that I have devolved my View as it currently is (handling events from the Model and UI) into a Mediator and that the UI class is what should be the View?

    Read the article

  • Union struct produces garbage and general question about struct nomenclature

    - by SoulBeaver
    I read about unions the other day( today ) and tried the sample functions that came with them. Easy enough, but the result was clear and utter garbage. The first example is: union Test { int Int; struct { char byte1; char byte2; char byte3; char byte4; } Bytes; }; where an int is assumed to have 32 bits. After I set a value Test t; t.Int = 7; and then cout cout << t.Bytes.byte1 << etc... the individual bytes, there is nothing displayed, but my computer beeps. Which is fairly odd I guess. The second example gave me even worse results. union SwitchEndian { unsigned short word; struct { unsigned char hi; unsigned char lo; } data; } Switcher; Looks a little wonky in my opinion. Anyway, from the description it says, this should automatically store the result in a high/little endian format when I set the value like Switcher.word = 7656; and calling with cout << Switcher.data.hi << endl The result of this were symbols not even defined in the ASCII chart. Not sure why those are showing up. Finally, I had an error when I tried correcting the example by, instead of placing Bytes at the end of the struct, positioning it right next to it. So instead of struct {} Bytes; I wanted to write struct Bytes {}; This tossed me a big ol' error. What's the difference between these? Since C++ cannot have unnamed structs it seemed, at the time, pretty obvious that the Bytes positioned at the beginning and at the end are the things that name it. Except no, that's not the entire answer I guess. What is it then?

    Read the article

  • If I wanted to make a Pac-Man Game?

    - by SoulBeaver
    I am immediately placing this as a community wiki thing. I don't want to ask for help in programming yet or have even a specific question about programming, but rather the process and the resources needed to make such a game. To put it simply: My college friend and I decided to give ourselves a really big challenge to further our skills in programming. In six months time we want to show ourselves a Pac-Man game. Pac-Man will be AI-controlled like the Ghosts and whichever Pac-Man lives the longest after a set of tries wins. This isn't like anything we've done so far. The goal here, for me, isn't to create a perfect game, but to try and complete it, learn a whole bunch in the process. Even if I don't finish in the time, which is a good possibility, I would want to have at least tried this. So my question is this: How should I start preparing myself? I already have started vector math, matrices, all that fun stuff. My desired platform would be DirectX 9.0c; is that advisable? Keep in mind that this is not a preference just for this project, but I wish to have some kind of future in graphics develepment, so I want to pick a platform that is future-safe. As for the game development in general, what should I take into consideration? I have never done a real game before, so any and all advise to development of mid-scale projects( if this would be a mid-scale project ) is greatly appreciated. My main concerns are the pit-falls and demotivators. Sorry if the question is so vague. If it doesn't belong here, then I will remove it. Otherwise, any and all advise regarding making larger projects is greatly appreciated.

    Read the article

  • Parse int to string with stringstream

    - by SoulBeaver
    Well! I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution. I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999]. As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream. So my code looked like this: // tempTotal is my int value I want converted. void toString( int tempTotal, string &str ) { ostringstream ss; // C++ Standard compliant method. ss << tempTotal; str = ss.str(); // Overwrite referenced value of given string. } and the function calling it was: else { toString( tempTotal, store ); cout << loop1 << " x " << loop2 << "= " << store << endl; } So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there. Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal. All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know. So even though I feel this is a really, really lame question, I just have to ask: How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.

    Read the article

  • Initialize Pointer Through Function

    - by SoulBeaver
    I was browsing my teacher's code when I stumbled across this: Order* order1 = NULL; then order1 = order(customer1, product2); which calls Order* order(Customer* customer, Product* product) { return new Order(customer, product); } This looks like silly code. I'm not sure why, but the teacher initialized all pointers to NULL instead of declaring them right away(looking at the code it's entirely possible, but he chose not to). My question is: is this good or acceptable code? Does the function call have any benefits over calling a constructor explicitely? And how does new work in this case? Can I imagine the code now as kind of like: order1 = new Order(customer, product);

    Read the article

  • How to Access a Private Variable?

    - by SoulBeaver
    This question isn't meant to sound as blatantly insulting as it probably is right now. This is a homework assignment, and the spec sheet is scarce and poorly designed to say the least. We have a function: double refuel( int liter, GasStation *gs ) { // TODO: Access private variable MaxFuel of gs and decrement. } Sound simple enough? It should be, but the class GasStation comes with no function that accesses the private variable MaxFuel. So how can I access it anyway using the function refuel? I'm not considering creating a function setFuel( int liter ) because the teacher always complains rather energetically if I change his specification. So... I guess I have to do some sort of hack around it, but I'm not sure how to go about this without explicitely changing the only function in GasStation and giving it a parameter so that I can call it here. Any hints perhaps?

    Read the article

  • Input not cleared.

    - by SoulBeaver
    As the question says, for some reason my program is not flushing the input or using my variables in ways that I cannot identify at the moment. This is for a homework project that I've gone beyond what I had to do for it, now I just want the program to actually work :P Details to make the finding easier: The program executes flawlessly on the first run through. All throws work, only the proper values( n 0 ) are accepted and turned into binary. As soon as I enter my terminate input, the program goes into a loop and only asks for the termiante again like so: When I run this program on Netbeans on my Linux Laptop, the program crashes after I input the terminate value. On Visual C++ on Windows it goes into the loop like just described. In the code I have tried to clear every stream and initialze every variable new as the program restarts, but to no avail. I just can't see my mistake. I believe the error to lie in either the main function: int main( void ) { vector<int> store; int terminate = 1; do { int num = 0; string input = ""; if( cin.fail() ) { cin.clear(); cin.ignore( numeric_limits<streamsize>::max(), '\n' ); } cout << "Please enter a natural number." << endl; readLine( input, num ); cout << "\nThank you. Number is being processed..." << endl; workNum( num, store ); line; cout << "Go again? 0 to terminate." << endl; cin >> terminate // No checking yet, just want it to work! cin.clear(); }while( terminate ); cin.get(); return 0; } or in the function that reads the number: void readLine( string &input, int &num ) { int buf = 1; stringstream ss; vec_sz size; if( ss.fail() ) { ss.clear(); ss.ignore( numeric_limits<streamsize>::max(), '\n' ); } if( getline( cin, input ) ) { size = input.size(); for( int loop = 0; loop < size; ++loop ) if( isalpha( input[loop] ) ) throw domain_error( "Invalid Input." ); ss << input; ss >> buf; if( buf <= 0 ) throw domain_error( "Invalid Input." ); num = buf; ss.clear(); } }

    Read the article

  • Project Euler Problem #11

    - by SoulBeaver
    Source: http://projecteuler.net/index.php?section=problems&id=11 Quick overview: Take a 20x20 grid of numbers and compute the largest product of 4 pairs of numbers in either horizontal, vertical, or diagonal. My current approach is to divide the 20x20 grid up into single rows and single columns and go from there with a much more manageable grid. The code I'm using to divide the rows into rows is void fillRows ( string::const_iterator& fieldIter, list<int>& rowElements, vector<list<int>>& rows ) { int count(0); for( ; fieldIter < field.end(); ++fieldIter ) { if(isdigit(field[*fieldIter])) { rowElements.push_back(toInt(field[*fieldIter])); ++count; } if(count == 40) { rows.push_back(rowElements); count = 0; rowElements.clear(); } } } Short explanation: I have the field set as static const std::string field and I am filling a vector with lists of rows. Why a list? Because the queue doesn't have a clear function. Also practice using STL container lists and not ones I write myself. However, this thing isn't working. Oftentimes I see it omitting a character( function toInt parses the const char as int ) and I end up with 18 rows, two rows short of the 20x20 grid. The length of the rows seem good. Rows: 18 RowElements[0]: 40 (instead of pairs I saved each number individually. Will fix that later) What am I doing wrong?

    Read the article

  • Pointer initialization

    - by SoulBeaver
    Sorry if this question has been asked before. On my search through SO I didn't find one that asked what I wanted to know. Basically, when I have this: typedef struct node { int data; node *node; } *head; and do node *newItem = new node; I am under the impression that I am declaring and reserving space, but not defining, a pointer to struct node, is that correct? So when I do newItem->data = 100 and newItem->next = 0 I get confused. newItem = 0would declare what exactly? Both data and next? The object as a whole? I'm especially confused when I use typedef. Which part is the macro? I assume node because that's how I call it, but why do I need it? Finally, what happens when I do: node *temp; temp = new node; temp = head->next; head->next = newItem; newItem->next = temp; I mean, head-next is a pointer pointing to object newItem, so I assume not to newItem.data or next themselves. So how can I use an uninitialized pointer that I described above safely like here? is head now not pointing to an uninitialized pointer?

    Read the article

  • Finding character in String in Vector.

    - by SoulBeaver
    Judging from the title, I kinda did my program in a fairly complicated way. BUT! I might as well ask anyway xD This is a simple program I did in response to question 3-3 of Accelerated C++, which is an awesome book in my opinion. I created a vector: vector<string> countEm; That accepts all valid strings. Therefore, I have a vector that contains elements of strings. Next, I created a function int toLowerWords( vector<string> &vec ) { for( int loop = 0; loop < vec.size(); loop++ ) transform( vec[loop].begin(), vec[loop].end(), vec[loop].begin(), ::tolower ); that splits the input into all lowercase characters for easier counting. So far, so good. I created a third and final function to actually count the words, and that's where I'm stuck. int counter( vector<string> &vec ) { for( int loop = 0; loop < vec.size(); loop++ ) for( int secLoop = 0; secLoop < vec[loop].size(); secLoop++ ) { if( vec[loop][secLoop] == ' ' ) That just looks ridiculous. Using a two-dimensional array to call on the characters of the vector until I find a space. Ridiculous. I don't believe that this is an elegant or even viable solution. If it was a viable solution, I would then backtrack from the space and copy all characters I've found in a separate vector and count those. My question then is. How can I dissect a vector of strings into separate words so that I can actually count them? I thought about using strchr, but it didn't give me any epiphanies.

    Read the article

  • How to pass a function in a function?

    - by SoulBeaver
    That's an odd title. I would greatly appreciate it if somebody could clarify what exactly I'm asking because I'm not so sure myself. I'm watching the Stanford videos on Programming Paradigms(that teacher is awesome) and I'm up to video five when he started doing this: void *lSearch( void* key, void* base, int elemSize, int n, int (*cmpFn)(void*, void*)) Naturally, I thought to myself, "Oi, I didn't know you could declare a function and define it later!". So I created my own C++ test version. int foo(int (*bar)(void*, void*)); int bar(void* a, void* b); int main(int argc, char** argv) { int *func = 0; foo(bar); cin.get(); return 0; } int foo(int (*bar)(void*, void*)) { int c(10), d(15); int *a = &c; int *b = &d; bar(a, b); return 0; } int bar(void* a, void* b) { cout << "Why hello there." << endl; return 0; } The question about the code is this: it fails if I declare function int *bar as a parameter of foo, but not int (*bar). Why!? Also, the video confuses me in the fact that his lSearch definition void* lSearch( /*params*/ , int (*cmpFn)(void*, void*)) is calling cmpFn in the definition, but when calling the lSearch function lSearch( /*params*/, intCmp ); also calls the defined function int intCmp(void* elem1, void* elem2); and I don't get how that works. Why, in lSearch, is the function called cmpFn, but defined as intCmp, which is of type int, not int* and still works? And why does the function in lSearch not have to have defined parameters?

    Read the article

  • ARM Assembly - Converting Endianness

    - by SoulBeaver
    Hello people! This is currently a homework project that me and my teammate are stuck on. We haven't been given much of an introduction into Assembly, and this is supposed to be our first homework exercise. The task is to create a program that converts 0xAABBCCDD into 0xDDCCBBAA. I'm not looking for an answer, as that would defeat the purpose, but we are getting severely frustrated over the difficulty of this stupid thing. We think we have a good start in creating a viable solution, but we just cannot come up with the rest of the program. First, we mask every single tupel (aa), (bb), (cc), (dd) into a different register: LDR R0, LittleEndian // 0xAABBCCDD AND R1, R0, #0xFF000000 // 0xAA AND R2, R0, #0x00FF0000 // 0xBB AND R3, R0, #0x0000FF00 // 0xCC AND R4, R0, #0x000000FF // 0xDD Then we try to re-align them into the R0 register, but hell if we could come up with a good solution... Our best effort came from: ORR R0, R1, LSL #24 ORR R0, R2, LSL #8 ORR R0, R3, LSR #8 ORR R0, R4, LSR #24 which produced 0xBBBBCCDD for some odd reason; we really don't know. Any hints would be greatly appreciated. Again, we are asking for help, but not for a solution. Cheers!

    Read the article

  • Extremely CPU Intensive Alarm Clock

    - by SoulBeaver
    For some reason my program, a console alarm clock I made for laughs and practice, is extremely CPU intensive. It consumes about 2mB RAM, which is already quite a bit for such a small program, but it devastates my CPU with over 50% resources at times. Most of the time my program is doing nothing except counting down the seconds, so I guess this part of my program is the one that's causing so much strain on my CPU, though I don't know why. If it is so, could you please recommend a way of making it less, or perhaps a library to use instead if the problem can't be easily solved? /* The wait function waits exactly one second before returning to the * * called function. */ void wait( const int &seconds ) { clock_t endwait; // Type needed to compare with clock() endwait = clock() + ( seconds * CLOCKS_PER_SEC ); while( clock() < endwait ) {} // Nothing need be done here. } In case anybody browses CPlusPlus.com, this is a genuine copy/paste of the clock() function they have written as an example for clock(). Much why the comment //Nothing need be done here is so lackluster. I'm not entirely sure what exactly clock() does yet. The rest of the program calls two other functions that only activate every sixty seconds, otherwise returning to the caller and counting down another second, so I don't think that's too CPU intensive- though I wouldn't know, this is my first attempt at optimizing code. The first function is a console clear using system("cls") which, I know, is really, really slow and not a good idea. I will be changing that post-haste, but, since it only activates every 60 seconds and there is a noticeable lag-spike, I know this isn't the problem most of the time. The second function re-writes the content of the screen with the updated remaining time also only every sixty seconds. I will edit in the function that calls wait, clearScreen and display if it's clear that this function is not the problem. I already tried to reference most variables so they are not copied, as well as avoid endl as I heard that it's a little slow compared to \n.

    Read the article

  • Initialize a Variable Again.

    - by SoulBeaver
    That may sound a little confusing. Basically, I have a function CCard newCard() { /* Used to store the string variables intermittantly */ std::stringstream ssPIN, ssBN; int picker1, picker2; int pin, bankNum; /* Choose 5 random variables, store them in stream */ for( int loop = 0; loop < 5; ++loop ) { picker1 = rand() % 8 + 1; picker2 = rand() % 8 + 1; ssPIN << picker1; ssBN << picker2; } /* Convert them */ ssPIN >> pin; ssBN >> bankNum; CCard card( pin, bankNum ); return card; } that creates a new CCard variable and returns it to the caller CCard card = newCard(); My teacher advised me that doing this is a violation of OOP principles and has to be put in the class. He told me to use this method as a constructor. Which I did: CCard::CCard() { m_Sperre = false; m_Guthaben = rand() % 1000; /* Work */ /* Convert them */ ssPIN >> m_Geheimzahl; ssBN >> m_Nummer; } All variables with m_ are member variables. However, the constructor works when I initialize the card normally CCard card(); at the start of the program. However, I also have a function, that is supposed to create a new card and return it to the user, this function is now broken. The original command: card = newCard(); isn't available anymore, and card = new CCard(); doesn't work. What other options do I have? I have a feeling using the constructor won't work, and that I probably should just create a class method newCard, but I want to see if it is somehow at all possible to do it the way the teacher wanted. This is creating a lot of headaches for me. I told the teacher that this is a stupid idea and not everything has to be classed in OOP. He has since told me that Java or C# don't allow code outside of classes, which sounds a little incredible. Not sure that you can do this in C++, especially when templated functions exist, or generic algorithms. Is it true that this would be bad code for OOP in C++ if I didn't force it into a class?

    Read the article

  • Win32: No Window Appears

    - by SoulBeaver
    I was programming the example code from Frank Luna's book "Introduction to 3D Game Programming with DirectX 10". The code is the first Win32 example in the Appendix A: Windows Programming section. Right now, the program compiles under both VC++ 2008/2010, but no window appears, although the debug session has started and I have to forcefully close it. I have no idea where it is, I'm not using Win32 Console mode, I have closed all other windows and no other IDE or session of VC++ is running. Any idea why this might be happening? PS: I have also checked my Processes. It is indeed running.

    Read the article

  • When to use () with classes?

    - by SoulBeaver
    This is really starting to confuse the hell out of me. When do I use them, when don't I? For example I was reading a .cpp on linked lists whose class declaration was: struct CarPart { long PartNumber; char Partname[40]; double UnitPrice; CarPart *next; }; class ListOfParts { int size; public: CarPart *head; ListOfParts(); ~ListOfParts(); const int count() const; void insert( CarPart *item ); CarPart *retrieve( int pos ); }; With this code, why am I allowed to write ListOfParts *pPart = new ListOfParts(); CarPart *pCarPart = new CarPart; Declaring an instance of ListOfParts requires (), but not my CarPart? That's confusing me. When I asked a question before and people told me that such a declaration is a function that returns a ListOfParts object, but not the actual constructor. So I'm guessing this is still something different. What's happening here? PS: Am I correct to assume that the const to the right of count() means I cannot modify any values in count?

    Read the article

1