As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
We're funding a new Acquisitions Incorporated series on Kickstarter right now! Check it out at https://www.kickstarter.com/projects/pennyarcade/acquisitions-incorporated-the-series-2

The beginner programming thread

1111214161763

Posts

  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    You shouldn't be multiplying anything by b. Look at your code carefully and make sure you understand what you're trying to accomplish with each instruction.

    The while (b < 0) return 0; at the end is also rather strange.

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Well... I've edited my code to this:
    double powerTo (double a, int b)
    {
    double result;

    if (b < 0)
    result = 0;
    for (result = 1; b >= 0; b--)
    result *= a;
    return result;
    }

    but I honestly don't know what I'm doing wrong.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Go through your code and see what happens when you call powerTo(5.0, -1) and powerTo(2.0, 3).

    Smasher on
  • BamaBama Registered User regular
    edited March 2008
    Yea, you're not too far off with that last revision. What Smasher suggested should point you in the right direction.

    Hints:

    1) You can leave the initialization expression (where you have "result = 1") blank in for loops. Of course, if you ever find yourself needing to do that you should probably consider using a while loop.

    2) One of the things you should notice from Smasher's second test case is that you get 2^4 instead of 2^3, this is because of what has to be the most common mistake you'll encounter with loops.

    Bama on
  • 12gauge12gauge Registered User regular
    edited March 2008
    Well... I've edited my code to this:
    double powerTo (double a, int b)
    {
    double result;

    if (b < 0)
    result = 0;
    for (result = 1; b >= 0; b--)
    result *= a;
    return result;
    }

    but I honestly don't know what I'm doing wrong.

    First of all, you don't need to wait until the last line to return a result, actually, most of the time you want to get out of a method as fast as possible - everything in a method after the first return you hit will not be run through. Second, look carefully at the for loop declaration and compare it to yours - you are not initializing or defining a control variable but the result variable.

    12gauge on
    davidoc0.jpg
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Wow, what a silly mistake. Thanks guys!

    JacksNsomnia on
    24584849if1gs7.jpg
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    So now I'm stuck on yet another problem:
    /*	==================== printTwo ====================
    	Prints pattern#2, as shown below:
    	   Pre   size
    	   Post  pattern#2 printed 
    				
                                   if size is 5:       if the size is 6
    
    			        5 * 5 * 5           6 * 6 * 6 *
    				5 * 5 * 5           6 * 6 * 6 *
    				5 * 5 * 5           6 * 6 * 6 *
    				5 * 5 * 5           6 * 6 * 6 *
    				5 * 5 * 5           6 * 6 * 6 *
                                                            6 * 6 * 6 *  [b]I don't know why this won't align, but it is in the program.[/b]
    
    


    Currently I am using this
    void  printTwo (int size )
    {
    		int i;
    		int j;
    		int temp;
    		
    		
    		for (i = 1; i <= size; i++)
    		{
    			for (j = 1; j <= size; j += 2)
    			{
    				printf(" %d ", size);
    				printf("*");
    				
    			}
    			
    
    		printf("\n");
    
    		}
    
    	return;
    }
    

    Which outputs this (for size 5 and 6):
    5 * 5 * 5 *
    5 * 5 * 5 *
    5 * 5 * 5 *
    5 * 5 * 5 *
    5 * 5 * 5 *
    
     6 * 6 * 6 *
     6 * 6 * 6 *
     6 * 6 * 6 *
     6 * 6 * 6 *
     6 * 6 * 6 *
     6 * 6 * 6 *
    

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Your inner loop always prints a number and a star together as a pair. Assuming I understand what it's supposed to do right, that shouldn't be the case for odd numbers, where you should have one more number than star.

    You need to make sure that you actually want to print the star in a given iteration of the inner loop. Ask yourself: in what case do you not want to print it?

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Right, I understand that I can't print a star at the end when the size is odd but I can't quite figure out how to do that.

    JacksNsomnia on
    24584849if1gs7.jpg
  • RohaqRohaq UKRegistered User regular
    edited March 2008
    Guys, our C++ programming classes, whilst useful and teaching us lovely things, annoyingly require a library that only runs under Windows, called Gwin, which creates windows and can create shapes, lines, and text etc. which was apparently developed by the university itself.

    As such, I've got a virtual machine running on my linux machine, running Windows, I can run Visual Studio 2005, all's good there.

    The problem is when I build my programs, in order to make Gwin redraw the screen, and check for new events, extensive use of continuous loops is used. On a normal Windows machine, this isn't a problem, but on a virtual machine, or under Wine, my CPU usage shoots up to 100% and it runs like a turd on a rubber tyre tread floor. I tested it on the university Windows computers earlier, and this basic program was taking up 50% CPU usage, constantly. Bloody ridiculous.

    My code's below, but can someone please offer me an alternative to this ridiculously CPU intensive method of doing things, so that I can test my programs within Ubuntu without needing to pester my Windows-toting buddies on MSN?

    Also, if anyone has a better way of passing values from the Ball class to the BallCol function, that would just be super: I have a distaste for functions with masses of parameters, it'd be cool if I could pass all the parameters I needed with say
    BallCol( Ball1.Properties(), Ball2.Properties() );
    
    or something.

    And one more thing: It'd be awesome if there was some way to check for collisions for anything that falls under the Ball class in one function, that way, I could throw more balls in there and not worry about checking for every possible ball collision. Can anyone suggest anything?

    Apologies for all the questions, I know it sounds like I'm asking you guys to do my homework, but rather sadly, this is purely for self-interest: There are no bonus marks for doing any of the above, I would just like to know better ways of doing things. Cheers!

    Full Code:
    // TwoBalls.cpp:
    
    #include "stdafx.h"
    #include "gwin.h"
    #include <math.h>
    
    #include <iostream>
    
    using namespace std;
    
    void BallCol(double Xpos1, double Ypos1, double Xpos2, double Ypos2, double Size1, double Size2, double &Vel1X, double &Vel1Y, double &Vel2X, double &Vel2Y, double Mass1, double Mass2 );
    
    int main()
    {
    	class Ball
    	{
    	private:
    		double XMax;
    		double YMax;
    	public:
    		double X;
    		double Y;
    		double Size;
    		Colour Colour;
    		double Mass;
    		double XVel;
    		double YVel;
    
    		void Initialise(double InitXVel, double InitYVel)
    		{
    			XMax = Gwin.getWidth();
    			YMax = Gwin.getHeight();
    			X = XMax*0.5+InitXVel*Size+1;
    			Y = YMax*0.5+InitYVel;
    		}
    
    		void Update()
    		{
    			X = X + XVel;
    			Y = Y + YVel;
    			YVel = YVel + 0.0005;
    		}
    
    		void WallCheck()
    		{
    			if (X <= 0 || X >= XMax)
    			{
    				XVel = -XVel;
    			}
    			if (Y <= 0 || Y >= YMax)
    			{
    				YVel = -YVel;
    			}
    		}
    		void DrawBall()
    		{
    			Gwin.setFillColour(Colour);
    			Gwin.circle(X,Y,Size);
    		}
    	};
    
    	Ball Ball1,Ball2;
    
    	// Holy crap it's Ball1!
    	Ball1.Size = 20;
    	Ball1.Colour = RED;
    	Ball1.Mass = 1;
    	Ball1.X = 0; Ball1.Y = 10;
    	Ball1.XVel = 0.03; Ball1.YVel = 0.0;
    
    	// And Ball2!
    	Ball2.Size = 28;
    	Ball2.Colour = BLUE;
    	Ball2.Mass = 0.5;
    	Ball2.X = 0; Ball2.Y = 0;
    	Ball2.XVel = -0.05;	Ball2.YVel = 0.001;
    
    	// Clear the Gwin window
    	Gwin.clear();
    
    	// Initialise Balls
    	Ball1.Initialise(-5.0,10.0);
    	Ball2.Initialise(5.0,6.0);
    
    	// Disable Gwin auto-refreshing
    	Gwin.refreshMode(false);
    	do
    	{
    		//clear back screen - won't afect visible screen till the end
    		Gwin.clear();
    
    		// Update positions and velocities.
    		Ball1.Update();
    		Ball2.Update();
    
    		// Check if Balls are colliding together.
    		BallCol(Ball1.X, Ball1.Y, Ball2.X, Ball2.Y, Ball1.Size, Ball2.Size, Ball1.XVel, Ball1.YVel, Ball2.XVel, Ball2.YVel, Ball1.Mass, Ball2.Mass );
    
    		// Check if balls are colliing with walls.
    		Ball1.WallCheck();
    		Ball2.WallCheck();
    
    		Ball1.DrawBall();
    		Ball2.DrawBall();
    
    		Gwin.refresh();
    
    	}while (!Keyboard.kbhit());
    
    
    	// Finally, wait for a key to be pressed
    	Keyboard.getch();
    
    	return 0;
    }
    
    
    void BallCol(double Xpos1, double Ypos1, double Xpos2, double Ypos2, double Size1, double Size2, double &Vel1X, double &Vel1Y, double &Vel2X, double &Vel2Y, double Mass1, double Mass2 )
    {
    	double xdif = Xpos1 - Xpos2;
    	double ydif = Ypos1 - Ypos2;
    	double dist=sqrt(xdif*xdif+ydif*ydif);
    
    	if (dist<=Size1+Size2)
    	{
    		double xdifn = xdif / dist;
    		double ydifn = ydif / dist;
    		double vel1c = xdifn*Vel1X+ydifn*Vel1Y;
    		double vel2c = xdifn*Vel2X+ydifn*Vel2Y;
    		double velcg = (Mass1*vel1c+Mass2*vel2c)/(Mass1+Mass2);
    		double vel1cg = vel1c-velcg;
    		double vel2cg = vel2c-velcg;
    
    		Vel1X = Vel1X-2.0*vel1cg*xdifn;
    		Vel1Y = Vel1Y-2.0*vel1cg*ydifn;
    		Vel2X = Vel2X-2.0*vel2cg*xdifn;
    		Vel2Y = Vel2Y-2.0*vel2cg*ydifn;
    	}
    }
    

    Rohaq on
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    1) I'm not familiar with windows programming, but there should be some sort of sleep command that your program can use to temporarily release control of the cpu. Just have it sleep for 16 milliseconds or so after each iteration of the main loop and your program should use only as much CPU time as it needs.

    2) All those properties are contained in the Ball class, so you can just pass Ball1 and Ball2 to the function (preferably by reference to prevent unnecessary copying) and get the needed variables from them.

    3) I'm not entirely sure what you mean by "anything that falls under the ball class". If you want your program to be correct you're going to have to check every possible collision between balls unless you use Quadtrees or the like. Quadtrees reduce the number of collisions you need to check for, at the expense of some additional code complexity.

    Smasher on
  • BarrakkethBarrakketh Registered User regular
    edited March 2008
    Rohaq wrote: »
    Also, if anyone has a better way of passing values from the Ball class to the BallCol function, that would just be super: I have a distaste for functions with masses of parameters, it'd be cool if I could pass all the parameters I needed with say
    BallCol( Ball1.Properties(), Ball2.Properties() );
    
    or something.

    One way to do that would be through using an interface, but I don't remember the proper way to do that in C++. My terminology may be off.

    Basically you can use inheritance to define a superclass of Ball (that Ball will inherit from) that defines a virtual function named Properties (as per your example) that will return the values needed for BallCol to do its magic. BallCol will accept objects of the superclass' type. Since the type of Ball is also the type of the superclass, the Properties method defined by Ball should be called via the magic of polymorphism.

    Barrakketh on
    Rollers are red, chargers are blue....omae wa mou shindeiru
  • BamaBama Registered User regular
    edited March 2008
    Right, I understand that I can't print a star at the end when the size is odd but I can't quite figure out how to do that.
    Think of it this way: you only print a star out to even numbered columns. You've been introduced to the modulo operator, %, right?

    Bama on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Heh I've been trying to figure out how to do it with the modulo... so would it be something along the lines of:
    temp = i &#37; 2;
    if (temp = 0)
    printf("*");
    

    ?

    EDIT: Argh no I don't think that will work. See I went down this path before and got extremely frustrated ha that's why I'm taking a break.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    A very very important thing to remember: = is assignment, == is comparing. if(temp = 0) will assign 0 to temp, then evaluate if(temp) as a boolean expression. Since temp is now 0 (which when cast to a boolean equals FALSE) the if() statement will always evaluate to false.

    Smasher on
  • RohaqRohaq UKRegistered User regular
    edited March 2008
    Smasher wrote: »
    1) I'm not familiar with windows programming, but there should be some sort of sleep command that your program can use to temporarily release control of the cpu. Just have it sleep for 16 milliseconds or so after each iteration of the main loop and your program should use only as much CPU time as it needs.

    2) All those properties are contained in the Ball class, so you can just pass Ball1 and Ball2 to the function (preferably by reference to prevent unnecessary copying) and get the needed variables from them.

    3) I'm not entirely sure what you mean by "anything that falls under the ball class". If you want your program to be correct you're going to have to check every possible collision between balls unless you use Quadtrees or the like. Quadtrees reduce the number of collisions you need to check for, at the expense of some additional code complexity.

    1). sleep(16); should still work: I'll give that a go, it might be what I'm after.

    2). I've tried redefining my function as follows:
    void BallCol( Ball Ball1, Ball Ball2)
    

    And it throws errors at me on the compile:
    ------ Build started: Project: TwoBalls, Configuration: Debug Win32 ------
    Compiling...
    TwoBalls.cpp
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(16) : error C2065: 'Ball' : undeclared identifier
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(16) : error C2146: syntax error : missing ')' before identifier 'Ball1'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(16) : error C2182: 'BallCol' : illegal use of type 'void'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(16) : error C2059: syntax error : ')'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(102) : error C2064: term does not evaluate to a function taking 2 arguments
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(63) : warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(63) : warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(63) : warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(123) : error C2146: syntax error : missing ')' before identifier 'Ball1'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(123) : error C2182: 'BallCol' : illegal use of type 'void'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(123) : error C2374: 'BallCol' : redefinition; multiple initialization
            c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(16) : see declaration of 'BallCol'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(123) : error C2059: syntax error : ')'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(124) : error C2143: syntax error : missing ';' before '{'
    c:\documents and settings\<username>\desktop\home\twoballs2\twoballs\twoballs.cpp(124) : error C2447: '{' : missing function header (old-style formal list?)
    Build log was saved at "file://c:\Documents and Settings\<username>\Desktop\Home\TwoBalls2\TwoBalls\Debug\BuildLog.htm"
    TwoBalls - 11 error(s), 3 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    
    All code is the same as before, except that the function is defined as above, and the Xpos1, Ypos2, Size1 etc. have been replaced with Ball1.X, Ball2.Y, Ball1.Size etc.

    I've not used classes much before, so any tips on getting that working would be great, thanks guys!

    3). Quadtrees... sounds complicated. I'll work on passing my programming module before I delve into that, I think.

    Rohaq on
  • RohaqRohaq UKRegistered User regular
    edited March 2008
    Actually fuck it, never mind, I see the problem: I'm attempting to declare a function and pass through class types that were declared within main(), so it fucks up royally. Moved the class outside of main() and compiles just fine, now testing...

    EDIT:- Tested, changed the function to the following:
    void BallCol( Ball &Ball1, Ball &Ball2 )
    

    All's working perfectly, thank you very much guys!

    That sleep function didn't work though, any more tips on how to better handle event checking and redrawing without using that huge loop?

    Rohaq on
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    "Colour Colour;" is likely going to give you problems too. You can't use a name as both a class identifier and a variable.

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Should I just write my function to make columns instead of rows? I'm getting really frustrated heh and I have a bunch of these "make the pattern" question due tomorrow so any more help is greatly, greatly appreciated.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    You're not going to be able to do it by columns instead of rows because of the way printf works (row by row, rather than column by column).

    The number of rows you need to print is easy, and you've got that down already. Describe to me, in English, what should be contained within each row for a given input N.

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Alright. Basically the user inputs a number between 2 and 9 for "size". Size determines the dimensions of the pattern (in box format) i.e. the box dimensions will always be size x size. So if I input size as 2 the box dimensions would be 2 x 2. So given printf only works in rows, we will say that 1r1 designates the first spot in the first row and 1r2 would be the second spot in row 1. So for every odd row point (1r1, 1r3 etc) there will be the the size number and for every even row point (1r2, 1r4) there will be an asterisk. The number of numbers and asterisks in a row must always add up to the designated size number so for size = five the pattern would look like so:

    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5

    I think that is as detailed as I can get.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Alright. Basically the user inputs a number between 2 and 9 for "size". Size determines the dimensions of the pattern (in box format) i.e. the box dimensions will always be size x size. So if I input size as 2 the box dimensions would be 2 x 2. So given printf only works in rows, we will say that 1r1 designates the first spot in the first row and 1r2 would be the second spot in row 1. So for every odd row point (1r1, 1r3 etc) there will be the the size number and for every even row point (1r2, 1r4) there will be an asterisk. The number of numbers and asterisks in a row must always add up to the designated size number so for size = five the pattern would look like so:

    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5
    5 * 5 * 5

    I think that is as detailed as I can get.

    That's good. Now distill that to the basics:

    There's n symbols per row.
    Odd symbols are numbers.
    Even symbols are *s.

    Do you know how to test if a number is odd or even? If not, familiarize yourself with the % (pronounced mod) operator.

    I'd give you an outline for the algorithm, but it's something you should really practice coming up with for yourself. Take it from there.

    Smasher on
  • RohaqRohaq UKRegistered User regular
    edited March 2008
    Smasher wrote: »
    "Colour Colour;" is likely going to give you problems too. You can't use a name as both a class identifier and a variable.
    Hm, not had a problem yet. I'll keep that in mind though.

    Rohaq on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    void  printTwo (int size )
    {
    		int i;
    		int j;
    		int temp;
    		
    		
    		for (i = 1; i <= size; i++)
    		{
    			for (j = 1; j <= size; j += 2)
    			{
    				temp = i &#37; 2;
    				if (temp == 1)
    				printf(" %d ", size);
    				if (temp == 0)
    				printf("*");
    			}		
    		printf("\n");
    		}
    	return;
    }
    
    

    I know I'm so close too.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Look at what j does.

    Also, something is wrong with "temp = i % 2;".

    Smasher on
  • BamaBama Registered User regular
    edited March 2008
    Yes, you are. Would you say you're only printing out about half as many columns as you need?

    edit: beat'd

    Bama on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Alright I replaced "i" with "size" ...

    err in terms of temp = size % 2

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    What is the purpose of that statement? In other words, what does it accomplish?

    (Rhetorical questions, not "WTF are you doing" ones)

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Well it obviously doesn't do anything because size isn't changing. I can't figure out how to write a statement that will produce an asterisk when the number is even and a number when odd. I mean I understand the whole number % 2 = 0 means a number is even and number % 2 = 1 means odd but I can't figure out how to incorporate that into this function.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    What variable has a different value each time you want to print a character?

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    void  printTwo (int size )
    {
                    int i;
                    int j;
    				int temp;
                   
                    for (i = 1; i <= size; i++)
                    {
                     for (j = 1; j <= size; j += 2)
    					{
                            printf(" &#37;d ", size);
    				temp = size % 2;
    				if (temp < 0 && j != size)
    				printf("*");
    				    }               
                    printf("\n");
                    }
            return;
    }
    
    
    
    

    EDIT: AHHH! Finally! Now will someone explain to me why this works or how they would've done it?

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Well, I would, but it doesn't. Honestly your last attempt was closer to the answer.

    Try renaming i to row and j to column respectively. I think their names may be causing you some confusion when you think about the problem.

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    How does it not work? I've compiled it and everything and it works fine.

    JacksNsomnia on
    24584849if1gs7.jpg
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Are you sure you copied it right then? When I copy paste it it definitely doesn't work (though it compiles).

    Smasher on
  • JacksNsomniaJacksNsomnia Registered User regular
    edited March 2008
    Well here is the code again:
    void  printTwo (int size )
    {
       int row;
       int column;
       int temp;
                   
       for (row = 1; row <= size; row++)
    		{
    		 for (column = 1; column <= size; column += 2)
    			{
    				printf(" %d ", size);
    				temp = size % 2;
    				if (temp >= 0 && column != size)
    				printf("*");
    			}               
    		printf("\n");
    	    }
       return;
    }
    

    And, at least for me, it works perfectly well. If you look into the logic of the statement it works too simply because column will never be equal to the size of an even "size".

    JacksNsomnia on
    24584849if1gs7.jpg
  • LittleBootsLittleBoots Registered User regular
    edited March 2008
    Rohaq wrote: »
    Actually fuck it, never mind, I see the problem: I'm attempting to declare a function and pass through class types that were declared within main(), so it fucks up royally. Moved the class outside of main() and compiles just fine, now testing...

    EDIT:- Tested, changed the function to the following:
    void BallCol( Ball &Ball1, Ball &Ball2 )
    

    All's working perfectly, thank you very much guys!

    That sleep function didn't work though, any more tips on how to better handle event checking and redrawing without using that huge loop?

    The Sleep function in windows is in milliseconds. So you may want to try something higher than 16 to notice anything. Such as something in the thousands maybe?

    EDIT: Just think of it like a ping in a game. At a ping of 16 you wouldn't notice a delay in anything. At something in or approaching a ping of a thousand or more.. well, I'm sure you can figure it out ;)

    LittleBoots on

    Tofu wrote: Here be Littleboots, destroyer of threads and master of drunkposting.
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Ah, I see what happened. In your other post it had temp < 0, where in that one it's temp >= 0. It actually was closer to being right than the version before it, I just thought you were trying to do it a different way so it didn't seem like it. As a matter of fact, since you're doing it that way you can get rid of temp entirely.
    void  printTwo (int size )
    {
    	int row;
    	int column;
                 
    	for (row = 1; row <= size; row++)
    	{
    		for (column = 1; column <= size; column += 2)
    		{
    			printf(" %d ", size);
    			if (column != size)
    				printf("*");
    		}             
    		printf("\n");
    	}
    	return;
    }
    
    The reason this works is that it goes through the columns two at a time, printing the digit and * respectively. The only time you don't need to print the * is in the last column when the size is odd. The column != size check takes care of the first part. Why doesn't that mess up the last star for even sizes, and why don't we explicitly have to check if it's odd? Those two questions have the same answer.

    With an even size (let's say 8) column starts at 1, then becomes 3, 5, and 7. It prints out 8, then compares column and size. Since column starts at 7 in this iteration of the loop, and we don't modify it until the next iteration, the if() statement evaluates to true and we print out the last *. column then becomes 9, and the for loop automatically exits.

    With an odd size (going with 7 this time) column again goes 1, 3, 5, then 7. It prints out 7, but this time column does equal size and so the if() statement evaluates to false and the second printf doesn't get executed.

    As for how I would have done it, I'd probably do this:
    void  printTwo (int size )
    {
    	int row;
    	int column;
                 
    	for (row = 0; row < size; row++)
    	{
    		for (column = 0; column < size; column++)
    		{
    			if(column % 2 == 0)
    				printf("%d ", size);
    			else
    				printf("* ");
    		}             
    		printf("\n");
    	}
    	return;
    }
    

    I start my indexes at 0 instead of 1 and use < size instead of <= size. In this case it doesn't matter which way you do it; you could set row and column to start at 50 if you wanted, as long as you account for it in the rest of the loop. Just keep in mind once you start using arrays that their indexing starts at 0 and the last valid element in the array is element size - 1; when you're using loops to iterate over the elements in an array your indexes will become important.

    The biggest difference in our code is that I increment column by one each time I go through the loop instead of two, and correspondingly print one character instead of two each time. I then do the mod check to see which character I'm supposed to be printing. Again either way is equally valid, and all comes down to what you feel makes your code easier to read and understand.

    Smasher on
  • SmasherSmasher Starting to get dizzy Registered User regular
    edited March 2008
    Rohaq wrote: »
    Actually fuck it, never mind, I see the problem: I'm attempting to declare a function and pass through class types that were declared within main(), so it fucks up royally. Moved the class outside of main() and compiles just fine, now testing...

    EDIT:- Tested, changed the function to the following:
    void BallCol( Ball &Ball1, Ball &Ball2 )
    
    All's working perfectly, thank you very much guys!

    That sleep function didn't work though, any more tips on how to better handle event checking and redrawing without using that huge loop?

    The Sleep function in windows is in milliseconds. So you may want to try something higher than 16 to notice anything. Such as something in the thousands maybe?

    EDIT: Just think of it like a ping in a game. At a ping of 16 you wouldn't notice a delay in anything. At something in or approaching a ping of a thousand or more.. well, I'm sure you can figure it out ;)

    I chose 16 milliseconds because it's about 1/60th of a second. Unless the Gwin library has function callbacks you can register with it (which would basically automatically call whatever functions you registered when the relevant timing, keyboard, etc. event occurred) you'll have to loop through your code repeatedly so it can do more than one frame. Do a frame, sleep for 16 milliseconds, do a frame, sleep for 16 milliseconds, rinse and repeat. If you set the sleep time to a second that means the program will run at 1 FPS, which naturally is far slower than what he probably wants.

    Rohaq, how did the sleep function not work? Did it not get called in the loop, or did it simply not reduce the CPU load? Keep in mind that the Update() function should only be getting checked 60 times a second now instead of however many times it was before.

    Actually we need some more info to debug this. You say Gwin can display text; make a counter that increments once per iteration of the loop, and display that on the screen so you can see how many frames you've drawn. Even better if you can use timing functions to get an actual FPS counter. In any case, take out the sleep call and see what you get there. If it's at or below 60 then sleep won't help you, and I suspect your problem is simply the speed of the virtual machine not being fast enough for this.

    Even if this is the case sleep should still help when you're running Windows natively; you'll just have to use timing functions to see how long the last frame took to render, then sleep for 16 - lastFrameMillis. Now that I mention it that's a good idea anyways. Don't forget to use the time since the last frame in your physics calculations to achieve frame-rate independence.

    If your frame-rate is above 60 FPS I'm not sure why sleep isn't working. In that case I'd guess your physics time is simply running too slowly; using the real frame time should help alleviate that problem.

    Smasher on
  • Zetetic ElenchZetetic Elench Registered User regular
    edited March 2008
    Hey guys what's goin' on in this thread?

    I'm just learning C#, actually, so I find this at a brilliant time. I'm planning to just tinker on some simple board-game-like projects to see how things go; I used to dabble with QBasic and the like but I'm fairly new to OOP, so it's weird adjusting to the new flow of programs. I like it, though.

    One thing I'd like to ask is; I see a lot of animation examples, for making things rotate or fade in and out, and so on, and they're often just a time counter plugged into a sine function. Is that the best way to go about things which are visual and time dependent? Moving a box onto the screen in a way which is more organic, for example - coming in fast and slowing down to stop right where you want it.

    Zetetic Elench on
    nemosig.png
  • LeumasWhiteLeumasWhite New ZealandRegistered User regular
    edited March 2008
    More C# here.
    string[] listboxItems = new string[] { };
    
    for (int i = 0; i < lstMaleFirstName.Items.Count; i++)
        {
            listboxItems[i] = lstMaleFirstName.Items[i].ToString();
        }
    
    maleFirstNameArray.Add(listboxItems);
    

    lstMaleFirstName is a listbox. maleFirstNameArray is an empty ArrayList. Whenever I run that bit of code, it throws an out of range exception.

    For completeness, here's the method that adds stuff to the listbox:
    private void btnMaleFirstAdd_Click(object sender, EventArgs e)
        {
            if (txtMaleFirst.Text != "")
            {
                lstMaleFirstName.Items.Add(txtMaleFirst.Text);
                txtMaleFirst.Text = "";
                txtMaleFirst.Focus();
            }
        }
    

    txtMaleFirst is the textbox that the string is pulled from. Probably something blisteringly simple that I'm missing here.

    LeumasWhite on
    QPPHj1J.jpg
This discussion has been closed.