how to creating interval race game using c++ - html

This is the JavaScript part(car_race.js) i am able to create a track that is moving but it is not that much realistic as it should be. Write now what's happening is if one boundary bar gets completely disappeared then only it appears at the top of the canvas. what i want to do is when one boundary bar goes through the complete canvas from top to bottom i want it to resume back from top with the amount of body it gets disappeared from bottom part of canvas. Can anyone help me with this part.

To create an interval race game in C++, you will need to implement the following steps:
Set up a loop to run the game. The game should continue until the player has finished all the intervals or has chosen to quit.
Display the current interval and prompt the player to enter their time for that interval.
Read the player's time for the interval and store it in a variable.
Calculate the player's time for the entire race by adding their time for the current interval to their total time.
Check if the player has finished all the intervals. If they have, go to step 7. If not, go to step 6.
Display the player's current total time and go back to step 2 to start the next interval.
Display the player's final time and any other relevant information (e.g. their time for each interval).
Here is some sample code that demonstrates how you might implement these steps in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Set up variables to track the player's time and interval count
int interval_count = 0;
int total_time = 0;
// Run the game loop
while (true) {
// Increment the interval count
interval_count++;
// Display the current interval and prompt the player to enter their time
cout << "Interval " << interval_count << ": ";
cout << "Enter your time (in seconds): ";
// Read the player's time for the interval
int interval_time;
cin >> interval_time;
// Add the interval time to the total time
total_time += interval_time;
// Check if the player has finished all the intervals
if (interval_count == 3) {
// The player has finished all the intervals
break;
} else {
// The player has more intervals to complete
cout << "Total time: " << total_time << endl;
}
}
// Display the player's final time
cout << "Final time: " << total_time << endl;
return 0;
}

Related

Understanding heisenbug example: different precision in registers vs main memory

I read the wiki page about heisenbug, but don't understand this example. Can
anyone explain it in detail?
One common example
of a heisenbug is a bug that appears when the program is compiled with an
optimizing compiler, but not when the same program is compiled without
optimization (as is often done for the purpose of examining it with a debugger).
While debugging, values that an optimized program would normally keep in
registers are often pushed to main memory. This may affect, for instance, the
result of floating-point comparisons, since the value in memory may have smaller
range and accuracy than the value in the register.
Here's a concrete example recently posted:
Infinite loop heisenbug: it exits if I add a printout
It's a really nice specimen because we can all reproduce it: http://ideone.com/rjY5kQ
These bugs are so dependent on very precise features of the platform that people also find them very difficult to reproduce.
In this case when the 'print-out' is omitted the program performs a high precision comparison inside the CPU registers (higher than stored in a double).
But to print out the value the compiler decides to move the result to main memory which results in an implicit truncation of the precision. When it uses that truncated value for the comparison it succeeds.
#include <iostream>
#include <cmath>
double up = 19.0 + (61.0/125.0);
double down = -32.0 - (2.0/3.0);
double rectangle = (up - down) * 8.0;
double f(double x) {
return (pow(x, 4.0)/500.0) - (pow(x, 2.0)/200.0) - 0.012;
}
double g(double x) {
return -(pow(x, 3.0)/30.0) + (x/20.0) + (1.0/6.0);
}
double area_upper(double x, double step) {
return (((up - f(x)) + (up - f(x + step))) * step) / 2.0;
}
double area_lower(double x, double step) {
return (((g(x) - down) + (g(x + step) - down)) * step) / 2.0;
}
double area(double x, double step) {
return area_upper(x, step) + area_lower(x, step);
}
int main() {
double current = 0, last = 0, step = 1.0;
do {
last = current;
step /= 10.0;
current = 0;
for(double x = 2.0; x < 10.0; x += step) current += area(x, step);
current = rectangle - current;
current = round(current * 1000.0) / 1000.0;
//std::cout << current << std::endl; //<-- COMMENT BACK IN TO "FIX" BUG
} while(current != last);
std::cout << current << std::endl;
return 0;
}
Edit: Verified bug and fix still exhibit: 03-FEB-22, 20-Feb-17
It comes from Uncertainty Principle which basically states that there is a fundamental limit to the precision with which certain pairs of physical properties of a particle can be known simultaneously. If you start observing some particle too closely,(i.e., you know its position precisely) then you can't measure its momentum precisely. (And if you have precise speed, then you can't tell its exact position)
So following this, Heisenbug is a bug which disappears when you are watching closely.
In your example, if you need the program to perform well, you will compile it with optimization and there will be a bug. But as soon as you enter in debugging mode, you will not compile it with optimization which will remove the bug.
So if you start observing the bug too closely, you will be uncertain to know its properties(or unable to find it), which resembles the Heisenberg's Uncertainty Principle and hence called Heisenbug.
The idea is that code is compiled to two states - one is normal or debug mode and other is optimised or production mode.
Just as it is important to know what happens to matter at quantum level, we should also know what happens to our code at compiler level!

