Archives from S:\ Drive

Good to keep around methinks
This commit is contained in:
Amrit Panesar committed 2015-04-01 21:23:15 -07:00
1 parent eadaf70b9e
commit 6dd63cc439
606 files changed
+50212

No files matched your search

@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Hangman", "Hangman\Hangman.vcxproj", "{7310FC30-2591-4B40-9580-33268702093E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7310FC30-2591-4B40-9580-33268702093E}.Debug|Win32.ActiveCfg = Debug|Win32
{7310FC30-2591-4B40-9580-33268702093E}.Debug|Win32.Build.0 = Debug|Win32
{7310FC30-2591-4B40-9580-33268702093E}.Release|Win32.ActiveCfg = Release|Win32
{7310FC30-2591-4B40-9580-33268702093E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,458 @@
#include "stdhangman.h"
Hangman::Hangman()
{
attempts = 0;
wordLength = 0;
secretWord = "";
wordList = vector<hangword>();
adminList = vector<string>();
//readdmins();
readFromFile();
blankguesses();
doseed();
}
void Hangman::blankguesses()
{
attempts = 0;
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (unsigned int i = 0; i < alpha.length(); i++)
{
alphabet[i] = alpha[i];
}
}
void Hangman::displayMenu()
{
while (true)
{
cls();
fflush(stdout);
centerline("Main Menu",1);
centerline("==========================",2);
centerline("1. Game Administration",3);
centerline("2. Begin a game",4);
centerline("3. Exit",5);
centerline("==========================",6);
cursorpos(1,7);
cout << "Please make a selection" << endl << ":";
char input;
input = _getch();
cout << input;
switch (input)
{
case '1':
while(doadmin());
break;
case '2':
while(playGame());
break;
case '3':
break;
default:
writeline("Please make a valid selection [1-3]");
writeline(2);
}
if ( input == '3' )
{
break;
}
}
}
bool Hangman::playGame()
{
chooseword();
blankguesses();
while (attempts <= 6)
{
while(!handleinput());
if (revealedword == secretWord)
{
break;
}
}
cls();
if (attempts >= 6)
{
centerline("Hangman - Loss", 1);
centerline(secretWord, 4);
centerline("Sorry! You loose this round", 8);
}
else
{
centerline("Hangman - Winner", 1);
centerline(secretWord, 4);
centerline("Congratulations! You guessed correctly",8);
}
writeline(2);
char input;
while (true)
{
cout << "Play again?" << endl << "[Y/n]";
input = _getch();
cout << input;
if (toupper(input) == 'Y')
{
return true;
}
else if (toupper(input) == 'N')
{
return false;
}
else
{
cout << "Please enter either Yes or No" << endl;
}
}
return true;
}
bool Hangman::notguessed(char inguess)
{
for (int j = 0; j < 26; j++)
{
if (alphabet[j] == inguess)
{
alphabet[j] = ' ';
return true;
}
}
return false;
}
bool Hangman::doadmin()
{
cls();
centerline("Hangman - Administration",1);
centerline("Hangman Administrator Login",4);
cursorpos(1,10);
cout << "Please enter your password" << endl << ":";
return false;
}
bool Hangman::isinword(char inguess)
{
string secret = getSecretWord();
for (unsigned int i = 0; i < secret.length(); i++)
{
if (secret[i] == toupper(inguess))
{
return true;
}
}
return false;
}
void Hangman::drawletters()
{
for (int i = 0; i < 26; i++)
{
if (i == 0)
{
cursorpos (4,6);
}
if (i == 8)
{
cursorpos (4,8);
}
if (i == 16)
{
cursorpos (4,10);
}
if ( i == 24 )
{
cursorpos(4, 12);
}
cout << alphabet[i] << " ";
}
cursorpos(4, 18);
cout << revealedword;
}
bool Hangman::handleinput()
{
cls(); // clear screen
drawseperator(); // do the separator thing
centerline("Hangman",1); // screen title
drawhangman();
drawletters();
fflush(stdout);
cursorpos(0, 20);
writeline("Please enter a letter");
cout << ":";
char input;
input = _getch();
input = toupper(input);
cout << input;
if (isalpha(input) && notguessed(input))
{
if (isinword(input))
{
revealchar(input);
}
else
{
attempts++;
}
return true;
}
else
{
cout << input << " is an invalid input, please try again";
pause();
return false;
}
}
void Hangman::revealchar(char input)
{
string secret = getSecretWord();
for (unsigned int i = 0; i < secret.length(); i++)
{
if (secret[i] == input)
{
revealedword[i] = secret[i];
}
}
}
void Hangman::readFromFile()
{
/*
hangword holdword;
ifstream hangmanfile ("wordlist.bin", ios::in|ios::binary|ios::ate);
if (hangmanfile.is_open())
{
while(!hangmanfile.eof())
{
holdword.Read(hangmanfile);
wordList.push_back(holdword);
}
}
else
{
cout << "Unable to open wordlist.bin for reading. Trying to create it.." << endl;
*/
initFile();
// }
}
void Hangman::initFile()
{
hangword holdword;
ifstream hangwordtxt ("hangmanwordlist.txt", ios::in);
int id = 1;
if (hangwordtxt.is_open())
{
while (!hangwordtxt.eof())
{
string word = "";
getline(hangwordtxt,word);
for (unsigned int j = 0; j < word.length(); j++)
{
word[j] = toupper(word[j]);
}
holdword.setword(word);
holdword.setid(id);
wordList.push_back(holdword);
id++;
}
}
else
{
cout << "Error unable to open hangmanwordlist.txt for reading" << endl;
pause();
}
hangwordtxt.close();
if (wordList.size() != 0)
{
ofstream hangmanbin ("wordlist.bin", ios::out|ios::binary|ios::app);
if (hangmanbin.is_open())
{
for (unsigned int i = 0; i < wordList.size(); i++)
{
wordList[i].Write(hangmanbin);
}
}
else
{
cout << "Error unable to open wordlist.bin for writing" << endl;
pause();
}
}
else
{
cout << "No words in the wordlist. Not creating file." << endl;
pause();
}
}
void Hangman::chooseword()
{
if (wordList.size() == 0)
{
hangword hang;
hang.setid(0);
hang.setword("TEST");
wordList.push_back(hang);
}
int wordindex = rand()%wordList.size();
setSecretWord(wordList[wordindex].getword());
string rev = string(getSecretWord().length(),'_');
revealedword = rev;
}
void Hangman::drawhangman()
{
cursorpos(55, 10);
switch (attempts)
{
case 0:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" |" << endl;
cursorpos(55, 13);
cout <<" |" << endl;
cursorpos(55, 14);
cout <<" |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 1:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" |" << endl;
cursorpos(55, 14);
cout <<" |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 2:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" | |" << endl;
cursorpos(55, 14);
cout <<" |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 3:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" /| |" << endl;
cursorpos(55, 14);
cout <<" |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 4:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" /|\\ |" << endl;
cursorpos(55, 14);
cout <<" |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 5:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" /|\\ |" << endl;
cursorpos(55, 14);
cout <<" | |" << endl;
cursorpos(55, 15);
cout <<" |" << endl;
break;
case 6:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" /|\\ |" << endl;
cursorpos(55, 14);
cout <<" | |" << endl;
cursorpos(55, 15);
cout <<" / |" << endl;
break;
case 7:
cout <<" ___ " << endl;
cursorpos(55, 11);
cout <<" | |" << endl;
cursorpos(55, 12);
cout <<" @ |" << endl;
cursorpos(55, 13);
cout <<" /|\\ |" << endl;
cursorpos(55, 14);
cout <<" | |" << endl;
cursorpos(55, 15);
cout <<" / \\ |" << endl;
break;
}
cursorpos(55, 16);
cout <<" ________|________" << endl;
cursorpos(55, 17);
cout <<" / | /|" << endl;
cursorpos(55, 18);
cout <<"/________________/ /" << endl;
cursorpos(55, 19);
cout <<"|________________|/" << endl;
}
void Hangman::setSecretWord(string word)
{
secretWord = word;
}
string Hangman::getSecretWord()
{
return secretWord;
}
void Hangman::setWordLength(int length)
{
wordLength = length;
}
int Hangman::getWordLength()
{
return wordLength;
}
/***********************************
___
| |
@ |
/|\ |
| |
/ \ |
________|________
/ | /|
/________________/ /
|________________|/
************************************/
@@ -0,0 +1,42 @@
#pragma once
#include "stdhangman.h"
class Hangman
{
private:
int attempts;
vector<hangword> wordList;
vector<string> adminList;
string secretWord;
string revealedword;
int wordLength;
char alphabet[26];
bool emessage;
string message;
public:
Hangman();
bool playGame();
void enterNewWords();
bool isWin();
void convertToUpper();
void readFromFile();
void setSecretWord(string word);
string getSecretWord();
void setWordLength(int length);
int getWordLength();
void initFile();
bool notguessed(char guess);
bool isinword(char guess);
bool doadmin();
void displayMenu();
void drawhangman();
bool handleinput();
void blankguesses();
void revealchar(char reveal);
void chooseword();
void drawletters();
};
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{7310FC30-2591-4B40-9580-33268702093E}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>Hangman</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Hangman.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="Hangword.cpp" />
<ClCompile Include="stdhangman.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Hangman.h" />
<ClInclude Include="main.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="stdhangman.h" />
<ClInclude Include="hangword.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc" />
</ItemGroup>
<ItemGroup>
<Image Include="icon.ico" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Hangman.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stdhangman.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Hangword.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdhangman.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Hangman.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="hangword.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="main.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<Image Include="icon.ico">
<Filter>Resource Files</Filter>
</Image>
</ItemGroup>
</Project>
@@ -0,0 +1,76 @@
#include "stdhangman.h"
int hangword::getid()
{
return id;
}
void hangword::setid(int id)
{
this->id = id;
}
void hangword::setword(string word)
{
this->word = word;
}
string hangword::getword()
{
return word;
}
void hangword::Read(ifstream& file)
{
setid(readid(file));
setword(readword(file));
}
void hangword::Write(ofstream& file)
{
int id = getid();
writeid(file, id);
writeword(file, getword());
}
void hangword::writeword(ofstream& file,const string& str)
{
// get the length of the string data
unsigned int len = str.size();
// write the size:
file.write( reinterpret_cast<const char*>( &len ), sizeof(len) );
// write the actual string data:
file.write( str.c_str(), len );
}
string hangword::readword(ifstream& file)
{
// this probably isn't the optimal way to do it, but whatever
string str;
// get the length
unsigned int len;
file.read( reinterpret_cast<char*>( &len ), sizeof(len) );
// we can't read to string directly, so instead, create a temporary buffer
if(len > 0)
{
char* buf = new char[len];
file.read( buf, len );
str.append( buf, len );
delete[] buf;
}
return str;
}
inline void hangword::writeid(ofstream& file, int& num)
{
file.write(reinterpret_cast<char *>(&num),sizeof(int));
}
int hangword::readid(ifstream& file)
{
int num;
file.read(reinterpret_cast<char *>(&num),sizeof(int));
return num;
}
@@ -0,0 +1,100 @@
fluorine
steapsin
gadoid
optics
master
uninvasive
nettable
preintend
scourge
clinah
planking
autogenetic
inweaved
peipus
corneal
descendant
premonopolizing
wadmoll
grimily
anatolic
uniced
unendeared
geothermic
tarsier
hartmann
actuarially
caffein
antiexpressive
refasten
hostelling
sacculus
teazeling
resolution
demoralised
fletcherizing
decently
mitrephorus
reverser
eudora
comestible
kilpatrick
peroneal
corporate
provisional
plaice
atheneum
juicing
wintery
ellipsoid
avigation
republicanism
bocage
frederika
cleruch
counterbracing
uninstigated
undocumented
voyeurism
catchfly
scatomas
overwore
radiably
rhoecus
eighteenmo
imperfectness
siziness
curable
gradin
breadroot
heresy
ophytic
cosmopolitanizing
cannoneer
haverhill
abingdon
mentor
dissimulator
fazenda
syrphid
rockier
inobservance
hipbone
duckiest
interclub
mollendo
touche
dionysius
impedible
intoner
cichoriaceous
nondrinkable
nevada
pithecanthropus
upswinging
humectant
diakinesis
capacitively
nonaccord
cilice
exuviate
@@ -0,0 +1,25 @@
#pragma once
#include "stdhangman.h"
class hangword
{
private:
int id;
string word;
public:
void setid(int in);
int getid();
void setword(string in);
string getword();
void Read(ifstream& file);
void Write(ofstream& file);
void writeword(ofstream& file,const string& str);
string readword(ifstream& file);
void writeid(ofstream& file, int& num);
int readid(ifstream& file);
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

@@ -0,0 +1,78 @@
#define _CRT_SECURE_NO_WARNINGS
#include "stdhangman.h"
#include "main.h"
#include "resource.h"
using namespace std;
int main()
{
ConsoleSetup(TEXT("Hangman"));
Hangman game;
game.displayMenu();
cout << "Thanks for playing!" << endl << endl;
pause();
return 0;
}
/* ------------------------------------------- Just boring stuff after here ------------------------ */
void ConsoleSetup(TCHAR* input)
{
system("color 1e");
ChangeConsoleIcon(IDI_ICON1);
ChangeConsoleTitle(input);
cout << string(80,'*') << "Welcome to ";
wcout << input;
cout << " " << GetYear() << " Edition!" << endl << string(80,'*') << endl << endl;
}
void ChangeConsoleTitle (const TCHAR* input)
{
time_t t = time(NULL);
tm* timePtr = localtime(&t);
TCHAR szNewTitle[MAX_PATH];
TCHAR szYear[7];
StringCchCopy(szNewTitle, MAX_PATH, TEXT(" "));
StringCchCat(szNewTitle, MAX_PATH, input);
StringCchPrintf(szYear, 7, TEXT(" %d!"), GetYear());
StringCchCat(szNewTitle, MAX_PATH, szYear);
SetConsoleTitle(szNewTitle);
}
void ChangeConsoleIcon (const int resource_number)
{
HMODULE hMainMod = GetModuleHandle(0);
assert (hMainMod);
HICON hMainIcon = ::LoadIcon(hMainMod, MAKEINTRESOURCE(resource_number));
assert (hMainIcon);
// Load kernel 32 library
HMODULE hMod = LoadLibrary( _T( "Kernel32.dll" ));
assert (hMod);
// Load console icon changing procedure
typedef DWORD (__stdcall *SCI)(HICON);
SCI pfnSetConsoleIcon = reinterpret_cast<SCI>(GetProcAddress(hMod, "SetConsoleIcon"));
assert (pfnSetConsoleIcon);
// Call function to change icon
pfnSetConsoleIcon (hMainIcon);
FreeLibrary (hMod);
}// End ChangeIcon
int GetYear()
{
time_t t = time(NULL);
tm* timePtr = localtime(&t);
return timePtr->tm_year + 1900;
}
@@ -0,0 +1,13 @@
void ChangeConsoleTitle (const TCHAR* input);
void ChangeConsoleIcon (int resource_number);
void ConsoleSetup(TCHAR* input);
int GetYear();
enum { NUL = 0, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT,
LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK,
SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US, DEL = 127 };
@@ -0,0 +1,94 @@
#include "stdhangman.h"
// Pause() use conio.h's get character to pause the program
void pause()
{
int c;
cout << endl << "Press any key to continue . . ." << endl;
c = _getch();
if (c == 0 || c == 224) // getch will return a 0 or 244 on error
{
_getch(); // try again
}
}
// cursorpos(X,Y) use ConsoleAPI to place the cursor at a particular position
void cursorpos(int X, int Y)
{
if ( X < 0 ) // off the screen
{
X = 0;
}
if ( Y < 0 )
{
Y = 0;
}
HANDLE hStdOut = GetStdHandle( STD_OUTPUT_HANDLE ); //grab the stdout handle
COORD newpos = { X, Y }; // use the Coord struct to stage the new position
SetConsoleCursorPosition( hStdOut, newpos ); // set the new cursor position
}
// take the input modulus the length by 80, set the cursor position there
void centerline(string input, int linenum)
{
if (input.length() > 80) // over 80 characters? must be centred already
{
cursorpos(0,linenum);
}
int mod = (80-input.length())/2; // formula: input length subtracted from console line length divided by 2
cursorpos(mod,linenum); // set where to write
cout << input << endl; // write it
}
// write a line
void writeline(string input)
{
cout << ' ' << input << endl; // simple function to begin a line with a ' '
}
// write a blank line
void writeline(int num)
{
for (int i = 0; i <= num; i++) // easy function for multiple blank lines
{
cout << endl;
}
}
// do the separator thing
void drawseperator()
{
for (int i = 2; i < 24; i++) // separates the hangman from the words
{
cursorpos(50,i);
cout << "|";
}
}
// seed using micro time. much better than grabbing a random pointer.
void doseed()
{
unsigned __int64 freq;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
double timerFrequency = (1.0/freq);
unsigned __int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
srand(startTime*freq);
}
// use the console api to fill the screen with spaces
void cls() {
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {0, 0};
DWORD written;
CONSOLE_SCREEN_BUFFER_INFO screen_attr;
unsigned size;
GetConsoleScreenBufferInfo(screen, &screen_attr);
size = screen_attr.dwSize.X * screen_attr.dwSize.Y;
FillConsoleOutputCharacterW(screen, ' ', size, pos, &written);
SetConsoleCursorPosition(screen, pos);
}
@@ -0,0 +1,34 @@
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <ctime>
#include <ctype.h>
#include <Windows.h>
#include <conio.h>
#include <time.h>
#include <assert.h>
#include <stdlib.h>
#include <iomanip>
#include <sstream>
#include <tchar.h>
#include <strsafe.h>
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "Hangman.h"
#include "hangword.h"
using namespace std;
void pause();
void cursorpos(int x, int y);
void centerline(string input, int linenum);
void writeline(string input);
void writeline(int num);
void drawseperator();
void doseed();
void cls();
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloWorld", "HelloWorld\HelloWorld.vcxproj", "{1DB2F6D8-614C-4057-97E4-831195518676}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1DB2F6D8-614C-4057-97E4-831195518676}.Debug|Win32.ActiveCfg = Debug|Win32
{1DB2F6D8-614C-4057-97E4-831195518676}.Debug|Win32.Build.0 = Debug|Win32
{1DB2F6D8-614C-4057-97E4-831195518676}.Release|Win32.ActiveCfg = Release|Win32
{1DB2F6D8-614C-4057-97E4-831195518676}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,89 @@
/*****************************************************************************
* Program: Hello World *
* Author: Amrit Panesar <apanesar@coleman.edu> *
* Date: 08/04/2014 *
* Description: Display "Hello World" and do a bit of adding and multlipling *
*****************************************************************************/
#include <conio.h>
#include <string>
#include <iostream>
using namespace std;
bool pause()
{
enum { NUL = 0, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT,
LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK,
SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US, DEL = 127 };
cout << "Press any key to continue..." << endl << endl;
int i = getch();
if ( i == ETX || i == ESC ) // control + c || escape
{
return true;
}
return false;
}
int main(int argc, char* argv[])
{
int i, j, k, l = 0;
while (true)
{
cout << "Hello World!" << endl;
if (pause())
break;
cout << "Adding! Please enter two integers." << endl;
cout << "Number 1: ";
cin >> i;
cout << endl;
cout << "Number 2: ";
cin >> j;
cout << endl;
k = i + j;
cout << "The result is: " << k << endl;
if (pause())
break;
cout << "Comparing! Please enter two integers." << endl;
cout << "Number 1: ";
cin >> i;
cout << endl;
cout << "Number 2: ";
cin >> j;
cout << endl;
if ( i == j )
cout << i << " == " << j << endl;
else
cout << i << " != " << j << endl;
if ( i > j )
cout << i << " > " << j << endl;
else if ( i < j )
cout << i << " < " << j << endl;
if (pause())
break;
cout << "Multiplication! Please enter three integers." << endl;
cout << "Number 1: ";
cin >> i;
cout << endl;
cout << "Number 2: ";
cin >> j;
cout << endl;
cout << "Number 3: ";
cin >> k;
cout << endl;
l = i * j * k;
cout << "The result is: " << l << endl;
if (pause())
break;
}
return 0;
}
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1DB2F6D8-614C-4057-97E4-831195518676}</ProjectGuid>
<RootNamespace>HelloWorld</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="HelloWorld.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="HelloWorld.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PetSim", "PetSim\PetSim.vcxproj", "{8387506E-641F-4005-AF63-F98EBDDF0E48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8387506E-641F-4005-AF63-F98EBDDF0E48}.Debug|Win32.ActiveCfg = Debug|Win32
{8387506E-641F-4005-AF63-F98EBDDF0E48}.Debug|Win32.Build.0 = Debug|Win32
{8387506E-641F-4005-AF63-F98EBDDF0E48}.Release|Win32.ActiveCfg = Release|Win32
{8387506E-641F-4005-AF63-F98EBDDF0E48}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,21 @@
#include "stdhead.h"
using namespace std;
class CenteredOut
{
public:
ostream &m_file;
CenteredOut(ostream &o = cout):m_file(o){};
template <typename T>
CenteredOut &operator<<(const T &a) {
m_file<<a;
return *this;
}
CenteredOut &operator<<(ostream& (*pf) (ostream&)){
m_file<<pf;
return *this;
}
};
@@ -0,0 +1,158 @@
/******************************************************************************
* Pet.cpp - Define a pet object *
* Author: Amrit Panesar <apanesar@coleman.edu> *
* Date: 08/18/2014 *
* License: Released into public domain *
*****************************************************************************/
#include "stdhead.h"
/****************************************** Getters and Setters **************/
int Pet::getHungerLevel()
{
return hungerlevel;
}
void Pet::setHungerLevel(int hunger)
{
hungerlevel = hunger;
}
int Pet::getBoredomLevel()
{
return boredomlevel;
}
void Pet::setBoredomLevel(int boredom)
{
boredomlevel = boredom;
}
string Pet::getName()
{
return name;
}
void Pet::setName(string name)
{
Pet::name = name;
}
/*********************** lets begin ******************************************/
Pet::Pet(string name, int hunger, int boredom)
{
setName(name);
setHungerLevel(hunger);
setBoredomLevel(boredom);
}
void Pet::Talk()
{
if (PetMood() < 7)
cout << getName() << " is feeling happy!" << endl;
else if (PetMood() >= 7 && PetMood() < 16)
cout << getName() << " is feeling okay." << endl;
else if (PetMood() >=16 && PetMood() < 21)
cout << getName() << " is feeling fustrated." << endl;
else
cout << getName() << " is feeling mad!" << endl;
PassTime();
DisplayPetBehavior();
}
void Pet::FeedPet(int in)
{
if (in > 4)
in = 4;
if (in <= 0)
in = 1;
if (getHungerLevel() < in)
setHungerLevel(getHungerLevel()-getHungerLevel());
else
setHungerLevel(getHungerLevel()-in);
cout << getName() << " has been fed " << in << " pellets of food" << endl;
PassTime();
DisplayPetBehavior();
}
void Pet::Play(int in)
{
if (in > 4)
in = 4;
if (in <= 0)
in = 1;
if (getBoredomLevel() < in)
setBoredomLevel(getBoredomLevel()-getBoredomLevel());
else
setBoredomLevel(getBoredomLevel()-in);
cout << getName() << " had " << in << " hours of fun." << endl;
PassTime();
DisplayPetBehavior();
}
void Pet::DisplayPetBehavior()
{
cout << " Boredom: " << getBoredomLevel() << endl;
cout << " Hunger: " << getHungerLevel() << endl;
if (getBoredomLevel() < 3 && getHungerLevel() < 3)
cout << getName() << " is content" << endl;
if ( getBoredomLevel() >= 3 && getBoredomLevel() < 11)
cout << getName() << " is a litte bored" << endl;
else if (getBoredomLevel() >= 11)
cout << getName() << " is very bored" << endl;
if ( getHungerLevel() >= 3 && getHungerLevel() < 11)
cout << getName() << " is a litte hungry" << endl;
else if (getHungerLevel() >= 11)
cout << getName() << " is very hungry" << endl;
cout << endl;
}
int Pet::PetMood()
{
return getBoredomLevel() + getHungerLevel();
}
void Pet::PassTime(int time)
{
setHungerLevel(getHungerLevel()+time);
setBoredomLevel(getBoredomLevel()+time);
}
void Pet::menu()
{
enum { TALK = 1, FEED, PLAY, QUIT };
bool breakout = false;
while (!breakout)
{
cout << "Pet: " << getName() << endl;
cout << TALK << ". Talk with your pet." << endl;
cout << FEED << ". Feed your pet." << endl;
cout << PLAY << ". Play with your pet." << endl;
cout << QUIT << ". Quit your pet." << endl;
cout << "What would you like to do?" << endl << ":";
int menuSelection = getch() - '0';
//cls();
system("cls");
switch (menuSelection)
{
case TALK:
Talk();
break;
case FEED:
FeedPet((((rand()%509)*(rand()%349))%4));
break;
case PLAY:
Play((((rand()%509)*(rand()%349))%4));
break;
case QUIT:
breakout = true;
default:
break;
}
}
}
@@ -0,0 +1,39 @@
/******************************************************************************
* Pet.h - Define a pet object *
* Author: Amrit Panesar <apanesar@coleman.edu> *
* Date: 08/18/2014 *
* License: Released into public domain *
*****************************************************************************/
#include "stdhead.h"
class Pet
{
private:
int hungerlevel;
int boredomlevel;
string name;
int PetMood();
void PassTime(int time = 1);
int getHungerLevel();
void setHungerLevel(int hunger);
int getBoredomLevel();
void setBoredomLevel(int boredom);
string getName();
void setName(string name);
public:
Pet(string name, int hunger = 0, int boredom = 0);
void Talk();
void FeedPet(int in);
void Play(int in);
void DisplayPetBehavior();
void menu();
};
@@ -0,0 +1,173 @@
// PetSim.cpp : Defines the entry point for the console application.
//
#include "stdhead.h"
bool yorn();
void ChangeIcon( const HICON hNewIcon );
int _tmain(int argc, _TCHAR* argv[])
{
int i;
time_t t = time(NULL);
tm* timePtr = localtime(&t);
TCHAR szNewTitle[MAX_PATH];
HMODULE hMainMod = GetModuleHandle( 0 );
assert( hMainMod );
HICON hMainIcon = ::LoadIcon( hMainMod, MAKEINTRESOURCE( IDI_ICON1 ));
assert( hMainIcon );
// Change main window icon
ChangeIcon( hMainIcon );
system("color 1e");
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("Pet Simulator %d"), timePtr->tm_year + 1900);
SetConsoleTitle(szNewTitle);
cout << string(80, '*');
cout << "Welcome to Pet Simulator " << timePtr->tm_year + 1900 << " Edition!" << endl << endl;
cout << string(80, '*');
bool named = false;
string name;
while(!named)
{
cout << endl << endl;
cout << "Step one: Name your pet." << endl;
cout << "It's time to name your pet! Please enter a name for your pet" << endl << ": ";
cin >> name;
cout << "You've named your pet: " << name << endl << endl;
cout << "Is this correct?" << endl << "[Y/n]: ";
i = getch();
cout << (char)i << endl;
bool breakout = false;
if ( i == 89 || 121 || 13 || 27 || 28 || 110)
{
switch (i)
{
case 89:
case 121:
case 13:
named = true;
breakout = true;
break;
case 27:
case 28:
case 110:
breakout = true;
break;
}
}
if (!breakout)
{
if (yorn())
{
named = true;
breakout = true;
}
else
{
breakout = true;
}
}
}
Pet pet = Pet(name);
bool breakout = false;
while(!breakout)
{
pet.menu();
system("cls");
cout << "Would you like to play again?" << endl << "[Y/n]: ";
i = getch();
cout << (char)i << endl;
bool bjorn = false;
if ( i == 89 || 121 || 13 || 27 || 28 || 110)
{
switch (i)
{
case 89:
case 121:
case 13:
bjorn = true;
breakout = false;
break;
case 27:
case 28:
case 110:
bjorn = true;
breakout = true;
break;
default:
bjorn = false;
}
}
if (!bjorn)
{
if (yorn())
{
breakout = false;
}
else
{
breakout = true;
}
}
}
system("cls");
cout << "Game over .." << endl << endl;
cout << "Press any key to continue...";
getch();
return 0;
}
bool yorn()
{
int i = 0;
while (i != 0)
{
cout << "Please enter Y or N :" << endl;
i = getch();
cout << (char)i << endl;
switch (i)
{
case 89:
case 121:
return true;
break;
case 28:
case 110:
return false;
break;
default:
i = 0;
}
}
ChangeIcon( 0 );
}
void ChangeIcon( const HICON hNewIcon )
{
// Load kernel 32 library
HMODULE hMod = LoadLibrary( _T( "Kernel32.dll" ));
assert( hMod );
// Load console icon changing procedure
typedef DWORD ( __stdcall *SCI )( HICON );
SCI pfnSetConsoleIcon = reinterpret_cast<SCI>( GetProcAddress( hMod, "SetConsoleIcon" ));
assert( pfnSetConsoleIcon );
// Call function to change icon
pfnSetConsoleIcon( hNewIcon );
FreeLibrary( hMod );
}// End ChangeIcon
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{8387506E-641F-4005-AF63-F98EBDDF0E48}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>PetSim</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CenteredOut.h" />
<ClInclude Include="Pet.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="stdhead.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="Pet.cpp" />
<ClCompile Include="PetSim.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc" />
</ItemGroup>
<ItemGroup>
<Image Include="icon.ico" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Pet.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="CenteredOut.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="stdhead.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="PetSim.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Pet.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<Image Include="icon.ico">
<Filter>Resource Files</Filter>
</Image>
</ItemGroup>
</Project>
@@ -0,0 +1,40 @@
========================================================================
CONSOLE APPLICATION : PetSim Project Overview
========================================================================
AppWizard has created this PetSim application for you.
This file contains a summary of what you will find in each of the files that
make up your PetSim application.
PetSim.vcxproj
This is the main project file for VC++ projects generated using an Application Wizard.
It contains information about the version of Visual C++ that generated the file, and
information about the platforms, configurations, and project features selected with the
Application Wizard.
PetSim.vcxproj.filters
This is the filters file for VC++ projects generated using an Application Wizard.
It contains information about the association between the files in your project
and the filters. This association is used in the IDE to show grouping of files with
similar extensions under a specific node (for e.g. ".cpp" files are associated with the
"Source Files" filter).
PetSim.cpp
This is the main application source file.
/////////////////////////////////////////////////////////////////////////////
Other standard files:
StdAfx.h, StdAfx.cpp
These files are used to build a precompiled header (PCH) file
named PetSim.pch and a precompiled types file named StdAfx.obj.
/////////////////////////////////////////////////////////////////////////////
Other notes:
AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.
/////////////////////////////////////////////////////////////////////////////
Binary file not shown.

