Transcription

Graphics and C This term you can create programs on UNIX or you can createprograms using any C compiler (on your own computer).There is open source software available for free, so you don’thave to buy a compiler .For fun we will be demonstrating Graphicsusing PC C Compilers

Some of the Choices In CS161 our focus is on problem solvingand learning how to apply thesesolutions to a high level programminglanguage, like C We will also compare this to C and Javafrequently, other high level languages You can work with graphics, if you wantto challenge yourself (and have fun), butthere is no requirement that you do this.

Some of the Choices If you want to work on your own PC witha C compiler, rather than being loggedin remotely to the PSU systemsYou have many choices – there are manycompilers available for free download Many provide Integrated DevelopmentEnvironments (IDE’s) Which just means they have a graphical frontend and aren’t just text based when you enter inyour program.

Some of the Choices Some of your choices are (for free)Dev-C Visual Student C Express 2008NetBeansEclipse for C These all support the basic languagefeatures But, they are not equal in terms ofcomputer graphics

Some of the Choices Here is how they rank Dev-C provides a single graphics.h library thatwe use for in-class demos. It is easy to use. Visual and NetBeans are environments manyComputer Science students use, It is limited in support and functionalityBut it is easy to use!but they more complicatedEclipse for C requires more advanced OpenGLprogramming, which is beyond the scope of CS161 In CS202 we will use Eclipse

What is Dev-Cpp? Dev-C , developed by Bloodshed Software, is a fully featuredgraphical IDE (Integrated Development Environment), which isable to create Windows or console-based C/C programs.It is recommended because it is easy to use, doesn’t requireknowing a lot to get started, and is a great way to create some funprograms quickly.It is based on MinGW (Minimalist GNU* for Windows) which usesthe same family of compilers that we use on PSU’s unixenvironment ( a GNU g compiler collection).Although there are some differences, we don’t need to be tooconcerned with that in CS161. Differences between Cygwin andMinGW for more information.Links of interest:http://www.bloodshed.net/devcpp.html

What does it allow me to do? With an IDE, we can do all of our work on ourhome computer without logging in and withoutbeing on the internet.You can also use some cool features thatallow you to turn your screen into a graphicalparadise.In class some programs were demonstratedusing Dev-C -- such as painting programs,tic-tac-toe, and more.