How can I correctly calculate the time delta?

I'm trying to create a game with an independent frame rate, in which myObject is moving to the right at one unit per millisecond. However, I don't know how to calculate deltaTime in this code:
var currentTime = 0;
var lastTime = 0;
var deltaTime = 0;
while( play ) {
// Retrieve the current time
currentTime = Time.now();
deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Move myObject at the rate of one unit per millisecond
myObject.x += 1 * deltaTime;
}
Let's say the first frame took 30 ms, so deltaTime should be 30 but it was 0
because we only know the time at the start of the frame not at the end of the frame. Then, in the second frame it took 40 ms, so deltaTime is 30 and thus myObject.x is 30. However, the elapsed time is 70 ms (30ms in 1st frame + 40ms in 2nd frame ) so myObject.x is supposed to be 70, not 30.
I'm not simulating physics, I'm just trying to move myObject relative to the elapsed time (not the frame).
How do I calculate deltaTime correctly?
I know that some game engine people use chunk of time or tick, so they're animating ahead of time. Also, I've already read Glenn Fiedler's article on fixing your timestep and many other ones, but I'm still confused.
Try this:
float LOW_LIMIT = 0.0167f; // Keep At/Below 60fps
float HIGH_LIMIT = 0.1f; // Keep At/Above 10fps
float lastTime = Time.now();
while( play ) {
float currentTime = Time.now();
float deltaTime = ( currentTime - lastTime ) / 1000.0f;
if ( deltaTime < LOW_LIMIT )
deltaTime = LOW_LIMIT;
else if ( deltaTime > HIGH_LIMIT )
deltaTime = HIGH_LIMIT;
lastTime = currentTime;
myObject.x += 1000 * deltaTime; // equivalent to one unit per ms (ie. 1000 per s)
}
There is alot wrong with this, but it makes it easier to illustrate the basic concept.
First, notice that you need to initialize lastTime with some value BEFORE the loop starts. You can use a lower value (i.e. Time.now() - 33) so that the first frame yields the desired delta, or just use it as I did (you will see that we limit it in the loop).
Next you get the current time at the start of each froame, use it to calculate the time elapsed since the last loop (which will be zero on the first run of this exaple). Then I like to convert it to seconds because it makes much more sense to work in "per second" than "per milisecond" - but feel free to remove the / 1000.0f part to keep it in ms.
Then you need to limit the deltaTime to some usable range (for the example I used 10-60fps, but you can change this as needed). This simply prevents the loop from running too fast or too slow. The HIGH_LIMIT is especially important because it will prevent very large delta values which can cause chaos in a game loop (better to be somewhat inaccurate than have the code break down) - LOW_LIMIT prevents zero (or very small) time steps, which can be equally problematic (especially for physics).
Finally, once you've calculated the new deltaTime for this frame, you save the current time for use during the next frame.

Outputting a bitstream onto a pin in verilog