After

Width:  |  Height:  |  Size: 422 KiB

@@ -0,0 +1,29 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
using namespace std;
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
// TODO: reference additional headers your program requires here
#include "CenteredOut.h"
#include "resource.h"
#include "Pet.h"
@@ -0,0 +1,9 @@
Code change needed from the handout.
Use the following code to instantiate your root object in the Pong constructor:
#ifdef _DEBUG
rootPtr = new Root("Plugins_d.cfg"); // initialize Root object
#else
rootPtr = new Root("Plugins.cfg"); // initialize Root object
#endif
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ogre Project", "Ogre Project\Ogre Project.vcproj", "{220D5644-C06B-4022-A9D7-7B43CEBC46D8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Debug|Win32.ActiveCfg = Debug|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Debug|Win32.Build.0 = Debug|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Release|Win32.ActiveCfg = Release|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Ogre Project", "Ogre Project\Ogre Project.vcproj", "{220D5644-C06B-4022-A9D7-7B43CEBC46D8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Debug|Win32.ActiveCfg = Debug|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Debug|Win32.Build.0 = Debug|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Release|Win32.ActiveCfg = Release|Win32
{220D5644-C06B-4022-A9D7-7B43CEBC46D8}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,165 @@
// Ball.cpp
// Ball class member-function definitions.
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
#include <OgreAL.h> // OgreAL class definition
#include "Ball.h" // Ball class definition
#include "Paddle.h" // Paddle class definition
#include "Pong.h" // Pong class definition
// Ball constructor
Ball::Ball( SceneManager *ptr )
{
sceneManagerPtr = ptr; // set pointer to the SceneManager
soundManagerPtr = new OgreAL::SoundManager(); // create SoundManager
speed = 100; // speed of the Ball
direction = Vector3( 1, -1, 0 ); // direction of the Ball
} // end Ball constructor
// Ball destructor
Ball::~Ball()
{
// empty body
} // end Ball destructor
// add the Ball to the scene
void Ball::addToScene()
{
// create Entity and attach it to a node in the scene
Entity *entityPtr =
sceneManagerPtr->createEntity( "Ball", "cube.mesh" );
entityPtr->setMaterialName( "ball" ); // set material for the Ball
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "Ball" ); // create a SceneNode
nodePtr->attachObject( entityPtr ); // attach the Entity to SceneNode
nodePtr->setScale( .05, .05, .05 ); // scale SceneNode
// attach sounds to Ball so they will play from where Ball is
wallSoundPtr = soundManagerPtr->createSound( "wallSound", "wallSound.wav", false );
nodePtr->attachObject( wallSoundPtr ); // attach a sound to SceneNode
paddleSoundPtr = soundManagerPtr->createSound( "paddleSound", "paddleSound.wav", false );
nodePtr->attachObject( paddleSoundPtr ); // attach sound to SceneNode
scoreSoundPtr = soundManagerPtr->createSound( "cheer", "cheer.wav", false ); // create a Sound
// attach the score sound to its own node centered at ( 0, 0, 0 )
sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "score" )->attachObject( scoreSoundPtr );
} // end function addToScene
// move the Ball across the screen
void Ball::moveBall( Real time )
{
nodePtr->translate( ( direction * ( speed * time ) ) ); // move Ball
Vector3 position = nodePtr->getPosition(); // get Ball's new position
// get the positions of the four walls
Vector3 topPosition = sceneManagerPtr->getSceneNode( "WallTop" )->getPosition();
Vector3 bottomPosition = sceneManagerPtr->getSceneNode( "WallBottom" )->getPosition();
Vector3 leftPosition = sceneManagerPtr->getSceneNode( "WallLeft" )->getPosition();
Vector3 rightPosition = sceneManagerPtr->getSceneNode( "WallRight" )->getPosition();
const int WALL_WIDTH = 5; // the width of the walls
// check if the Ball hit the left side
if ( ( position.x - RADIUS ) <= leftPosition.x + ( WALL_WIDTH / 2 ) )
{
nodePtr->setPosition( 0, 0, 0 ); // place Ball in center of screen
Pong::updateScore( Players::PLAYER2 ); // update the score
scoreSoundPtr->play(); // play a sound when player 2 scores
} // end if
// check if the Ball hit the right side
else if (
( position.x + RADIUS ) >= rightPosition.x - ( WALL_WIDTH / 2 ) )
{
nodePtr->setPosition( 0, 0, 0 ); // place Ball in center of screen
Pong::updateScore( Players::PLAYER1 ); // update the score
scoreSoundPtr->play(); // play a sound when player 1 scores
} // end else
// check if the Ball hit the bottom wall
else if (
( position.y - RADIUS ) <= bottomPosition.y + ( WALL_WIDTH / 2 ) &&
direction.y < 0 )
{
// place the Ball on the bottom wall
nodePtr->setPosition( position.x,
( bottomPosition.y + ( WALL_WIDTH / 2 ) + RADIUS ), position.z );
reverseVerticalDirection(); // make the Ball start moving up
} // end else
// check if the Ball hit the top wall
else if (
( position.y + RADIUS ) >= topPosition.y - ( WALL_WIDTH / 2 ) &&
direction.y > 0 )
{
// place the Ball on the top wall
nodePtr->setPosition( position.x,
( topPosition.y - ( WALL_WIDTH / 2 ) - RADIUS ), position.z );
reverseVerticalDirection(); // make the Ball start moving down
} // end else
hitPaddle(); // check if the Ball hit a Paddle
} // end function moveBall
// reverse the Ball's horizontal direction
void Ball::reverseHorizontalDirection()
{
direction *= Vector3( -1, 1, 1 ); // reverse the horizontal direction
paddleSoundPtr->play(); // play the "paddleSound" sound effect
} // end function reverseHorizontalDirection
// reverse the Ball's vertical direction
void Ball::reverseVerticalDirection()
{
direction *= Vector3( 1, -1, 1 ); // reverse the vertical direction
wallSoundPtr->play(); // play the "wallSound" sound effect
} // end function reverseVerticalDirection
// control the Ball colliding with the Paddle
void Ball::hitPaddle()
{
// get the position of the Paddles and the Ball
Vector3 leftPaddlePosition = sceneManagerPtr->
getSceneNode( "LeftPaddle" )->getPosition(); // left Paddle
Vector3 rightPaddlePosition = sceneManagerPtr->
getSceneNode( "RightPaddle" )->getPosition(); // right Paddle
Vector3 ballPosition = nodePtr->getPosition(); // the Ball's position
const int PADDLE_WIDTH = 2; // width of the Paddle
const int PADDLE_HEIGHT = 30; // height of the Paddle
// is the Ball in range of the left Paddle?
if ( ( ballPosition.x - RADIUS ) <
( leftPaddlePosition.x + ( PADDLE_WIDTH / 2 ) ) )
{
// check for collision with left Paddle
if ( ( ballPosition.y - RADIUS ) <
( leftPaddlePosition.y + ( PADDLE_HEIGHT / 2 ) ) &&
( ballPosition.y + RADIUS ) >
( leftPaddlePosition.y - ( PADDLE_HEIGHT / 2 ) ) )
{
reverseHorizontalDirection(); // reverse the Ball's direction
// place the Ball at the edge of the Paddle
nodePtr->setPosition(
( leftPaddlePosition.x + ( PADDLE_WIDTH / 2 ) + RADIUS ),
ballPosition.y, ballPosition.z );
} // end if
} // end if
// is the Ball in range of the right Paddle?
else if ( ( ballPosition.x + RADIUS ) >
( rightPaddlePosition.x - ( PADDLE_WIDTH / 2 ) ) )
{
// check for collision with right Paddle
if ( ( ballPosition.y - RADIUS ) <
( rightPaddlePosition.y + ( PADDLE_HEIGHT / 2 ) ) &&
( ballPosition.y + RADIUS ) >
( rightPaddlePosition.y - ( PADDLE_HEIGHT / 2 ) ) )
{
reverseHorizontalDirection(); // reverse the Ball's direction
// place the Ball at the edge of the Paddle
nodePtr->setPosition(
( rightPaddlePosition.x - ( PADDLE_WIDTH / 2 ) - RADIUS ),
ballPosition.y, ballPosition.z );
} // end if
} // end else
} // end function hitPaddle
@@ -0,0 +1,40 @@
// Ball.h
// Ball class definition (represents a bouncing ball).
#ifndef BALL_H
#define BALL_H
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
#include <OgreAL.h> // OgreAL class definition
class Paddle; // forward declaration of class Paddle
const int RADIUS = 5; // the radius of the Ball
class Ball
{
public:
Ball( SceneManager *sceneManagerPtr ); // constructor
~Ball(); // destructor
void addToScene(); // add the Ball to the scene
void moveBall( Real time ); // move the Ball across the screen
private:
SceneManager *sceneManagerPtr; // pointer to the SceneManager
SceneNode *nodePtr; // pointer to the SceneNode
OgreAL::SoundManager *soundManagerPtr; // pointer to the SoundManager
OgreAL::Sound *wallSoundPtr; // sound played when Ball hits a wall
OgreAL::Sound *paddleSoundPtr; // sound played when Ball hits a Paddle
OgreAL::Sound *scoreSoundPtr; // sound played when someone scores
int speed; // speed of the Ball
Vector3 direction; // direction of the Ball
// private utility functions
void reverseHorizontalDirection(); // change horizontal direction
void reverseVerticalDirection(); // change vertical direction
void hitPaddle(); // control the Ball hitting the Paddles
}; // end class Ball
#endif // BALL_H
@@ -0,0 +1,307 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="Ogre Project"
ProjectGUID="{220D5644-C06B-4022-A9D7-7B43CEBC46D8}"
RootNamespace="OgreProject"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="&quot;$(GDD_OGRE_HOME)\Ogre3D\include&quot;;&quot;$(GDD_OGRE_HOME)\OpenAL\include&quot;;&quot;$(GDD_OGRE_HOME)\OgreAL\include&quot;;&quot;$(GDD_OGRE_HOME)\ogg\include&quot;;&quot;$(GDD_OGRE_HOME)\vorbis\include&quot;"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="OgreMain_d.lib OIS_d.lib OgreAL_d.lib"
LinkIncremental="2"
AdditionalLibraryDirectories="&quot;$(GDD_OGRE_HOME)\Ogre3D\lib\$(ConfigurationName)&quot;;&quot;$(GDD_OGRE_HOME)\OgreAL\lib\$(ConfigurationName)&quot;"
GenerateDebugInformation="true"
SubSystem="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="&quot;$(GDD_OGRE_HOME)\Ogre3D\include&quot;;&quot;$(GDD_OGRE_HOME)\OpenAL\include&quot;;&quot;$(GDD_OGRE_HOME)\OgreAL\include&quot;;&quot;$(GDD_OGRE_HOME)\ogg\include&quot;;&quot;$(GDD_OGRE_HOME)\vorbis\include&quot;"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="OgreMain.lib OIS.lib OgreAL.lib"
LinkIncremental="1"
AdditionalLibraryDirectories="&quot;$(GDD_OGRE_HOME)\Ogre3D\lib\$(ConfigurationName)&quot;;&quot;$(GDD_OGRE_HOME)\OgreAL\lib\$(ConfigurationName)&quot;"
GenerateDebugInformation="true"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\Ball.cpp"
>
</File>
<File
RelativePath=".\Paddle.cpp"
>
</File>
<File
RelativePath=".\Pong.cpp"
>
</File>
<File
RelativePath=".\PongMain.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\Ball.h"
>
</File>
<File
RelativePath=".\Paddle.h"
>
</File>
<File
RelativePath=".\Pong.h"
>
</File>
<File
RelativePath=".\resource.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
<File
RelativePath=".\resources\BlueBold.fontdef"
>
</File>
<File
RelativePath=".\resources\bluebold.ttf"
>
</File>
<File
RelativePath=".\resources\boing.wav"
>
</File>
<File
RelativePath=".\resources\boing1.wav"
>
</File>
<File
RelativePath=".\resources\cheer.wav"
>
</File>
<File
RelativePath=".\resources\cube.mesh"
>
</File>
<File
RelativePath=".\resources\MenuMaterial.material"
>
</File>
<File
RelativePath=".\resources\MenuOverlay.overlay"
>
</File>
<File
RelativePath=".\resources\paddleSound.wav"
>
</File>
<File
RelativePath="..\..\..\..\..\Downloads\pong.ico"
>
</File>
<File
RelativePath="..\..\..\..\..\Downloads\pong.png"
>
</File>
<File
RelativePath=".\resources\PongMaterials.material"
>
</File>
<File
RelativePath=".\resources\PongOverlays.overlay"
>
</File>
<File
RelativePath=".\resources\PongScore.fontdef"
>
</File>
<File
RelativePath=".\resources\PongScore.ttf"
>
</File>
<File
RelativePath=".\resources\PongText.fontdef"
>
</File>
<File
RelativePath=".\resources\PongText.ttf"
>
</File>
<File
RelativePath=".\Resource.rc"
>
</File>
<File
RelativePath=".\resources\sphere.mesh"
>
</File>
<File
RelativePath=".\resources\wallSound.wav"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
@@ -0,0 +1,111 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{220D5644-C06B-4022-A9D7-7B43CEBC46D8}</ProjectGuid>
<RootNamespace>OgreProject</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(GDD_OGRE_HOME)\Ogre3D\include;$(GDD_OGRE_HOME)\OpenAL\include;$(GDD_OGRE_HOME)\OgreAL\include;$(GDD_OGRE_HOME)\ogg\include;$(GDD_OGRE_HOME)\vorbis\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>OgreMain_d.lib;OIS_d.lib;OgreAL_d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(GDD_OGRE_HOME)\Ogre3D\lib\$(Configuration);$(GDD_OGRE_HOME)\OgreAL\lib\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(GDD_OGRE_HOME)\Ogre3D\include;$(GDD_OGRE_HOME)\OpenAL\include;$(GDD_OGRE_HOME)\OgreAL\include;$(GDD_OGRE_HOME)\ogg\include;$(GDD_OGRE_HOME)\vorbis\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>OgreMain.lib;OIS.lib;OgreAL.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(GDD_OGRE_HOME)\Ogre3D\lib\$(Configuration);$(GDD_OGRE_HOME)\OgreAL\lib\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Ball.cpp" />
<ClCompile Include="Paddle.cpp" />
<ClCompile Include="Pong.cpp" />
<ClCompile Include="PongMain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Ball.h" />
<ClInclude Include="Paddle.h" />
<ClInclude Include="Pong.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Ball.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Paddle.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Pong.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="PongMain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Ball.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Paddle.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Pong.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -0,0 +1,45 @@
// Paddle.cpp
// Paddle class member-function definitions.
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
#include "Paddle.h" // Paddle class definition
// constructor
Paddle::Paddle( SceneManager *ptr, String paddleName, int positionX )
{
sceneManagerPtr = ptr; // set the pointer to the SceneManager
name = paddleName; // set the Paddle's name
x = positionX; // set the Paddle's x coordinate
} // end Paddle constructor
// destructor
Paddle::~Paddle()
{
// empty body
} // end Paddle default destructor
// add the Paddle to the scene
void Paddle::addToScene()
{
Entity *entityPtr = sceneManagerPtr->
createEntity( name, "cube.mesh" ); // create an Entity
entityPtr->setMaterialName( "paddle" ); // set the Paddle's material
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( name ); // create a SceneNode for the Paddle
nodePtr->attachObject( entityPtr ); // attach Paddle to the SceneNode
nodePtr->setScale( .02, .3, .1 ); // set the Paddle's size
nodePtr->setPosition( x, 0, 0 ); // set the Paddle's position
} // end function addToScene
// move the Paddle up and down the screen
void Paddle::movePaddle( const Vector3 &direction )
{
nodePtr->translate( direction ); // move the Paddle
if ( nodePtr->getPosition().y > 52.5 ) // top of the box
nodePtr->setPosition( x, 52.5, 0 ); // place Paddle at top of box
else if ( nodePtr->getPosition().y < -52.5 ) // bottom of the box
// place the Paddle at the bottom of the box
nodePtr->setPosition( x, -52.5, 0 );
} // end function movePaddle
@@ -0,0 +1,27 @@
// Paddle.h
// Paddle class definition (represents a paddle in the game).
#ifndef PADDLE_H
#define PADDLE_H
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
class Paddle
{
public:
// constructor
Paddle( SceneManager *sceneManagerPtr, String paddleName,
int positionX);
~Paddle(); // destructor
void addToScene(); // add a Paddle to the scene
void movePaddle( const Vector3 &direction ); // move a Paddle
private:
SceneManager* sceneManagerPtr; // pointer to the SceneManager
SceneNode *nodePtr; // pointer to a SceneNode
String name; // name of the Paddle
int x; // x coordinate of the Paddle
}; // end of class Paddle
#endif // PADDLE_H
@@ -0,0 +1,14 @@
# Defines plugins to load
# Define plugin folder
PluginFolder=.
# Define plugins
Plugin=RenderSystem_Direct3D9
Plugin=RenderSystem_GL
Plugin=Plugin_ParticleFX
Plugin=Plugin_BSPSceneManager
Plugin=Plugin_OctreeSceneManager
Plugin=Plugin_CgProgramManager
@@ -0,0 +1,14 @@
# Defines plugins to load
# Define plugin folder
PluginFolder=.
# Define plugins
Plugin=RenderSystem_Direct3D9_d
Plugin=RenderSystem_GL_d
Plugin=Plugin_ParticleFX_d
Plugin=Plugin_BSPSceneManager_d
Plugin=Plugin_OctreeSceneManager_d
Plugin=Plugin_CgProgramManager_d
@@ -0,0 +1,407 @@
// Pong.cpp
// Pong class member-function definitions.
#include <sstream>
#include <stdexcept>
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
using namespace std; // use the Standard C namespace
#include <OgreAL.h> // OgreAL class definition
#include <OgreStringConverter.h> // OgreStringConverter class definition
#include <OIS/OISEvents.h> // OISEvents class definition
#include <OIS/OISInputManager.h> // OISInputManager class definition
#include <OIS/OISKeyboard.h> // OISKeyboard class definition
#include "Ball.h" // Ball class definition
#include "Paddle.h" // Paddle class definition
#include "Pong.h" // Pong class definition
int Pong::player1Score = 0; // initialize player 1's score to 0
int Pong::player2Score = 0; // initialize player 2's score to 0
bool Pong::wait = false; // initialize wait to false
// directions to move the Paddles
const Vector3 PADDLE_DOWN = Vector3( 0, -1, 0 );
const Vector3 PADDLE_UP = Vector3( 0, 1, 0 );
// constructor
Pong::Pong()
{
#ifdef _DEBUG
rootPtr = new Root("Plugins_d.cfg"); // initialize Root object
#else
rootPtr = new Root("Plugins.cfg"); // initialize Root object
#endif
// use the Ogre Config Dialog Box to choose the settings
//if ( !( rootPtr->showConfigDialog() ) ) // user canceled the dialog box
// throw runtime_error( "User Canceled Ogre Setup Dialog Box." );
WIN32_FIND_DATA w32FD;
HANDLE h = FindFirstFile(L"ogre.cfg", &w32FD);
if(FAILED(h)){
if(!rootPtr->showConfigDialog()){
throw runtime_error( "User Canceled Ogre Setup Dialog Box." );
} else {
rootPtr->saveConfig();
}
} else {
rootPtr->restoreConfig();
}
// get a pointer to the RenderWindow
windowPtr = rootPtr->initialise( true, "Pong! 2014 Edition" );
// create the SceneManager
sceneManagerPtr = rootPtr->createSceneManager( ST_GENERIC );
// create the Camera
cameraPtr = sceneManagerPtr->createCamera( "PongCamera" );
cameraPtr->setPosition( Vector3( 0, 0, 200 ) ); // set Camera position
cameraPtr->lookAt( Vector3( 0, 0, 0 ) ); // set where Camera looks
cameraPtr->setNearClipDistance( 5 ); // near distance Camera can see
cameraPtr->setFarClipDistance( 1000 ); // far distance Camera can see
// create the Viewport
viewportPtr = windowPtr->addViewport( cameraPtr );
viewportPtr->setBackgroundColour( ColourValue( 0, 0, 0 ) );
// set the Camera's aspect ratio
cameraPtr->setAspectRatio( Real( viewportPtr->getActualWidth() ) /( viewportPtr->getActualHeight() ) );
// set the scene's ambient light
sceneManagerPtr->setAmbientLight( ColourValue( 0.75, 0.75, 0.75 ) );
// create the Light
Light *lightPtr = sceneManagerPtr->createLight( "Light" ); // a Light
lightPtr->setPosition( 0, 0, 50 ); // set the Light's position
unsigned long hWnd; // variable to hold the window handle
windowPtr->getCustomAttribute( "WINDOW", &hWnd ); // get window handle
OIS::ParamList paramList; // create an OIS ParamList
// add the window to the ParamList
paramList.insert( OIS::ParamList::value_type( "WINDOW", Ogre::StringConverter::toString( hWnd ) ) );
// create the InputManager
inputManagerPtr = OIS::InputManager::createInputSystem( paramList );
keyboardPtr = static_cast< OIS::Keyboard* >( inputManagerPtr->createInputObject( OIS::OISKeyboard, true ) ); // create a Keyboard
keyboardPtr->setEventCallback( this ); // add a KeyListener
rootPtr->addFrameListener( this ); // add this Pong as a FrameListener
// load resources for Pong
ResourceGroupManager::getSingleton().addResourceLocation("resources", "FileSystem", "Pong" );
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
quit = pause = false; // player has not quit or paused the game
time = 0; // initialize the time since Ball was reset to 0
paddle[0] = paddle[1] = 0;
} // end Pong constructor
// Pong destructor erases objects contained in a Pong object
Pong::~Pong()
{
Ogre::WindowEventUtilities::removeWindowEventListener(windowPtr, this);
windowClosed(windowPtr);
// free dynamically allocated memory for Keyboard/mouse
if(inputManagerPtr)
{
//inputManagerPtr->destroyInputObject( mousePtr );
//mousePtr = 0;
inputManagerPtr->destroyInputObject( keyboardPtr );
keyboardPtr = 0;
OIS::InputManager::destroyInputSystem(inputManagerPtr);
inputManagerPtr = 0;
}
// free dynamically allocated memory for Root
delete rootPtr; // release memory pointer points to
rootPtr = 0; // point pointer at 0
// free dynamically allocated memory for Ball
delete ballPtr; // release memory pointer points to
ballPtr = 0; // point pointer at 0
// free dynamically allocated memory for Paddle
delete leftPaddlePtr; // release memory pointer points to
leftPaddlePtr = 0; // point pointer at 0
// free dynamically allocated memory for Paddle
delete rightPaddlePtr; // release memory pointer points to
rightPaddlePtr = 0; // point pointer at 0
} // end Pong destructor
// create the scene to be displayed
void Pong::createScene()
{
// get a pointer to the Score Overlay
Overlay *scoreOverlayPtr = OverlayManager::getSingleton().getByName( "Score" );
scoreOverlayPtr->show(); // show the Overlay
// make the game objects
ballPtr = new Ball( sceneManagerPtr ); // make the Ball
ballPtr->addToScene(); // add the Ball to the scene
rightPaddlePtr = new Paddle( sceneManagerPtr, "RightPaddle", 90 );
rightPaddlePtr->addToScene(); // add a Paddle to the scene
leftPaddlePtr = new Paddle( sceneManagerPtr, "LeftPaddle", -90 );
leftPaddlePtr->addToScene(); // add a Paddle to the scene
// create the walls
Entity *entityPtr = sceneManagerPtr->createEntity( "WallLeft", "cube.mesh" ); // create the left wall
entityPtr->setMaterialName( "wall" ); // set material for left wall
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
// create the SceneNode for the left wall
SceneNode *nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "WallLeft" );
nodePtr->attachObject( entityPtr ); // attach left wall to SceneNode
nodePtr->setPosition( -95, 0, 0 ); // set the left wall's position
nodePtr->setScale( .05, 1.45, .1 ); // set the left wall's size
entityPtr = sceneManagerPtr->createEntity( "WallRight", "cube.mesh" );
entityPtr->setMaterialName( "wall" ); // set material for right wall
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
// create the SceneNode for the right wall
nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "WallRight" );
nodePtr->attachObject( entityPtr ); // attach right wall to SceneNode
nodePtr->setPosition( 95, 0, 0 ); // set the right wall's position
nodePtr->setScale( .05, 1.45, .1 ); // set the right wall's size
entityPtr = sceneManagerPtr->createEntity( "WallBottom", "cube.mesh" );
entityPtr->setMaterialName( "wall" ); // set material for bottom wall
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
// create the SceneNode for the bottom wall
nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "WallBottom" );
nodePtr->attachObject( entityPtr ); // attach bottom wall to SceneNode
nodePtr->setPosition( 0, -70, 0 ); // set the bottom wall's position
nodePtr->setScale( 1.95, .05, .1 ); // set bottom wall's size
entityPtr = sceneManagerPtr->createEntity( "WallTop", "cube.mesh" );
entityPtr->setMaterialName( "wall" ); // set the material for wall
entityPtr->setNormaliseNormals( true ); // fix the normals when scaled
// create the SceneNode for the top wall
nodePtr = sceneManagerPtr->getRootSceneNode()->createChildSceneNode( "WallTop" );
nodePtr->attachObject( entityPtr ); // attach top wall to SceneNode
nodePtr->setPosition( 0, 70, 0 ); // set the top wall's position
nodePtr->setScale( 1.95, .05, .1 ); // set the top wall's size
} // end function createScene
// start a game of Pong
void Pong::run()
{
createScene(); // create the scene
Ogre::WindowEventUtilities::addWindowEventListener(windowPtr, this);
rootPtr->startRendering(); // start rendering frames
} // end function run
// update the score
void Pong::updateScore( Players player )
{
// increase the correct player's score
if ( player == Players::PLAYER1 )
player1Score++;
else
player2Score++;
wait = true; // the game should wait to restart the Ball
updateScoreText(); // update the score text on the screen
} // end function updateScore
// update the score text
void Pong::updateScoreText()
{
ostringstream scoreText; // text to be displayed
scoreText << "P2: " << player2Score; // make the text
// get the right player's TextArea
OverlayElement *textElementPtr = OverlayManager::getSingletonPtr()->getOverlayElement( "right" );
textElementPtr->setCaption( scoreText.str() ); // set the text
scoreText.str( "" ); // reset the text in scoreText
scoreText << "P1: " << player1Score; // make the text
// get the left player's TextArea
textElementPtr = OverlayManager::getSingletonPtr()->getOverlayElement( "left" );
textElementPtr->setCaption( scoreText.str() ); // set the text
} // end function updateScoreText
// respond to user keyboard input
bool Pong::keyPressed( const OIS::KeyEvent &keyEventRef )
{
// if the game is not paused
if ( !pause )
{
// process KeyEvents that apply when the game is not paused
switch ( keyEventRef.key )
{
case OIS::KC_ESCAPE: // escape key hit: quit
quit = true;
break;
case OIS::KC_UP: // up-arrow key hit: move the right Paddle up
paddle[0] = 1;
break;
case OIS::KC_DOWN: // down-arrow key hit: move the right Paddle down
paddle[0] = -1;
break;
case OIS::KC_NUMPAD8: // 8 key hit: move left Paddle up
paddle[1] = 1;
break;
case OIS::KC_NUMPAD2: // 2 key hit: move left Paddle down
paddle[1] = -1;
break;
case OIS::KC_W: // W key hit: rotate board 'up'
break;
case OIS::KC_A: // A key hit: rotate board 'left'
break;
case OIS::KC_S: // S key hit: rorate board 'down'
break;
case OIS::KC_D: // D key hit: rotate board 'right'
break;
case OIS::KC_P: // P key hit: pause the game
pause = true; // set pause to true when the user pauses the game
Overlay *pauseOverlayPtr = OverlayManager::getSingleton().getByName( "PauseOverlay" );
pauseOverlayPtr->show(); // show the pause Overlay
break;
} // end switch
} // end if
else // game is paused
{
// user hit 'R' on the keyboard
if ( keyEventRef.key == OIS::KC_R )
{
pause = false; // set pause to false when user resumes the game
Overlay *pauseOverlayPtr = OverlayManager::getSingleton().getByName( "PauseOverlay" );
pauseOverlayPtr->hide(); // hide the pause Overlay
} // end if
} // end else
return true;
} // end function keyPressed
// process key released events
bool Pong::keyReleased( const OIS::KeyEvent &keyEventRef )
{
switch ( keyEventRef.key )
{
case OIS::KC_UP: // up-arrow key released, stop moving that direction
if (paddle[0] != -1) // if we're not moving down already
paddle[0] = 0;
break;
case OIS::KC_DOWN: // down-arrow key released, stop moving that direction
if (paddle[0] != 1) // if we're not moving up already
paddle[0] = 0;
break;
case OIS::KC_NUMPAD8: // number pad 8 key released, stop moving that direction
if (paddle[1] != -1) // if we're not moving down already
paddle[1] = 0;
break;
case OIS::KC_NUMPAD2: // number pad 2 key released, stop moving that direction
if (paddle[1] != 1) // if we're not moving up already
paddle[1] = 0;
break;
}
return true;
} // end function keyReleased
// return true if the program should render the next frame
bool Pong::frameEnded( const FrameEvent &frameEvent )
{
WindowEventUtilities::messagePump();
if(windowPtr->isClosed())
{
return false;
}
return !quit; // quit = false if the user hasn't quit yet
} // end function frameEnded
// process game logic, return true if the next frame should be rendered
bool Pong::frameStarted( const FrameEvent &frameEvent )
{
keyboardPtr->capture(); // get keyboard events
// paddle moving logic
if (paddle[0] != 0) // [0] = left paddle
{
//process
if (paddle[0] < 0) // go down
{
leftPaddlePtr->movePaddle( PADDLE_DOWN );
} else if (paddle[0] > 0) // go up
{
leftPaddlePtr->movePaddle( PADDLE_UP );
}
}
if (paddle[1] != 0) // [1] = right paddle
{
//process
if (paddle[1] < 0) // go down
{
rightPaddlePtr->movePaddle( PADDLE_DOWN );
} else if (paddle[1] > 0) // go up
{
rightPaddlePtr->movePaddle( PADDLE_UP );
}
}
// the game is not paused and the Ball should move
if ( !wait && !pause )
{
// move the Ball
ballPtr->moveBall( frameEvent.timeSinceLastFrame );
} // end if
// don't move the Ball if wait is true
else if ( wait )
{
// increase time if it is less than 4 seconds
if ( time < 4 )
// add the seconds since the last frame
time += frameEvent.timeSinceLastFrame;
else
{
wait = false; // shouldn't wait to move the Ball any more
time = 0; // reset the control variable to 0
} // end else
} // end else
return !quit; // quit = false if the user hasn't quit yet
} // end function frameStarted
//Adjust mouse clipping area
void Pong::windowResized(Ogre::RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mousePtr->getMouseState();
ms.width = width;
ms.height = height;
}
//Unattach OIS before window shutdown (very important under Linux)
void Pong::windowClosed(Ogre::RenderWindow* rw)
{
}
bool Pong::mousePressed(const OIS::MouseEvent &,OIS::MouseButtonID)
{
return true;
}
bool Pong::mouseReleased(const OIS::MouseEvent &,OIS::MouseButtonID)
{
return true;
}
bool Pong::mouseMoved(const OIS::MouseEvent &)
{
return true;
}
@@ -0,0 +1,80 @@
// Pong.h
// Pong class definition (represents a game of Pong).
#ifndef PONG_H
#define PONG_H
#include <Ogre.h> // Ogre class definition
using namespace Ogre; // use the Ogre namespace
#include <OIS\OISEvents.h> // OISEvents class definition
#include <OIS\OISInputManager.h> // OISInputManager class definition
#include <OIS\OISKeyboard.h> // OISKeyboard class definition
#include <OIS\OISMouse.h>
#include <OgreWindowEventUtilities.h>
class Ball; // forward declaration of class Ball
class Paddle; // forward declaration of class Paddle
enum Players { PLAYER1, PLAYER2 };
class Pong : public FrameListener, public OIS::KeyListener, public Ogre::WindowEventListener, public OIS::MouseListener
{
public:
Pong(); // constructor
~Pong(); // destructor
void run(); // run a game of Pong
// handle keyPressed and keyReleased events
virtual bool keyPressed( const OIS::KeyEvent &keyEventRef );
virtual bool keyReleased( const OIS::KeyEvent &keyEventRef );
// handle mouseMoved, mousePressed, and mouseReleased events
virtual bool mousePressed(const OIS::MouseEvent &,OIS::MouseButtonID);
virtual bool mouseReleased(const OIS::MouseEvent &,OIS::MouseButtonID);
virtual bool mouseMoved(const OIS::MouseEvent &);
// move the game objects and control interactions between frames
virtual bool frameStarted( const FrameEvent &frameEvent );
virtual bool frameEnded( const FrameEvent &frameEvent );
static void updateScore( Players player); // update the score
private:
void createScene(); // create the scene to be rendered
static void updateScoreText(); // update the score on the screen
// Ogre objects
Root *rootPtr; // pointer to Ogre's Root object
SceneManager *sceneManagerPtr; // pointer to the SceneManager
RenderWindow *windowPtr; // pointer to RenderWindow to render scene in
Viewport *viewportPtr; // pointer to Viewport, area that a camera sees
Camera *cameraPtr; // pointer to a Camera in the scene
// OIS input objects
OIS::InputManager *inputManagerPtr; // pointer to the InputManager
OIS::Keyboard *keyboardPtr; // pointer to the Keyboard
OIS::Mouse *mousePtr; // pointer to the mouse
// Ogre::WindowEventListener
virtual void windowResized(Ogre::RenderWindow* rw);
virtual void windowClosed(Ogre::RenderWindow* rw);
// game objects
Ball *ballPtr; // pointer to the Ball
Paddle *leftPaddlePtr; // pointer to player 1's Paddle
Paddle *rightPaddlePtr; // pointer to player 2's Paddle
// variables to control game states
bool quit, pause; // did user quit or pause the game?
Real time; // used to delay the motion of a new Ball
static bool wait; // should the Ball's movement be delayed?
static int player1Score; // player 1's score
static int player2Score; // player 2's score
int paddle[2];
}; // end class Pong
#endif // PONG_H
@@ -0,0 +1,37 @@
// PongMain.cpp
// Driver program for the game of Pong
#include <iostream>
#include "Pong.h" // Pong class definition
// If running on Windows, include windows.h and define WinMain function
#if OGRE_PLATFORM==PLATFORM_WIN32 || OGRE_PLATFORM==OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
// If not, define normal main function
#else
int main( int argc, char **argv )
#endif
{
try
{
Pong game; // create a Pong object
game.run(); // start the Pong game
} // end try
catch ( std::runtime_error &error )
{
#if OGRE_PLATFORM==PLATFORM_WIN32 || OGRE_PLATFORM==OGRE_PLATFORM_WIN32
MessageBoxA( NULL, error.what(), "Exception Thrown!",
MB_OK | MB_ICONERROR | MB_TASKMODAL );
#else
std::cerr << "Exception Thrown: " << error.what() << std::endl;
#endif
} // end catch
return 0;
} // end main
@@ -0,0 +1,122 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,3,3,7
PRODUCTVERSION 1,3,3,7
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x2fL
#else
FILEFLAGS 0x2eL
#endif
FILEOS 0x4L
FILETYPE 0x0L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "Comments", "Pong! 2014 Edition"
VALUE "CompanyName", "Copyright Amrit Panesar 2014"
VALUE "FileDescription", "Pong - a 2 bit game on a 32 bit computer"
VALUE "FileVersion", "1, 3, 3, 7"
VALUE "InternalName", "Pong"
VALUE "LegalCopyright", "Copyright Amrit Panesar (C) 2014"
VALUE "LegalTrademarks", "Amrit Panesar"
VALUE "OriginalFilename", "Pong.exe"
VALUE "PrivateBuild", "This build is far from private"
VALUE "ProductName", "Pong!"
VALUE "ProductVersion", "1, 3, 3, 7"
VALUE "SpecialBuild", "All my builds are special"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
/////////////////////////////////////////////////////////////////////////////
//
// PNG
//
IDB_PNG1 PNG "C:\\Users\\77260\\Downloads\\pong.png"
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "C:\\Users\\77260\\Downloads\\pong.ico"
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
@@ -0,0 +1,19 @@
Render System=OpenGL Rendering Subsystem
[Direct3D9 Rendering Subsystem]
Allow NVPerfHUD=No
Anti aliasing=None
Floating-point mode=Fastest
Full Screen=Yes
Rendering Device=NVIDIA GeForce GTX 460
VSync=No
Video Mode=1280 x 1024 @ 32-bit colour
[OpenGL Rendering Subsystem]
Colour Depth=32
Display Frequency=N/A
FSAA=16
Full Screen=No
RTT Preferred Mode=PBuffer
VSync=Yes
Video Mode=1024 x 768
@@ -0,0 +1,17 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Resource.rc
//
#define IDB_PNG1 101
#define IDI_ICON1 102
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
@@ -0,0 +1,24 @@
# Resource locations to be added to the 'boostrap' path
# This also contains the minimum you need to use the Ogre example framework
[Bootstrap]
FileSystem=resources
Zip=../../media/packs/OgreCore.zip
# Resource locations to be added to the default path
[General]
FileSystem=../../media
FileSystem=../../media/fonts
FileSystem=../../media/materials/programs
FileSystem=../../media/materials/scripts
FileSystem=../../media/materials/textures
FileSystem=../../media/models
FileSystem=../../media/overlays
FileSystem=../../media/particle
FileSystem=../../media/gui
FileSystem=../../media/DeferredShadingMedia
Zip=../../media/packs/cubemap.zip
Zip=../../media/packs/cubemapsJS.zip
Zip=../../media/packs/dragon.zip
Zip=../../media/packs/fresneldemo.zip
Zip=../../media/packs/ogretestmap.zip
Zip=../../media/packs/skybox.zip
@@ -0,0 +1,15 @@
// define the BlueBold font
BlueBold
{
// define the font type
type truetype
// set the source file for the font
source bluebold.ttf
// set the font size
size 16
// set the font resolution (96 is standard)
resolution 96
}
@@ -0,0 +1,12 @@
// menu material definition
material menu
{
technique
{
pass
{
ambient 1.0 1.0 1.0
diffuse 1.0 1.0 1.0
}
}
}
@@ -0,0 +1,167 @@
// An Overlay to display an options menu
MenuOverlay
{
// set a high z-order to display on top of everything
zorder 600
// the root container for the menu items
container Panel(rootPanel)
{
material menu
// text for the root Panel
element TextArea(instructionsText)
{
// position the text toward the bottom center of the screen
top 0.8
left 0.2
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Press Enter to start or Esc to exit
}
// end of instructionsText
// container for the Ball options
container Panel(ballPanel)
{
// position the container toward the left side of the screen
top 0.1
left 0.1
width 0.3
height 0.5
// TextAreas to display Ball options
element TextArea(ballOptionsTitle)
{
// position and size the TextArea
height 0.1
left 0.05
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Ball Options
}
// end of ballOptionsTitle
element TextArea(ballSlow)
{
// position and size the text
top 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Slow Ball (Press A)
}
// end of ballSlow
element TextArea(ballMedium)
{
// position and size the text
top 0.3
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Medium Ball (Press B)
}
// end of ballMedium
element TextArea(ballFast)
{
// position and size the text
top 0.4
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Fast Ball (Press C)
}
// end of ballFast
}
// end of ballPanel
// container for the Paddle options
container Panel(paddlePanel)
{
// position the container toward the right side of the screen
top 0.1
left 0.5
width 0.3
height 0.5
// TextAreas to display Paddle options
element TextArea(paddleOptionsTitle)
{
// position and size the text
height 0.1
left 0.05
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Paddle Options
}
// end of paddleOptionsTitle
element TextArea(paddleSlow)
{
// position and size the text
top 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Slow Paddles (Press 1)
}
// end of paddleSlow
element TextArea(paddleMedium)
{
// position and size the text
top 0.3
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Medium Paddles (Press 2)
}
// end of paddleMedium
element TextArea(paddleFast)
{
// position and size the text
top 0.4
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1 1 1
caption Fast Paddles (Press 3)
}
// end of paddleFast
}
// end of paddlePanel
}
// end of rootPanel
}
// end of MenuOverlay
@@ -0,0 +1,51 @@
// ball material definition
material ball
{
// define one technique for rendering the Ball
technique
{
// render the Ball in one pass
pass
{
// color the Ball White
ambient 1 1 1
diffuse 1 1 1
specular 1 1 1 255
}
}
}
// paddle material definition
material paddle
{
// define one technique for rendering a Paddle
technique
{
// render a Paddle in one pass
pass
{
// color the Paddle white
ambient 1 1 1
diffuse 1 1 1
specular 1 1 1 255
}
}
}
// wall material definition
material wall
{
// define one technique for rendering a wall
technique
{
// render a wall in one pass
pass
{
// color the wall cyan
ambient 0 0 0
diffuse 0 0 0
specular 0 0 0 255
}
}
}
@@ -0,0 +1,146 @@
// An Overlay to display the score
Score
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text areas
container Panel(ScorePanel)
{
// use relative metrics mode to position this container at the
// top-left corner of the screen
metrics_mode relative
left 0.0
top 0.0
// make it 1/10 the height and the full width of the screen
width 1.0
height .1
// create a TextAreaOverlayElement to display player 1's score
element TextArea(left)
{
// position and size the element relative to the container
metrics_mode relative
// position it at the top of the container 5% from the left and
// make it the same height and half as long as the container
left 0.05
top 0.0
width 0.5
height 1.0
// set font use for caption and set the size and color
font_name PongScore
char_height .05
colour 1 1 1
caption P1: 0
}
// create a TextAreaOverlayElement to display player 2's score
element TextArea(right)
{
// position and size the element relative to the container
metrics_mode relative
// position it at the top of the container 69% from the left and
// make it the same height as the container, stretch to the end
left 0.69
top 0.0
width 0.5
height 1.0
// set font use for caption and set the size and color
font_name PongScore
char_height 0.05
colour 1 1 1
caption P2: 0
}
}
}
// An Overlay to display "Game Paused" when the player pauses the game
PauseOverlay
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text area
container Panel(Pause)
{
// use relative metrics mode to position and size this container
metrics_mode relative
// place the container at the top-left corner of the window
left 0.0
top 0.0
// make the container the same size as the window
width 1.0
height 1.0
// create a TextAreaOverlayElement to display the text
element TextArea(pauseText)
{
// position and size the element relative to its container
metrics_mode relative
// center it vertically in the container
vert_align center
// put the left corner 4/10 from the left of the container and
// make it 2/10 the width of the container and 1/10 the height
left 0.4
width 0.2
height 0.1
// set font use for caption and set the size and color
font_name PongText
char_height 0.05
colour 1 1 1
caption Game Paused (Press R to Continue)
}
}
}
// An Overlay to display which player won the game
WinnerOverlay
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text area
container Panel(Winner)
{
// use relative metrics mode to position and size this container
metrics_mode relative
// place the container at the top-left corner of the window
left 0.0
top 0.0
// make the container the same size as the window
width 1.0
height 1.0
// create a TextAreaOverlayElement to display the text
element TextArea(winnerText)
{
// position and size the element relative to its container
metrics_mode relative
// put the left corner 4/10 from the left of the container and
// make it 2/10 the width of the container and 1/10 the height
left 0.4
top 0.3
width 0.2
height 0.1
// set font use for caption and set the size and color
font_name PongText
char_height 0.05
colour 1 1 1
}
}
}
@@ -0,0 +1,15 @@
// define the PongScore font
PongScore
{
// define the font type
type truetype
// set the source file for the font
source PongScore.ttf
// set the font size
size 16
// set the font resolution (96 is standard)
resolution 96
}
@@ -0,0 +1,15 @@
// define the PongText font
PongText
{
// define the font type
type truetype
// set the source file for the font
source PongText.ttf
// set the font size
size 16
// set the font resolution (96 is standard)
resolution 96
}
@@ -0,0 +1,15 @@
// define the BlueBold font
BlueBold
{
// define the font type
type truetype
// set the source file for the font
source bluebold.ttf
// set the font size
size 16
// set the font resolution (96 is standard)
resolution 96
}
@@ -0,0 +1,12 @@
// menu material definition
material menu
{
technique
{
pass
{
ambient 1.0 1.0 1.0
diffuse 1.0 1.0 1.0
}
}
}
@@ -0,0 +1,167 @@
// An Overlay to display an options menu
MenuOverlay
{
// set a high z-order to display on top of everything
zorder 600
// the root container for the menu items
container Panel(rootPanel)
{
material menu
// text for the root Panel
element TextArea(instructionsText)
{
// position the text toward the bottom center of the screen
top 0.8
left 0.2
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Press Enter to start or Esc to exit
}
// end of instructionsText
// container for the Ball options
container Panel(ballPanel)
{
// position the container toward the left side of the screen
top 0.1
left 0.1
width 0.3
height 0.5
// TextAreas to display Ball options
element TextArea(ballOptionsTitle)
{
// position and size the TextArea
height 0.1
left 0.05
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Ball Options
}
// end of ballOptionsTitle
element TextArea(ballSlow)
{
// position and size the text
top 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Slow Ball (Press A)
}
// end of ballSlow
element TextArea(ballMedium)
{
// position and size the text
top 0.3
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1.0 0 0
caption Medium Ball (Press B)
}
// end of ballMedium
element TextArea(ballFast)
{
// position and size the text
top 0.4
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Fast Ball (Press C)
}
// end of ballFast
}
// end of ballPanel
// container for the Paddle options
container Panel(paddlePanel)
{
// position the container toward the right side of the screen
top 0.1
left 0.5
width 0.3
height 0.5
// TextAreas to display Paddle options
element TextArea(paddleOptionsTitle)
{
// position and size the text
height 0.1
left 0.05
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Paddle Options
}
// end of paddleOptionsTitle
element TextArea(paddleSlow)
{
// position and size the text
top 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Slow Paddles (Press 1)
}
// end of paddleSlow
element TextArea(paddleMedium)
{
// position and size the text
top 0.3
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 1.0
caption Medium Paddles (Press 2)
}
// end of paddleMedium
element TextArea(paddleFast)
{
// position and size the text
top 0.4
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 0 0 0
caption Fast Paddles (Press 3)
}
// end of paddleFast
}
// end of paddlePanel
}
// end of rootPanel
}
// end of MenuOverlay
@@ -0,0 +1,51 @@
// ball material definition
material ball
{
// define one technique for rendering the Ball
technique
{
// render the Ball in one pass
pass
{
// color the Ball violet
ambient 0.58 0 0.827
diffuse 0.58 0 0.827
specular 0.58 0 0.827 120
}
}
}
// paddle material definition
material paddle
{
// define one technique for rendering a Paddle
technique
{
// render a Paddle in one pass
pass
{
// color the Paddle dark orange
ambient 1 0.549 0
diffuse 1 0.549 0
specular 1 0.549 0 120
}
}
}
// wall material definition
material wall
{
// define one technique for rendering a wall
technique
{
// render a wall in one pass
pass
{
// color the wall cyan
ambient 0 0.545 0.545
diffuse 0 0.545 0.545
specular 0 0.545 0.545 120
}
}
}
@@ -0,0 +1,146 @@
// An Overlay to display the score
Score
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text areas
container Panel(ScorePanel)
{
// use relative metrics mode to position this container at the
// top-left corner of the screen
metrics_mode relative
left 0.0
top 0.0
// make it 1/10 the height and the full width of the screen
width 1.0
height .1
// create a TextAreaOverlayElement to display player 1's score
element TextArea(left)
{
// position and size the element relative to the container
metrics_mode relative
// position it at the top of the container 5% from the left and
// make it the same height and half as long as the container
left 0.05
top 0.0
width 0.5
height 1.0
// set font use for caption and set the size and color
font_name BlueBold
char_height .05
colour 1.0 0 0
caption Player 1 Score: 0
}
// create a TextAreaOverlayElement to display player 2's score
element TextArea(right)
{
// position and size the element relative to the container
metrics_mode relative
// position it at the top of the container 69% from the left and
// make it the same height as the container, stretch to the end
left 0.69
top 0.0
width 0.5
height 1.0
// set font use for caption and set the size and color
font_name BlueBold
char_height 0.05
colour 1.0 0 0
caption Player 2 Score: 0
}
}
}
// An Overlay to display "Game Paused" when the player pauses the game
PauseOverlay
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text area
container Panel(Pause)
{
// use relative metrics mode to position and size this container
metrics_mode relative
// place the container at the top-left corner of the window
left 0.0
top 0.0
// make the container the same size as the window
width 1.0
height 1.0
// create a TextAreaOverlayElement to display the text
element TextArea(pauseText)
{
// position and size the element relative to its container
metrics_mode relative
// center it vertically in the container
vert_align center
// put the left corner 4/10 from the left of the container and
// make it 2/10 the width of the container and 1/10 the height
left 0.4
width 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height 0.05
colour 0 0 0
caption Game Paused
}
}
}
// An Overlay to display which player won the game
WinnerOverlay
{
// set a high z-order, displays on top of anything with lower z-order
zorder 500
// create a PanelOverlayElement container to hold the text area
container Panel(Winner)
{
// use relative metrics mode to position and size this container
metrics_mode relative
// place the container at the top-left corner of the window
left 0.0
top 0.0
// make the container the same size as the window
width 1.0
height 1.0
// create a TextAreaOverlayElement to display the text
element TextArea(winnerText)
{
// position and size the element relative to its container
metrics_mode relative
// put the left corner 4/10 from the left of the container and
// make it 2/10 the width of the container and 1/10 the height
left 0.4
top 0.3
width 0.2
height 0.1
// set font use for caption and set the size and color
font_name BlueBold
char_height 0.05
colour 0 0 0
}
}
}
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Project1", "Project1\Project1.vcxproj", "{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}.Debug|Win32.ActiveCfg = Debug|Win32
{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}.Debug|Win32.Build.0 = Debug|Win32
{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}.Release|Win32.ActiveCfg = Release|Win32
{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,67 @@
#include <iostream>
#include <string>
#include "Player.h"
using namespace std;
Player::Player(int score, int health, string name)
{
setScore(score);
setHealth(health);
setName(name);
}
void Player::setScore(int score)
{
if ( score <= 0 )
{
score = 0;
}
iScore = score;
}
int Player::getScore()
{
if ( iScore <= 0 )
{
iScore = 0;
}
return iScore;
}
void Player::setHealth(int health)
{
if ( health >= 0 && health <= 100 )
{
iHealth = health;
}
}
int Player::getHealth()
{
if ( iHealth <= 0 )
{
iHealth = 0;
}
if ( iHealth >= 100 )
{
iHealth = 100;
}
return iHealth;
}
void Player::setName(string name)
{
sName = name;
}
string Player::getName()
{
return sName;
}
void Player::display()
{
cout << "\tScore: " << getScore() << endl;
cout << "\tHealth: " << getHealth() << endl;
}
@@ -0,0 +1,23 @@
#include <string>
using namespace std;
class Player {
private:
int iScore;
int iHealth;
string sName;
public:
Player(int score, int health, string name);
void setScore(int score);
int getScore();
void setHealth(int health);
int getHealth();
string getName();
void setName(string Name);
void display();
};
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{28F4A708-4627-43EF-B148-DDA0ACBDBBC9}</ProjectGuid>
<RootNamespace>Project1</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="Player.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="Player.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Player.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Player.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,87 @@
/*****************************************************************************
* Program: player *
* Author: Amrit Panesar <apanesar@coleman.edu> *
* Date: 08/04/2014 *
* Description: Setup, instantiate, and access player functions *
*****************************************************************************/
#include <string>
#include <iostream>
#include <conio.h>
#include <ctime>
#include "Player.h"
using namespace std;
bool pause();
int main(const char* argv, int argc)
{
srand((unsigned int) time(NULL));
string in;
char choice;
while (true)
{
cout << "What would you like your player to be named?" << endl << ":";
cin >> in;
while (true) {
cout << "You want to name your player " << in << ". Is that correct?" << endl << ":[Y/n] ";
int i = getch();
if ((char)i == 'y' || (char)i == 'Y' || (char)i == 'n' || (char)i == 'N' )
{
choice = i;
break;
}
cout << "Please enter either Y or N" << endl << ":[Y/n] ";
}
if (choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N')
break;
}
while (choice == 'Y' || choice == 'y')
{
Player p1((((rand()%509)*(rand()%349))%101), (((rand()%509)*(rand()%349))%101), in);
cout << p1.getName() << " recieved " << p1.getScore() << " points with " << p1.getHealth() << " points of health!" << endl << endl;
while (true)
{
while (true) {
cout << "Would you like to play again? " << endl << ":[Y/n] ";
int i = getch();
if ((char)i == 'y' || (char)i == 'Y' || (char)i == 'n' || (char)i == 'N' )
{
choice = i;
break;
}
cout << "Please enter either Y or N" << endl;
}
if (choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N')
break;
}
cout << endl;
if (choice == 'n' || choice == 'N')
{
break;
}
}
pause();
}
bool pause()
{
enum { NUL = 0, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT,
LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK,
SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US, DEL = 127 };
cout << "Press any key to continue..." << endl << endl;
int i = getch();
if ( i == ETX || i == ESC ) // control + c || escape
{
return true;
}
return false;
}
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TicTacToe", "TicTacToe\TicTacToe.vcxproj", "{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}.Debug|Win32.ActiveCfg = Debug|Win32
{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}.Debug|Win32.Build.0 = Debug|Win32
{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}.Release|Win32.ActiveCfg = Release|Win32
{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

@@ -0,0 +1,148 @@
/******************************************************************************
* Project Two: Tic-Tac-Toe *
* Author: Amrit Panesar *
* Date: 08/20/2014 *
* License: Released into the Public Domain *
*****************************************************************************/
#include "includes.h"
#include "main.h"
int _tmain(int argc, _TCHAR* argv[])
{
ConsoleSetup("Tic-Tac-Toe");
string name = "";
while (name.length() == 0)
{
cout << "Please enter your name" << endl << ": ";
cin >> name;
bool breakin = false;
while (!breakin)
{
cout << "Your name is: "<< name << endl << "Is this correct? " << endl << "[Y/n]: ";
int in = _getch();
cout << (char)in << endl;
switch (toupper(in))
{
case 'Y':
breakin = true;
break;
case 'N':
breakin = true;
name = "";
break;
}
system("cls");
}
}
char player = ' ';
while (player == ' ')
{
cout << "Please enter one character for your board marker" << endl << ": ";
player = _getch();
cout << player << endl;
bool breakin = false;
while (!breakin)
{
cout << "Your marker is: "<< player << endl << "Is this correct? " << endl << "[Y/n]: ";
int in = _getch();
cout << (char)in << endl;
switch (toupper(in))
{
case 'Y':
breakin = true;
break;
case 'N':
breakin = true;
player = ' ';
break;
}
system("cls");
}
}
char computer = ' ';
if (player == 'X')
computer = 'O';
else
computer = 'X';
TicTacToe t = TicTacToe(name, player, computer);
while (true)
{
t.run();
cout << "Would you like to play again?" << endl << "[Y/n]: ";
char hold = toupper(_getch());
cout << hold << endl;
if (hold == 'Y' || hold == 'N' || hold == LF || hold == ESC)
{
if (hold == 'N' || hold == ESC)
break;
}
else
{
cout << "Please enter either Y or N." << endl;
continue;
}
}
cout << "Game Over." << endl << endl;
cout << "Press any key to continue..." << endl;
_getch();
}
void ConsoleSetup(char* input)
{
system("color 1e");
ChangeConsoleIcon(IDI_ICON1);
ChangeConsoleTitle(input);
cout << string(80,'*') << "Welcome to " << input << " " << GetYear() << " Edition!" << endl << string(80,'*') << endl << endl;
}
void ChangeConsoleTitle (const char* input)
{
time_t t = time(NULL);
tm* timePtr = localtime(&t);
TCHAR szNewTitle[MAX_PATH];
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("%s %d"), input, GetYear());
SetConsoleTitle(szNewTitle);
}
void ChangeConsoleIcon (const int resource_number)
{
HMODULE hMainMod = GetModuleHandle(0);
assert (hMainMod);
HICON hMainIcon = ::LoadIcon(hMainMod, MAKEINTRESOURCE(resource_number));
assert (hMainIcon);
// Load kernel 32 library
HMODULE hMod = LoadLibrary( _T( "Kernel32.dll" ));
assert (hMod);
// Load console icon changing procedure
typedef DWORD (__stdcall *SCI)(HICON);
SCI pfnSetConsoleIcon = reinterpret_cast<SCI>(GetProcAddress(hMod, "SetConsoleIcon"));
assert (pfnSetConsoleIcon);
// Call function to change icon
pfnSetConsoleIcon (hMainIcon);
FreeLibrary (hMod);
}// End ChangeIcon
int GetYear()
{
time_t t = time(NULL);
tm* timePtr = localtime(&t);
return timePtr->tm_year + 1900;
}
@@ -0,0 +1,522 @@
#include "includes.h"
int TicTacToe::easyMoves[] = { 4, 0, 2, 6, 8, 1, 3, 5, 7 };
enum { NUL = 0, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT,
LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK,
SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US, DEL = 127 };
TicTacToe::TicTacToe(string playername, char playerchar, char computerchar)
{
setplayername(playername);
sethuman(playerchar);
setcomputer(computerchar);
initboard();
initwins();
instructionsdisplayed = false;
}
void TicTacToe::initwins()
{
wins = vector< vector<int> >(8, vector<int>(3));
// diagonal
wins[0][0] = 0;
wins[0][1] = 4;
wins[0][2] = 8;
wins[1][0] = 2;
wins[1][1] = 4;
wins[1][2] = 6;
// down
wins[2][0] = 0;
wins[2][1] = 3;
wins[2][2] = 6;
wins[3][0] = 1;
wins[3][1] = 4;
wins[3][2] = 7;
wins[4][0] = 2;
wins[4][1] = 5;
wins[4][2] = 8;
// across
wins[5][0] = 0;
wins[5][1] = 1;
wins[5][2] = 2;
wins[6][0] = 3;
wins[6][1] = 4;
wins[6][2] = 5;
wins[7][0] = 6;
wins[7][1] = 7;
wins[7][2] = 8;
}
void TicTacToe::initboard()
{
memset(board,' ',sizeof(char)*9);
}
void TicTacToe::displayInstructions()
{
cout << "Instructions: Use your keyboard to type in coordinates to place a "
<< endl << "token on the game board. " << endl << endl;
cout << "You are "<< gethuman() << " - the protagonist in the story - you have been chosen by the high " << endl
<< "council of Tic-Toe to defeat the evil lord " << getcomputer() << ", played by the computer. " << endl;
cout << "Being the chosen one you are able to place your '" << gethuman() << "'" << endl
<< "token first, in an any open space." << endl;
cout << "The computer then places the " << getcomputer() << " token in a free space until " << endl
<< "all spaces are filled" << endl;
cout << "You and the computer continue to place tokens in free spaces until the game" << endl
<< "board is filled " << endl;
cout << "If all spaces are filled and no winner has been declared then a rematch is "
<< endl << "called and the forces of good and evil spar once again." << endl << endl;
system("pause");
system("cls");
}
void TicTacToe::run()
{
bool iseasy = true;
if (!instructionsdisplayed)
{
displayInstructions();
instructionsdisplayed = true;
}
initboard();
while (true)
{
cout << "Would you like to play in Easy mode or Hard mode ?" << endl << "[E/h]:";
char input;
input = _getch();
cout << input << endl;
if (toupper(input) == 'E' || input == LF)
{
iseasy = true;
break;
}
else if (toupper(input) == 'H')
{
iseasy = false;
break;
}
else
{
cout << "Invalid selection, please try again." << endl;
}
}
while (true)
{
displayBoard();
if (stalemate())
{
cout << "Stale mate!" << endl;
system("pause");
break;
}
else
{
setiswin(winner());
if(getiswin())
{
cout << "Sorry, the computer wins this round." << endl;
system("pause");
break;
}
getInput();
}
displayBoard();
if (stalemate())
{
cout << "Stale mate!" << endl;
system("pause");
break;
}
else
{
setiswin(winner());
if(getiswin())
{
cout << "Congratulations! A Winner is You!" << endl;
system("pause");
break;
}
think(iseasy);
}
}
}
void TicTacToe::think(bool easy)
{
if (easy)
{
for (int i = 0; i <= 8; i++)
{
if (board[easyMoves[i]] == ' ')
{
board[easyMoves[i]] = getcomputer();
break;
}
}
}
else // hard think
{
bool movemade = false;
if ( board[4] == ' ' ) // own this.
{
board[4] = getcomputer();
movemade = true;
return;
}
else
{
int count = 0;
for (int i = 0; i < 9; i++)
{
if (board[i] == getcomputer())
count++;
//cout << count;
}
bool closerlook = false;
// do we own the middle square?
if ( board[4] == getcomputer() )
{
// we have more options
closerlook = true;
}
else
{
// special case for:
// ____________
//A | X | | |
// ------------
//B | | O | |
// ------------
//C | | | O |
// ____________
// 1 2 3
if (board[4] == gethuman() && board[8] == gethuman() && board[6] == ' ')
{
board[6] = getcomputer();
movemade = true;
}
}
if (count >= 1 && !movemade)
{
for (int i = 0; i <= 7; i++) // win/block in one
{
//cout << "hard think pass: " << i << endl;
// defensive think - block before win
if (!movemade && board[wins[i][0]] == gethuman() && board[wins[i][1]] == gethuman() && board[wins[i][2]] == ' ')
{
board[wins[i][2]] = getcomputer();
movemade = true;
break;
}
if (!movemade && board[wins[i][1]] == gethuman() && board[wins[i][2]] == gethuman() && board[wins[i][0]] == ' ')
{
board[wins[i][0]] = getcomputer();
movemade = true;
break;
}
if (!movemade && board[wins[i][2]] == gethuman() && board[wins[i][0]] == gethuman() && board[wins[i][1]] == ' ')
{
board[wins[i][1]] = getcomputer();
movemade = true;
break;
}
//offensive think - seal the win if no blocks can be made?
if (!movemade && board[wins[i][0]] == getcomputer() && board[wins[i][1]] == getcomputer() && board[wins[i][2]] == ' ')
{
board[wins[i][2]] = getcomputer();
movemade = true;
break;
}
if (!movemade && board[wins[i][1]] == getcomputer() && board[wins[i][2]] == getcomputer() && board[wins[i][0]] == ' ')
{
board[wins[i][0]] = getcomputer();
movemade = true;
break;
}
if (!movemade && board[wins[i][2]] == getcomputer() && board[wins[i][0]] == getcomputer() && board[wins[i][1]] == ' ')
{
board[wins[i][1]] = getcomputer();
movemade = true;
break;
}
}
}
if (!movemade) // we still haven't made a move!? win in two? what are we doing? find first open space
{
for (int i = 0; i < 9; i++)
{
if (board[i] == ' ' )
{
board [i] = getcomputer();
movemade = true;
break;
}
}
}
}
}
}
bool TicTacToe::stalemate()
{
for (int i = 0; i < 9; i++)
{
if (board[i] == ' ')
{
return false;
}
}
return true;
}
void TicTacToe::displayBoard()
{
cout << " ____________" << endl;
cout << "A | " << board[0] << " | " << board[1] << " | " << board[2] << " |" << endl;
cout << " ------------" << endl;
cout << "B | " << board[3] << " | " << board[4] << " | " << board[5] << " |" << endl;
cout << " ------------" << endl;
cout << "C | " << board[6] << " | " << board[7] << " | " << board[8] << " |" << endl;
cout << " ____________" << endl;
cout << " 1 2 3 " << endl << endl;
}
void TicTacToe::getInput()
{
while (true)
{
cout << "Coordinates" << endl << ">:";
string input;
cin >> input;
bool isBad = false;
if (isalpha(input[0]) && isdigit(input[1]))
{
if ( toupper(input[0]) > 'C' || toupper(input[0]) < 'A' || input[1]-'0' > 3 || input[1]-'0' < 1 )
{
isBad = true;
}
else
{
switch (toupper(input[0]))
{
case 'A':
switch (input[1])
{
case '1':
if (board[0] == ' ')
{
board[0] = gethuman();
}
else
{
isBad = true;
}
break;
case '2':
if (board[1] == ' ')
{
board[1] = gethuman();
}
else
{
isBad = true;
}
break;
case '3':
if (board[2] == ' ')
{
board[2] = gethuman();
}
else
{
isBad = true;
}
break;
}
break;
case 'B':
switch (input[1])
{
case '1':
if (board[3] == ' ')
{
board[3] = gethuman();
}
else
{
isBad = true;
}
break;
case '2':
if (board[4] == ' ')
{
board[4] = gethuman();
}
else
{
isBad = true;
}
break;
case '3':
if (board[5] == ' ')
{
board[5] = gethuman();
}
else
{
isBad = true;
}
break;
}
break;
case 'C':
switch (input[1])
{
case '1':
if (board[6] == ' ')
{
board[6] = gethuman();
}
else
{
isBad = true;
}
break;
case '2':
if (board[7] == ' ')
{
board[7] = gethuman();
}
else
{
isBad = true;
}
break;
case '3':
if (board[8] == ' ')
{
board[8] = gethuman();
}
else
{
isBad = true;
}
break;
}
break;
default:
isBad = true;
}
}
if (isBad)
{
cout << "Error: bad coordinates" << endl;
}
else
{
cout << "Input accepted!" << endl;
break;
}
}
else
{
cout << "Error: bad coordinates" << endl;
}
}
}
bool TicTacToe::winner()
{
for (int i = 0; i < 2; i++)
{
char whatTest = gethuman();
if (i == 1)
whatTest = getcomputer();
for (int j = 0; j < 8; j++) // 8 ways to win
{
int thiswin[3] = { wins[j][0], wins[j][1], wins[j][2] };
// cout << board[thiswin[0]] << board[thiswin[1]] << board[thiswin[2]] << endl;
if (board[thiswin[0]] == whatTest && board[thiswin[1]] == whatTest && board[thiswin[2]] == whatTest)
return true;
}
}
return false;
}
bool TicTacToe::isTie()
{
for (int i = 0; i < boardsize; i++)
{
if (board[i] == ' ')
return true;
}
return false;
}
void TicTacToe::setplayername(string playername)
{
TicTacToe::playername = playername;
}
string TicTacToe::getplayername()
{
return TicTacToe::playername;
}
void TicTacToe::setiswin(bool isWin)
{
TicTacToe::isWin = isWin;
}
bool TicTacToe::getiswin()
{
return TicTacToe::isWin;
}
void TicTacToe::sethuman(char human)
{
TicTacToe::human = human;
}
char TicTacToe::gethuman()
{
return TicTacToe::human;
}
void TicTacToe::setcomputer(char computer)
{
TicTacToe::computer = computer;
}
char TicTacToe::getcomputer()
{
return TicTacToe::computer;
}
void TicTacToe::setboard(char *board)
{
*TicTacToe::board = *board;
}
char* TicTacToe::getboard()
{
return board;
}
void TicTacToe::setposition(int position)
{
TicTacToe::position = position;
}
int TicTacToe::getposition()
{
return TicTacToe::position;
}
@@ -0,0 +1,55 @@
#include "includes.h"
#pragma once
#define boardsize 9
class TicTacToe
{
private:
string playername;
bool isWin;
bool instructionsdisplayed;
char human;
char computer;
char board[boardsize];
int position;
/*
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
*/
vector< vector<int> > wins;
static int easyMoves[];
public:
TicTacToe(string playername, char playerchar, char computerchar);
void displayInstructions();
void run();
void displayBoard();
bool winner();
bool isTie();
void getInput();
void initboard();
bool stalemate();
void think(bool iseasy);
void setplayername(string playername);
string getplayername();
void setiswin(bool isWin);
bool getiswin();
void sethuman(char human);
char gethuman();
void setcomputer(char computer);
char getcomputer();
void setboard(char* board);
char* getboard();
void setposition(int position);
int getposition();
void initwins();
};
@@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{24EA466B-50AD-4F6D-85B6-FE99AA7ADC3E}</ProjectGuid>
<RootNamespace>TicTacToe</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Main.cpp" />
<ClCompile Include="TicTacToe.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="includes.h" />
<ClInclude Include="main.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="TicTacToe.h" />
</ItemGroup>
<ItemGroup>
<Image Include="Icon.ico" />
<Image Include="Icon.png" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="TicTacToe.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="TicTacToe.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="includes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="main.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Image Include="Icon.ico">
<Filter>Resource Files</Filter>
</Image>
<Image Include="Icon.png">
<Filter>Resource Files</Filter>
</Image>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
</Project>
@@ -0,0 +1,22 @@
#pragma once
using namespace std;
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <vector>
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
#include "resource.h"
#include "TicTacToe.h"
#define WIN32_LEAN_AND_MEAN
@@ -0,0 +1,13 @@
void ChangeConsoleTitle (const char* input);
void ChangeConsoleIcon (int resource_number);
void ConsoleSetup (char* input);
int GetYear();
enum { NUL = 0, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT,
LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK,
SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US, DEL = 127 };
Loaded 100 of 606 files, more files were not shown because too many files have changed in this diff. Show more