Where you can get Dev-Cpp You can get Dev-C as free software (under GPL) but alsooffers a CD for purchase.Go to the author’s site to get a list of sites where you can get it:Dev-C download sites. (http://www.bloodshed.net/dev/devcpp.html) You should let the installer put Dev-C in the default directory ofC:\Dev-Cpp, as it will make it easier to later install add-ons orupgrades. I downloaded:Dev-C 5.0 beta 9.2 (4.9.9.2) (9.0 MB) with Mingw/GCC 3.4.2

Adding in Graphics Capabilities The graphics functions that we use in examples in thiscourse are not automatically part of Dev-C , so youwould need to download them at:(http://www.uniqueness-template.com/devcpp) graphics.h (download to C:\Dev-Cpp\include) and libbgi.a (download to C:\Dev-Cpp\lib) Then, you must tell Dev-C where to find thegraphics library! First go to the File menu and start a New Project Then, go to the Project menu and select ProjectOptions See the next slide .

YOU MUST DO THIS! After you go to the Project menu and select ProjectOptions Go to the Parameters tab In the Linker field, enter the following text-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32 Click OK

This is what Dev C Looks like

The First time, it looks like this

To Configure Dev-C All programming done for CS161 will require separatecompilation projects. This process is pretty easy as long asyou know what goes where, which we will show in class anddemonstrate here in these slides. The first time you use Dev-C you will need toconfigure it so that it will allow you to more easily getyour work done and allow you to perform computergraphics, if you so desire.Go to the Tools menu and select Compiler OptionsIn the Settings tab, click on Linker in the left panel andchange Generate debugging information to YesClick OK

Compiler Options under Tools

To Create a new Project Think of a project as a container used to store all of the piecesneeded to compile a programGo to the File menu and select New and then ProjectChoose Empty Project unless you use one of the projects I haveposted on my website, make sure C project is selectedThis is also where you will give your project a name.If you reuse a project, you essentially will write over whatever wasthere, so you will probably want to start with a fresh project name.The name of your project will also be the name of yourexecutable.Once you have entered a name of your project, click OKDev-C will then ask you where you want to save your file

Make it a C Empty Project Select Empty Project Select C Project I checked “Make Default Language Click OK

Add Source Files Here are some ways to add source filesGo to the File menu and select New SourceFile Or, go to the Project menu and select NewFile I like to go to the green symbol whichallows me to add files to this project; youcan use it to add one of the examples thathas been posted on our website

After opening a new file

Opening a Demonstration Program To open one a file, go to the Projectmenu and select Add to Project Or, right click on the project name in theleft-hand panel and select Add to Project Make sure when you are adding aproject, that it has a .cpp extension. You can see the contents of the file inthe large window by clicking on the namein the left-hand panel

Now, Just hit “ok” one more time

To Compile a Program Once you have either entered in aprogram or opened one of thedemonstration files,It is time to compile and run the program Go to the Execute menu and select Compile Instead, I use: control key F9 Errors will display at the bottom window

Running the program! If there were no errors, you will get in thiscase both agraphics window and a console window:

Placing graphics.h in the package I like to put the graphics.hlibrary in the project, so that Ican see a summary of thefunctions available So, go back to the green symbol and selectgraphics.h from theinclude directory From the include directory,select graphics.h:

Select open .you’ll see this . Notice the graphics.h in the left-handwindow under the name of the project:By Clicking on the graphics.hfile name in the left-handwindow, that file is displayednow in the large window.Don’t modify this file!

Compile again Every time you fix errors or change yourprogram, you will need to compile againGo to the Execute menu and select Compile Or use: control key F9 Errors will display at the bottom window I made a couple of typos so you couldsee what it would look like .

Now, Just hit “ok” one more time

When we get error messages Many times, in C and C when we get errors,the errors actually occur on the line aboveWhen a compiler encounters somethingunexpected, it tries to correct the situation, buttypically by the next line it can’t resolve it andgives an errorSometimes the error messages arerelevant but sometimes they are not.Notice the error occurs in this case on the lineabove the highlighted line I mis-typed end (forgot the lower case L after)I forgot a semicolon!

Disappearing Windows If you run your program, you may noticethe console window flashes (or maybeyou don’t even see it), or the graphicswindow flashes up and goes away You will need to add, at the end, code toask the user to hit enter to pause thesystem until the user is ready, for boththe graphics window and consolewindow

Console Window The console window is where all inputand output occurs that is normal in C If you say cout “blablabla”; it will go tothe console window Most input from the keyboard works withthe console window Any use of cout or cin works with theconsole window in the same way as wewill learn in unix

Graphics Window The graphics window is where alldrawing will occur cin/cout do not work in the graphicswindow We can easily do some basic input,Single character input from the keyboard Mouse input

At the end of All Programs At the end of all programs you will wantthe following: For managing the console window:cout “Press ENTER to continue ” endl;cin.get(); For managing the graphics window:(you don’t have to do this if you also do the above)outtext(“Hit any Key when Done”);getch();

So, the form of all programs is

Some of the Graphics Features Initialize the graphics window(the maximum width is usually 1024x768 or 1280x1024)initwindow(width,height); Clearing the graphics window cleardevice(); Delay the program, so that users can seewhat is happening sending in the number of msecdelay(milliseconds); Wait for a keyboard hit:getch();or,kbhit();

Setting Graphics Attributes . Set Drawing Color (for lines and edges)(colors typically range from 0-15; 0 is usually black and 15 is white) setcolor(color);Set Background Color (usually for text)setbkcolor(color);Set Fill Style and Color (for interiors) Pattern 0-12, 0 empty, 1 solidsetfillstyle(pattern, color)Set Line Style and Thickness Style: 0 solid, 1 dotted, 3 dashedThickness is the width in terms of pixelssetlinestyle(style, pattern, thickness)

The Current Position for graphics Origin on graphics system is Upper LeftSo, positive y values move DOWN X,Y coordinate data are always wholenumbers Setting the Current PositionMove to a current position (x,y are whole numbers)moveto(x,y); Move relative to the current positionmoverel(x,y);

Drawing Lines Drawing a line Drawing from Current Position (from currentposition to the specified coordinate)lineto(x,y); Drawing relative (a delta amount from the current position) The delta amounts would be whole numberslinerel(deltax,deltay); Drawing absolute (from one coordinate to another)linerel(from x, from y, to x, to y);

Drawing Areas Drawing a Circle Given center and radius as whole numberscircle (center x, center y, radius);Drawing a filled Rectangle(given upper left and lower right corners)bar(ul x, ul y, lr x,lr y); Drawing an unfilled Rectangle(given upper left and lower right corners)rectangle(ul x, ul y, lr x, lr y);

How Text Look . Text Formatting Set the justification Horizontal: (0 left, 1 center, 2 right)Vertical: (0 bottom, 1 center, 2 top)settextjustify(horizontal, vertical) Set the text styleFont: (0-11) Direction: 0 left to right direction Character Size: 0 normal, 6 is really big! settextstyle(font,direction, character size)

Messages in the Graphics WIndow Text OutputSet Text color (index ranges 0-15)setcolor(index); Output a message on the graphics windowat the current positionouttext(“messages on graphics window”); Output a message on the graphics windowat the given x,y coordinateouttextxy(x,y,”message”);

Mouse Input! Has there been a mouse click? Right Click is 513Left Click is 516Middle Click is 519 (the wheel )answer ismouseclick(kind) Clear the mouse click(if you don’t do this you can’t get the next mouse click!)clearmouseclick(kind); What was the coordinate when themouse click happens x mousex();y mousey();