I need to output a 32bit bit-stream onto a pin in verilog. I know verilog has the streaming operators pack and unpack but I do not believe they will do what I want it to do.
I have 32x512 FIFO RAM in which data is stored. Data for the variable "I" stored on the first 32 bits and the data for variable "Q" is stored on the next 32 bits (the rest of FIFO saves data in this alternating fashion). I need to continually get a 32bit stream off the FIFO RAM and output the 32bit data stream onto a pin. My FIFO has three output signals(a signal for the 32 bit data stream(32_data), a signal to say when the FIFO is empty (32_empty), and a signal to say when the FIFO is full(32_full)) My sudo code is the following (It's sudo code because I know how to do everything else but the part I need help with and I wanted to keep it simple for understanding):
process # posedge clock
begin
if (32_empty != 1) then //if the FIFO has data
if (32_full == 1) then //if the FIFO is full, then we lose data (for testing purposes to know if I need to make the RAM bigger
PIN_1 <= 1; //output onto a pin that the FIFO is full
PIN_2 <= 0; //clear pin 2 from outputting data for "I"
PIN_3 <= 0; //clear pin 3 from outputting data for "Q"
else if (en_Q == 0)
(stream 32bit data for variable "I" onto pin 2) //variable "I" output//HELP-This is where I need help figuring out how to stream the output, 32_data, onto a pin
en_Q <= ~en_Q; // toggle en_Q so next 32bit stream will be for "Q"
else if (en_Q ==1)
(stream 32bit data for variable "Q" onto pin 3) //variable "Q" output//HELP-This is where I need help figuring out how to stream the output, 32_data, onto a pin
en_Q <= ~en_Q; // toggle en_Q so next 32bit stream will be for "I"
end
If you could help me with figuring out how to stream a 32 bit data stream onto a pin, that would be great!
Thanks in advance
I have added the suggestion. Could I put the data on the pins with a for loop? The following is my code segment and the bottom part is the shift register and outputting to a pin:
`// Wires and registers related to data capturing
wire capture_clk;
reg [31:0] capture_data;
wire capture_en;
reg [4:0] slowdown;
wire capture_full;
reg capture_open;
reg capture_open_cross;
reg capture_has_been_full;
reg capture_has_been_nonfull;
reg has_been_full_cross;
reg has_been_full;
// Data capture section
// ====================
always #(posedge capture_clk)
begin
if (capture_en)
capture_data <= user_w_write_32_data; // Bogus data source
// The slowdown register limits the data pace to 1/32 the bus_clk
// when capture_clk = bus_clk. This is necessary, because the
// core in the evaluation kit is configured for simplicity, and
// not for performance. Sustained data rates of 200 MB/sec are
// easily reached with performance-oriented setting.
// The slowdown register has no function in a real-life application.
slowdown <= slowdown + 1;
// capture_has_been_full remembers that the FIFO has been full
// until the file is closed. capture_has_been_nonfull prevents
// capture_has_been_full to respond to the initial full condition
// every FIFO displays on reset.
if (!capture_full)
capture_has_been_nonfull <= 1;
else if (!capture_open)
capture_has_been_nonfull <= 0;
if (capture_full && capture_has_been_nonfull)
capture_has_been_full <= 1;
else if (!capture_open)
capture_has_been_full <= 0;
end
// The dependency on slowdown is only for bogus data
assign capture_en = capture_open && !capture_full &&
!capture_has_been_full &&
(slowdown == 0);
// Clock crossing logic: bus_clk -> capture_clk
always #(posedge capture_clk)
begin
capture_open_cross <= user_r_read_32_open;
capture_open <= capture_open_cross;
end
// Clock crossing logic: capture_clk -> bus_clk
always #(posedge bus_clk)
begin
has_been_full_cross <= capture_has_been_full;
has_been_full <= has_been_full_cross;
end
// The user_r_read_32_eof signal is required to go from '0' to '1' only on
// a clock cycle following an asserted read enable, according to Xillybus'
// core API. This is assured, since it's a logical AND between
// user_r_read_32_empty and has_been_full. has_been_full goes high when the
// FIFO is full, so it's guaranteed that user_r_read_32_empty is low when
// that happens. On the other hand, user_r_read_32_empty is a FIFO's empty
// signal, which naturally meets the requirement.
assign user_r_read_32_eof = user_r_read_32_empty && has_been_full;
assign user_w_write_32_full = 0;
// The data capture clock here is bus_clk for simplicity, but clock domain
// crossing is done properly, so capture_clk can be an independent clock
// without any other changes.
assign capture_clk = bus_clk;
async_fifo_32x512 fifo_32 //FIFO created using Xilinx FIFO Generator Wizard
(
.rst(!user_r_read_32_open),
.wr_clk(capture_clk),
.rd_clk(bus_clk),
.din(capture_data),
.wr_en(capture_en),
.rd_en(user_r_read_32_rden),
.dout(user_r_read_32_data),
.full(capture_full),
.empty(user_r_read_32_empty)
);
reg Q_en = 1'b0; //starting value is 0 because first 32bit is I
reg [31:0] data_outI;
reg [31:0] data_outQ;
reg I;
reg Q;
integer counter;
always #(posedge bus_clk) begin
if(Q_en == 1'b0) begin //To output to I signal
data_outI <= user_r_read_32_data;
for (counter = 0; counter < 32; counter = counter + 1) begin //output to pins
I = data_outI[0];
data_outI <= (data_outI >> 1);
Q = data_outQ[0];
data_outQ <= (data_outQ >> 1);
end
Q_en <= ~Q_en;
end
else if(Q_en == 1'b1) begin //To output to Q signal
data_outQ <= user_r_read_32_data;
for (counter = 0; counter < 32; counter = counter + 1) begin //output to pins
I = data_outI[0];
data_outI <= (data_outI >> 1);
Q = data_outQ[0];
data_outQ <= (data_outQ >> 1);
end
Q_en <= ~Q_en;
end
end
assign PS_GPIO_ONE_I = I; //Assign Pin I
assign PS_GPIO_TWO_Q = Q; //Assign Pin Q
`
Basically, you'd want to do something like the following:
Fetch an item from the fifo into a 32 bit register (lets call data)
Each clock cycle, put the lsb of data onto the pin, and then right shift data by one value.
Keep repeating this shifting for 32 clock cycles, until all of the data has been shifted out.
Toggle the value of en_Q, and fetch another 32 bit item.
You should be able to make a small state machine that can handle this sequence. You can't shift out all 32 bits in a single clock cycle as you have done in your pseudo-code, unless you also have a 32x clock available, and that would likely be a more complicated design.

Problem with constructor - initialization list (c++)

it's a weird problem that I have
I have a very simple constructor that's creates a matrix with no values:
RegMatrix::RegMatrix(const int numRow, const int numCol):
_numRow(numRow),_numCol(numCol),_matrix()
{
}
_matrix is a vector that holds 'Comlex', an object I've created
and VAL(i,j) is #define VAL(i,j) ((i * _numCol) + j)
Now, I call this constructor in function transpose:
RegMatrix RegMatrix::transpose()
{
RegMatrix newMatrix(_numCol,_numRow);
cout << "DIMENSIONS " << newMatrix._numRow << " " << newMatrix._numCol << endl;
for(int j=0; j<_numCol; j++)
{
for(int i=0; i<_numRow; i++)
{
newMatrix._matrix[VAL(i,j)] = _matrix[VAL(j,i)]; //<--SEGMENTATION FAULT
}
}
return newMatrix;
}
And here's my problem: I get a segmentation fault the very first time I enter the second loop. When I use the eclipse debugger I see that _nunRow and _numCol values of newMatrix seem to be garbage (one is '0' the other is -10000000 or something like that). What's even more weird is that I added the output line just to be sure and it gave me the right numbers!
So, any ideas as to what can be my problem?
Thanks!
You are indexing into an empty vector, which is doomed to fail. Use at instead of the subscript operator and you will get an exception.
My guess (based on what you show) is that there may be some problems with how you implement the copy constructor.

Continue statements

Wondering what a continue statement does in a do...while(false) loop, I mocked up a simple test-case (pseudo-code):
count = 0;
do {
output(count);
count++;
if (count < 10)
continue;
}while (false);
output('out of loop');
The output was, to my surprise:
0
out of loop
A bit confused, I changed the loop from a do...while to a for:
for (count = 0; count == 0; count++) {
output(count);
if (count < 10)
continue;
}
output('out of loop');
While functionally not the same, the purpose is practically the same: Make a condition only satisfied the first iteration, and in next ones continue (until a certain value is reached, purely for stopping possible infinite-loops.) They might not run the same amount of times, but functionality here isn't the important bit.
The output was the same as before:
0
out of loop
Now, put into terms of a simple while loop:
count = 0;
while (count == 0) {
output(count);
count++;
if (count < 10)
continue;
}
output('out of loop');
Once again, same output.
This is a bit confusing, as I've always thought of the continue statement as "jump to the next iteration". So, here I ask: What does a continue statement do in each of these loops? Does it just jump to the condition?
((For what it's worth, I tested the above in JavaScript, but I believe it's language-agnostic...js had to get at least that right))
In a for loop, continue runs the 3rd expression of the for statement (usually used as some kind of iteration), then the condition (2nd expression), and then the loop if the condition is true. It does not run the rest of the current iteration of the loop.
In a while (or do-while) loop, it just runs the condition and then the loop if the condition holds. It also does not run the rest of the current iteration of the loop.
Your definition of continue statement as "jump to the next iteration" is correct. This will force the program to start next iteration by first re-evaluating the conditional expression.
The problem with your snippets is that they all exit after one iteration because your conditional expressions are set to either false or count ==0. This will always return false after one iteration.
Moreover, putting continue statement at the end of the loop is meaningless. It will re-evaluate the conditional expression in either case.
It's best to think of continue as jumping to the end of the enclosing loop. This may haelp:
#include <iostream>
using namespace std;
int main() {
int n = 0;
do {
cout << n << endl;
n += 1;
if ( n == 3 ) {
continue;
}
cout << "n was not 3" << endl;
} while( n != 3 );
}
which prints:
0
n was not 3
1
n was not 3
2
and terminates, because the continue jumps to the while() at the end of the loop. similar stiff happens for for() and while() loops.
continue skips to the next iteration when it is used in a loop. break exits the current block. Typically, break is used to exit a loop but it could be used to exit any block.
for (int i = 0; i < 1000; i++) {
if (some_condition) {
continue; // would skip to the next iteration
}
if (some_other_condition) {
break; // Exits the loop (block)
}
// other work
}