description/notes:

This is a little game that gives the user 5 tries to hit a house with a projectile, by entering the velocity and angle of a cannon. The projectile motion trails are left on screen after each try, to make it easier on the user. However, I never quite correctly implemented the collision detection portion of the code, so instead of registering a hit when a projectile trail crosses through the house, it only detects a hit when the end of the projectile's path hits the 'floor' of the house.

code:

#include "library.h"

const double g = 32.174;
const double pi = acos(-1);
double v, angle;

double h(double t)
{	
	double h = v*t*sin(angle) - 1.0/2*g*t*t;	
	return h;
}

double x(double t)
{
	double x = v*t*cos(angle);
	return x;
}

void main(void)
{	
	MakeWindow(1000,500);
	SetCaption("lab 03 - interactive cannons");
	
	//draws house
	int rand = random_in_range(600,900);
	PenColor0255(145,125,90); //main portion
		FillRectangleXYWH(rand,450,50,50);
	PenWidthColor(1,PEN_WHITE); //doors + window
		FillRectangleXYWH(rand+7,470,15,30);
		FillRectangleXYWH(rand+30,470,15,15);
	PenWidthColor(1,PEN_BLACK); //outline
		DrawRectangleXYWH(rand,450,50,50);
		DrawRectangleXYWH(rand+7,470,15,30);
		DrawRectangleXYWH(rand+30,470,15,15);

	int success=0, tries=0;
	while(success==0)
	{
		print("Tries remaining: ");
		print(5-tries); newline();
		print("Enter velocity of cannon: ");
		v =	read_double();
		print("Enter angle (in degrees)	of cannon: ");
		angle =	read_double()*pi/180;
		
		double tmax	= 2*sin(angle)*v/g;
		print("tmax	= ");
		print(tmax); newline();

		double scale = tmax/10.0;
		print("scale = ");
		print(scale); newline();

		//draws cannon
		MoveTo(0,500);
		PenWidthColor(10,PEN_BLACK);
		TurnToHeading(pi/2.0-angle);
		DrawLineLength(50);
		
		double t=0;
		while(t	< tmax+scale/2) //since	(i<=tmax) doesn't always work for certain combinations of values,
		                        //probably because of rounding errors..and weirdly, sometimes (i<tmax + scale)
		                        //doesn't work quite correctly either
		{
			PenWidthColor(1,PEN_BLACK);
			DrawLineTo(x(t),500-h(t));
			Pause(scale);
			t=t+scale;
		}	

		if(rand<x(tmax) && x(tmax)<rand+50) //i couldn't figure out how to make the program register a hit as
		                                    //the projectile path crossed the left wall/roof of the house;
		                                    //this only registers a hit if the end of the projectile's path
		                                    //hits at the "floor" of the house..
		{
			print("\nHit! You win!");
			success=1;
		}
		else
		{
			print("Miss!\n\n");
			//erases cannon on miss
			MoveTo(0,500);
			PenWidthColor(10,PEN_WHITE);
			TurnToHeading(pi/2.0-angle);
			DrawLineLength(50);
		}

		tries=tries+1;

		if(success==0 && tries==5)
		{
			print("Game over, man, game over...");
			break;
		}
	}
}	
        

screenshots:

lab03_01.png
lab03_02.png

files:

interactive cannons.cpp
interactive cannons.exe