00001 #include "GameContext.h"
00002 #include <fstream>
00003 #include <iostream>
00004 #include <locale>
00005 #include <algorithm>
00006 #include <vector>
00007
00008 void GameContext::generateNextWord(){
00009 if(words.size() > 0 ){
00010 word = words.front();
00011 words.pop_front();
00012 words.push_back(word);
00013 }
00014 }
00015
00016
00017 bool GameContext::doInit(){
00018 state = StateStart::instance();
00019 StateStart::instance()->setGameContext(this);
00020 std::srand((unsigned)std::time(0));
00021 return true;
00022 }
00023
00024 void GameContext::doLoop(){
00025 state->update();
00026 state->doPrint();
00027 state->doGetKey();
00028 }
00029
00030 bool GameContext::readWords(const std::string path){
00031 std::ifstream file(path.c_str(), std::ios_base::in);
00032 if(!file.is_open())
00033 return false;
00034
00035 std::string alphabet = "";
00036 for(int i = static_cast<int>('A'); i <= static_cast<int>('Z');i++ ){
00037 alphabet += static_cast<char>(i);
00038 }
00039 alphabet += " ";
00040
00041 std::vector<std::string> temp_vector;
00042 std::string line = "";
00043 std::locale loc;
00044 while (std::getline(file, line)){
00045 line = trimString(line);
00046 for (int i = 0; i < line.length(); ++i){
00047 line[i] = toupper(line[i],loc);
00048 if (alphabet.find(line[i]) == std::string::npos){
00049 line = "";
00050 break;
00051 }
00052 }
00053 if(line.size() >= minWordSize )
00054 temp_vector.push_back(line);
00055 }
00056 file.close();
00057 if(temp_vector.size() > 0 ){
00058 std::random_shuffle(temp_vector.begin(), temp_vector.end());
00059
00060 words = std::list<std::string>(temp_vector.begin(),temp_vector.end());
00061 generateNextWord();
00062 return true;
00063 }else
00064 return false;
00065 }
00066 std::string GameContext::trimString(std::string source,const std::string seq ){
00067 unsigned int first = source.find_first_not_of(seq);
00068 unsigned int last = source.find_last_not_of(seq);
00069 if(( std::string::npos == first ) || ( std::string::npos == last))
00070 return "";
00071 else
00072 return source.substr( first, last - first + 1 );
00073 }