<commit_before>// main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//               and 2003 Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: main.cc,v 1.18 2003/06/12 14:37:21 fluxgen Exp $

#include "fluxbox.hh"
#include "I18n.hh"
#include "version.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

//use GNU extensions
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <typeinfo>

using namespace std;
void showInfo(ostream &ostr) {
    ostr<<"Fluxbox version: "<<__fluxbox_version<<endl;
    ostr<<"Compiled: "<<__DATE__<<" "<<__TIME__<<endl;
    ostr<<"Compiler: ";
#ifdef  __GNUG__
    ostr<<"GCC";
#else
    ostr<<"Unknown";
#endif
    ostr<<endl<<"Compiler version: "<<__VERSION__<<endl;

    const char NOT[] = "-";
    ostr<<"Compiled options ("<<NOT<<" => disabled): "<<endl<<
#ifndef DEBUG
        NOT<<
#endif // DEBUG
        "DEBUG"<<endl<<
#ifndef SLIT
        NOT<<
#endif // SLIT
        "SLIT"<<endl<<
#ifndef HAVE_XPM
        NOT<<
#endif // HAVE_XPM
        "XPM"<<endl<<
#ifndef USE_GNOME
        NOT<<
#endif // USE_GNOME
        "GNOME"<<endl<<
#ifndef KDE
        NOT<<
#endif // KDE
        "KDE"<<endl<<
#ifndef USE_NEWWMSPEC
        NOT<<
#endif // USE_NEWWMSPEC
        "EWMH"<<endl<<
#ifndef REMEMBER
        NOT<<
#endif // REMEMBER
        "REMEMBER"<<endl<<
#ifndef SHAPE
        NOT<<
#endif // SHAPE
        "SHAPE"<<endl<<
#ifndef USE_XFT
        NOT<<
#endif // USE_XFT
        "XFT"<<endl<<
#ifndef USE_XMB
        NOT<<
#endif // USE_XMB
        "XMB"<<endl<<
#ifndef XINERAMA
        NOT<<
#endif // XINERAMA
        "XINERAMA"<<endl<<
#ifndef HAVE_XRENDER
        NOT<<
#endif // HAVE_XRENDER
        "RENDER"<<endl<<
        endl;
}

int main(int argc, char **argv) {

    std::string session_display;
    std::string rc_file;
    std::string log_filename;

    NLSInit("fluxbox.cat");
    I18n &i18n = *I18n::instance();

    int i;
    for (i = 1; i < argc; ++i) {
        if (! strcmp(argv[i], "-rc")) {
            // look for alternative rc file to use

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,
                                         "error: '-rc' requires and argument\n"));
                exit(1);
            }

            rc_file = argv[i];
        } else if (! strcmp(argv[i], "-display")) {
            // check for -display option... to run on a display other than the one
            // set by the environment variable DISPLAY

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
                                         "error: '-display' requires an argument\n"));
                exit(1);
            }

            session_display = argv[i];
            std::string display_env = "DISPLAY=" + session_display;
            if (putenv(const_cast<char *>(display_env.c_str()))) {
                fprintf(stderr,
                        i18n.
                        getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
                                   "warning: couldn't set environment variable 'DISPLAY'\n"));
                perror("putenv()");
            }
        } else if (strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "-v") == 0) {
            // print current version string
            cerr<<"Fluxbox "<<__fluxbox_version<<" : (c) 2001-2003 Henrik Kinnunen "<<endl<<endl;
            exit(0);
        } else if (strcmp(argv[i], "-log") == 0 ) {
            if (i + 1 >= argc) {
                cerr<<"error: '-log' need an argument"<<endl;
                exit(1);
            }
            log_filename = argv[++i];
        } else if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) {
            // print program usage and command line options
            printf(i18n.
                   getMessage(FBNLS::mainSet, FBNLS::mainUsage,
                              "Fluxbox %s : (c) %s Henrik Kinnunen\n"
                              "Website: http://www.fluxbox.org/ \n\n"
                              "	-display <string>\t\tuse display connection.\n"
                              "	-rc <string>\t\t\tuse alternate resource file.\n"
                              "	-version\t\t\tdisplay version and exit.\n"
                              "	-info\t\t\t\tdisplay some useful information.\n"
                              "\t-log <filename>\t\t\tlog output to file.\n"
                              "	-help\t\t\t\tdisplay this help text and exit.\n\n"),
                   __fluxbox_version, "2001-2003");
            exit(0);
        } else if (strcmp(argv[i], "-info") == 0 || strcmp(argv[i], "-i") == 0) {
            showInfo(cout);
            ::exit(0);
        }
    }

#ifdef __EMX__
    _chdir2(getenv("X11ROOT"));
#endif // __EMX__
    std::auto_ptr<Fluxbox> fluxbox;
    int exitcode=EXIT_FAILURE;

    streambuf *outbuf = 0;
    streambuf *errbuf = 0;

    ofstream log_file(log_filename.c_str());

    // setup log file
    if (log_file) {
        cerr<<"Loggin to: "<<log_filename<<endl;
        log_file<<"------------------------------------------"<<endl;
        log_file<<"Logfile: "<<log_filename<<endl;
        showInfo(log_file);
        log_file<<"------------------------------------------"<<endl;
        // setup log to use cout and cerr stream
        outbuf = cout.rdbuf(log_file.rdbuf());
        errbuf = cerr.rdbuf(log_file.rdbuf());
    }

    try {

        fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));
        fluxbox->eventLoop();

	exitcode = EXIT_SUCCESS;

    } catch (std::out_of_range &oor) {
        cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
    } catch (std::runtime_error &re) {
        cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
    } catch (std::bad_cast &bc) {
        cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
    } catch (std::bad_alloc &ba) {
        cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
    } catch (std::exception &e) {
        cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
    } catch (std::string error_str) {
        cerr<<"Error: "<<error_str<<endl;
    } catch (...) {
        cerr<<"Fluxbox: Unknown error."<<endl;
        abort();
    }

    // restore cout and cin streams
    if (outbuf != 0)
        cout.rdbuf(outbuf);
    if (errbuf != 0)
        cerr.rdbuf(errbuf);

    return exitcode;
}
<commit_msg>minor fix<commit_after>// main.cc for Fluxbox Window manager
// Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//               and 2003 Simon Bowden (rathnor at users.sourceforge.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: main.cc,v 1.19 2003/07/10 12:01:17 fluxgen Exp $

#include "fluxbox.hh"
#include "I18n.hh"
#include "version.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

//use GNU extensions
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <typeinfo>

using namespace std;
void showInfo(ostream &ostr) {
    ostr<<"Fluxbox version: "<<__fluxbox_version<<endl;
    ostr<<"Compiled: "<<__DATE__<<" "<<__TIME__<<endl;
    ostr<<"Compiler: ";
#ifdef  __GNUG__
    ostr<<"GCC";
#else
    ostr<<"Unknown";
#endif
    ostr<<endl<<"Compiler version: "<<__VERSION__<<endl;

    const char NOT[] = "-";
    ostr<<"Compiled options ("<<NOT<<" => disabled): "<<endl<<
#ifndef DEBUG
        NOT<<
#endif // DEBUG
        "DEBUG"<<endl<<
#ifndef SLIT
        NOT<<
#endif // SLIT
        "SLIT"<<endl<<
#ifndef HAVE_XPM
        NOT<<
#endif // HAVE_XPM
        "XPM"<<endl<<
#ifndef USE_GNOME
        NOT<<
#endif // USE_GNOME
        "GNOME"<<endl<<
#ifndef KDE
        NOT<<
#endif // KDE
        "KDE"<<endl<<
#ifndef USE_NEWWMSPEC
        NOT<<
#endif // USE_NEWWMSPEC
        "EWMH"<<endl<<
#ifndef REMEMBER
        NOT<<
#endif // REMEMBER
        "REMEMBER"<<endl<<
#ifndef SHAPE
        NOT<<
#endif // SHAPE
        "SHAPE"<<endl<<
#ifndef USE_XFT
        NOT<<
#endif // USE_XFT
        "XFT"<<endl<<
#ifndef USE_XMB
        NOT<<
#endif // USE_XMB
        "XMB"<<endl<<
#ifndef XINERAMA
        NOT<<
#endif // XINERAMA
        "XINERAMA"<<endl<<
#ifndef HAVE_XRENDER
        NOT<<
#endif // HAVE_XRENDER
        "RENDER"<<endl<<
        endl;
}

int main(int argc, char **argv) {

    std::string session_display;
    std::string rc_file;
    std::string log_filename;

    NLSInit("fluxbox.cat");
    I18n &i18n = *I18n::instance();

    int i;
    for (i = 1; i < argc; ++i) {
        if (! strcmp(argv[i], "-rc")) {
            // look for alternative rc file to use

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,
                                         "error: '-rc' requires and argument\n"));
                exit(1);
            }

            rc_file = argv[i];
        } else if (! strcmp(argv[i], "-display")) {
            // check for -display option... to run on a display other than the one
            // set by the environment variable DISPLAY

            if ((++i) >= argc) {
                fprintf(stderr,
                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
                                         "error: '-display' requires an argument\n"));
                exit(1);
            }

            session_display = argv[i];
            std::string display_env = "DISPLAY=" + session_display;
            if (putenv(const_cast<char *>(display_env.c_str()))) {
                fprintf(stderr,
                        i18n.
                        getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,
                                   "warning: couldn't set environment variable 'DISPLAY'\n"));
                perror("putenv()");
            }
        } else if (strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "-v") == 0) {
            // print current version string
            cerr<<"Fluxbox "<<__fluxbox_version<<" : (c) 2001-2003 Henrik Kinnunen "<<endl<<endl;
            exit(0);
        } else if (strcmp(argv[i], "-log") == 0 ) {
            if (i + 1 >= argc) {
                cerr<<"error: '-log' need an argument"<<endl;
                exit(1);
            }
            log_filename = argv[++i];
        } else if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) {
            // print program usage and command line options
            printf(i18n.
                   getMessage(FBNLS::mainSet, FBNLS::mainUsage,
                              "Fluxbox %s : (c) %s Henrik Kinnunen\n"
                              "Website: http://www.fluxbox.org/ \n\n"
                              "	-display <string>\t\tuse display connection.\n"
                              "	-rc <string>\t\t\tuse alternate resource file.\n"
                              "	-version\t\t\tdisplay version and exit.\n"
                              "	-info\t\t\t\tdisplay some useful information.\n"
                              "\t-log <filename>\t\t\tlog output to file.\n"
                              "	-help\t\t\t\tdisplay this help text and exit.\n\n"),
                   __fluxbox_version, "2001-2003");
            exit(0);
        } else if (strcmp(argv[i], "-info") == 0 || strcmp(argv[i], "-i") == 0) {
            showInfo(cout);
            exit(0);
        }
    }

#ifdef __EMX__
    _chdir2(getenv("X11ROOT"));
#endif // __EMX__
    std::auto_ptr<Fluxbox> fluxbox;
    int exitcode=EXIT_FAILURE;

    streambuf *outbuf = 0;
    streambuf *errbuf = 0;

    ofstream log_file(log_filename.c_str());

    // setup log file
    if (log_file) {
        cerr<<"Loggin to: "<<log_filename<<endl;
        log_file<<"------------------------------------------"<<endl;
        log_file<<"Logfile: "<<log_filename<<endl;
        showInfo(log_file);
        log_file<<"------------------------------------------"<<endl;
        // setup log to use cout and cerr stream
        outbuf = cout.rdbuf(log_file.rdbuf());
        errbuf = cerr.rdbuf(log_file.rdbuf());
    }

    try {

        fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));
        fluxbox->eventLoop();

	exitcode = EXIT_SUCCESS;

    } catch (std::out_of_range &oor) {
        cerr<<"Fluxbox: Out of range: "<<oor.what()<<endl;
    } catch (std::runtime_error &re) {
        cerr<<"Fluxbox: Runtime error: "<<re.what()<<endl;
    } catch (std::bad_cast &bc) {
        cerr<<"Fluxbox: Bad cast: "<<bc.what()<<endl;
    } catch (std::bad_alloc &ba) {
        cerr<<"Fluxbox: Bad Alloc: "<<ba.what()<<endl;
    } catch (std::exception &e) {
        cerr<<"Fluxbox: Standard exception: "<<e.what()<<endl;
    } catch (std::string error_str) {
        cerr<<"Error: "<<error_str<<endl;
    } catch (...) {
        cerr<<"Fluxbox: Unknown error."<<endl;
        abort();
    }

    // restore cout and cin streams
    if (outbuf != 0)
        cout.rdbuf(outbuf);
    if (errbuf != 0)
        cerr.rdbuf(errbuf);

    return exitcode;
}
<|endoftext|>


<commit_before>#include "stdsneezy.h"
#include "obj_tool.h"
#include "process.h"

map <int, bool> mRoomsFished;

void TBeing::doFish(sstring direction){
  TRoom *rp;
  roomDirData *exitp;
  const int ROOM_FISHING_SHACK=31818;

  if(!(exitp=exitDir(getDirFromChar(direction))) || direction.empty()){
    rp=roomp;
  } else {
    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
      rp=roomp;
    }
  }

  if(rp->isUnderwaterSector()){
    sendTo("You can't fish underwater!\n\r");
    return;
  }
  if(!rp->isWaterSector()){
    sendTo("You can't fish on land!\n\r");
    return;
  }

  if(task){
    stopTask();
  }

  sendTo("You start fishing.\n\r");

  if(getCond(DRUNK) > 10 && !::number(0,3) &&
     (inRoom() < 31800 || inRoom() > 31899)){

    sendTo("All of this drunken fishing has caused you to pass out.\n\r");
    sendTo("Strange things begin running through your mind...\n\r");

    setPosition(POSITION_SLEEPING);

    TRoom *room = real_roomp(ROOM_FISHING_SHACK);
    --(*this);
    *room += *this;
  }

  start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}

TObj *catch_a_fish(TRoom *rp){
  TObj *fish=NULL;
  int nfresh=23, nmarine=34, nice=7;
  int num=0;
  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
			   13807, 13816, 13817, 13818, 13819, 13820, 13821,
			   13822, 13823, 13824, 13896, 617, 620, 621, 622,
                           13814};
  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813,
			    13815, 13825, 13826, 13827, 13828, 13829, 13830,
			    13831, 13832, 13833, 13834, 13835, 13836, 13837,
			    13838, 13839, 13840, 13897, 607, 608, 609, 610,
                            611, 612, 613, 614, 615, 616};
  const int icefishes[]={13875, 13876, 13877, 13878, 13879, 618, 619};
  float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0;  // plus or minus 30%

  //  vlogf(LOG_PEEL, fmt("weightmod=%f") %  weightmod);

  if(!::number(0,99)){  // 1 in 100
    // big one
    weightmod = 2 + ((float)::number(0,100)/100.0); // 2-3

    if(!::number(0,99)){ // 1 in 10000
      // real big one
      weightmod = 3 + ((float)::number(0,100)/100.0); // 3-4

      if(!::number(0,99)){ // 1 in 1000000
	// REAL big one
	weightmod = 4 + ((float)::number(0,100)/100.0); // 4-5

	if(!::number(0,99)){ // 1 in 100000000
	  // freak of nature
	  weightmod = 5 + ((float)::number(0,500)/100.0); // 5-10
	}
      }
    }
  }

  bool adjustsize=true;
  if(rp->getSectorType() == SECT_ICEFLOW){
    num=::number(0,nmarine+nice-1);
    if(num<nice)
      fish=read_object(icefishes[num], VIRTUAL);
    else
      fish=read_object(marinefishes[num-nice], VIRTUAL);
  } else if(rp->isOceanSector()){
    if(!::number(0,nmarine)){
      fish=read_object(12445, VIRTUAL); // some random crap item
      adjustsize=false;
    } else {
      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
    }
  } else { // if(rp->isRiverSector()){  // river or pond or lake or whatever
    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
  }

  if(adjustsize){
    fish->setWeight(fish->getWeight()*weightmod);
    fish->setVolume((int)(fish->getWeight()*200));
  }

  rp->setFished(rp->getFished()+1);

  if (mRoomsFished.find(rp->number) == mRoomsFished.end())
    mRoomsFished[rp->number] = true;

  return fish;
}

TThing *findBait(TThing *stuff){
  TThing *tt;
  TTool *bait;
  TThing *ret;

  if(!stuff)
    return NULL;

  for(tt=stuff;tt;tt=tt->nextThing){
    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&
       (bait->getToolType() == TOOL_FISHINGBAIT))
      return tt;

    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))
      return ret;
  }

  return NULL;
}

int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
  TTool *bait=NULL;
  TThing *t=NULL, *tpole=NULL;
  sstring buf;
  TObj *fish=NULL, *pole=NULL;
  int baitmax=1000, baitchance=0;
  int polemax=5000, polechance=0;
  int catchchance=0;

  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
    act("You cease fishing.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops fishing.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  TThing *ss=ch->getStuff();

  // find our bait here
  t=findBait(ss);

  int m=WEAR_NOWHERE;
  while(!t && m<MAX_WEAR){
    ++m;
    t=findBait(ch->equipment[m]);
  }

  bait=dynamic_cast<TTool *>(t);

  if(!bait){
    ch->sendTo("You need to have some bait to fish.\n\r");
    ch->stopTask();
    return FALSE;
  }

  // find our pole here
  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
     !isname("fishingpole", tpole->name)){
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }
  if(!(pole=dynamic_cast<TObj *>(tpole))){
    vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }

  /*
    do generic checks here
   */

  if(rp && !rp->isWaterSector()){
    ch->sendTo("You can't fish on land!\n\r");
    ch->stopTask();
    return FALSE;
  }

  if (ch->task && ch->task->timeLeft < 0){
    ch->sendTo("You pack up and stop fishing.\n\r");
    ch->stopTask();
    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);

      switch (ch->task->timeLeft) {
	case 2:
	  // check for out of bait
	  bait->addToToolUses(-1);
	  if (bait->getToolUses() <= 0) {
	    act("Oops, you're out of bait.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n looks startled as $e realizes that $e is out of bait.",
		FALSE, ch, NULL, 0, TO_ROOM);
	    ch->stopTask();
	    delete bait;
	    return FALSE;
	  }

	  buf = fmt("You bait %s with $p.") % pole->shortDescr;
	  act(buf, FALSE, ch, bait, 0, TO_CHAR);

	  buf = fmt("$n baits %s with $p.") % pole->shortDescr;
          act(buf, TRUE, ch, bait, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You cast your line out.",
              FALSE, ch, NULL, 0, TO_CHAR);
	  act("$n casts $s line out.",
              TRUE, ch, NULL, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 0:
	  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)/(float)baitmax))*25);
	  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)/(float)polemax))*25);
	  catchchance=::number(1,100);

	  //	  vlogf(LOG_PEEL, fmt("fishing: baitcost=%i, bait=%i, pole=%i, catch=%i") %
	  //	bait->obj_flags.cost % baitchance % polechance % catchchance);

	  if((ch->bSuccess(SKILL_FISHING) ||
	      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&
	     (catchchance<(baitchance+polechance)) &&
	     (fish=catch_a_fish(rp)) &&
	     (::number(5,10) > rp->getFished())){
            *ch += *fish;

	    //	    gain_exp(ch, fish->getWeight() * 10, -1);
	    int lvl=ch->GetMaxLevel();
	    if(lvl>15)
	      lvl-=15;
	    else
	      lvl=1;

	    // 10% exp variance
	    double exp=mob_exp(lvl);
	    exp *= (1.0+((::number(0,20)-10)/100.0));

	    gain_exp(ch, exp, -1);

	    ch->doSave(SILENT_YES);

	    act("You reel in $p!",
		FALSE, ch, fish, 0, TO_CHAR);
	    act("$n reels in $p!",
		TRUE, ch, fish, 0, TO_ROOM);
	  } else {
	    if(fish)
	      delete fish;

	    act("You didn't catch anything.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n doesn't catch anything.",
		TRUE, ch, NULL, 0, TO_ROOM);

            // Don't reveal to the fisherman that there isn't any more fish
            // in the room.
            /*
	    if(rp->getFished()>10){
	      act("This place seems all fished out.",
		  FALSE, ch, NULL, 0, TO_CHAR);
	    }
            */
	  }
	  ch->stopTask();
          break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You cease fishing.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops fishing.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
      ch->stopTask();
      break;
    default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;
}

// procFishRespawning
procFishRespawning::procFishRespawning(const int &p)
{
  trigger_pulse=p;
  name="procFishRespawning";
}

void procFishRespawning::run(int pulse) const
{
  map <int, bool> ::iterator tIter     = mRoomsFished.begin(),
                             tLastGood = mRoomsFished.begin();

  while (tIter != mRoomsFished.end()) {
    TRoom * tRoom = real_roomp((*tIter).first);

    if (!tRoom) {
      vlogf(LOG_BUG, fmt("handleFishRespawning() handling non-existent room! (%d)") % (*tIter).first);
      continue;
    }

    // Make it only a chance.
    if ((tRoom->getFished() > 0) && !::number(0, 24))
      tRoom->setFished(tRoom->getFished() - 1);

    if (tRoom->getFished() < 1) {
      if (tIter == tLastGood) {
        mRoomsFished.erase(tIter);
        tIter = tLastGood = mRoomsFished.begin();
      } else {
        mRoomsFished.erase(tIter);
        tIter = tLastGood;
      }
    } else
      tLastGood = tIter;

    if (tIter == mRoomsFished.end())
      break;

    ++tIter;
  }
}
<commit_msg>fishing exp gain adjustment was WAY too high<commit_after>#include "stdsneezy.h"
#include "obj_tool.h"
#include "process.h"

map <int, bool> mRoomsFished;

void TBeing::doFish(sstring direction){
  TRoom *rp;
  roomDirData *exitp;
  const int ROOM_FISHING_SHACK=31818;

  if(!(exitp=exitDir(getDirFromChar(direction))) || direction.empty()){
    rp=roomp;
  } else {
    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
      rp=roomp;
    }
  }

  if(rp->isUnderwaterSector()){
    sendTo("You can't fish underwater!\n\r");
    return;
  }
  if(!rp->isWaterSector()){
    sendTo("You can't fish on land!\n\r");
    return;
  }

  if(task){
    stopTask();
  }

  sendTo("You start fishing.\n\r");

  if(getCond(DRUNK) > 10 && !::number(0,3) &&
     (inRoom() < 31800 || inRoom() > 31899)){

    sendTo("All of this drunken fishing has caused you to pass out.\n\r");
    sendTo("Strange things begin running through your mind...\n\r");

    setPosition(POSITION_SLEEPING);

    TRoom *room = real_roomp(ROOM_FISHING_SHACK);
    --(*this);
    *room += *this;
  }

  start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}

TObj *catch_a_fish(TRoom *rp){
  TObj *fish=NULL;
  int nfresh=23, nmarine=34, nice=7;
  int num=0;
  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
			   13807, 13816, 13817, 13818, 13819, 13820, 13821,
			   13822, 13823, 13824, 13896, 617, 620, 621, 622,
                           13814};
  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813,
			    13815, 13825, 13826, 13827, 13828, 13829, 13830,
			    13831, 13832, 13833, 13834, 13835, 13836, 13837,
			    13838, 13839, 13840, 13897, 607, 608, 609, 610,
                            611, 612, 613, 614, 615, 616};
  const int icefishes[]={13875, 13876, 13877, 13878, 13879, 618, 619};
  float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0;  // plus or minus 30%

  //  vlogf(LOG_PEEL, fmt("weightmod=%f") %  weightmod);

  if(!::number(0,99)){  // 1 in 100
    // big one
    weightmod = 2 + ((float)::number(0,100)/100.0); // 2-3

    if(!::number(0,99)){ // 1 in 10000
      // real big one
      weightmod = 3 + ((float)::number(0,100)/100.0); // 3-4

      if(!::number(0,99)){ // 1 in 1000000
	// REAL big one
	weightmod = 4 + ((float)::number(0,100)/100.0); // 4-5

	if(!::number(0,99)){ // 1 in 100000000
	  // freak of nature
	  weightmod = 5 + ((float)::number(0,500)/100.0); // 5-10
	}
      }
    }
  }

  bool adjustsize=true;
  if(rp->getSectorType() == SECT_ICEFLOW){
    num=::number(0,nmarine+nice-1);
    if(num<nice)
      fish=read_object(icefishes[num], VIRTUAL);
    else
      fish=read_object(marinefishes[num-nice], VIRTUAL);
  } else if(rp->isOceanSector()){
    if(!::number(0,nmarine)){
      fish=read_object(12445, VIRTUAL); // some random crap item
      adjustsize=false;
    } else {
      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
    }
  } else { // if(rp->isRiverSector()){  // river or pond or lake or whatever
    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
  }

  if(adjustsize){
    fish->setWeight(fish->getWeight()*weightmod);
    fish->setVolume((int)(fish->getWeight()*200));
  }

  rp->setFished(rp->getFished()+1);

  if (mRoomsFished.find(rp->number) == mRoomsFished.end())
    mRoomsFished[rp->number] = true;

  return fish;
}

TThing *findBait(TThing *stuff){
  TThing *tt;
  TTool *bait;
  TThing *ret;

  if(!stuff)
    return NULL;

  for(tt=stuff;tt;tt=tt->nextThing){
    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&
       (bait->getToolType() == TOOL_FISHINGBAIT))
      return tt;

    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))
      return ret;
  }

  return NULL;
}

int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
  TTool *bait=NULL;
  TThing *t=NULL, *tpole=NULL;
  sstring buf;
  TObj *fish=NULL, *pole=NULL;
  int baitmax=1000, baitchance=0;
  int polemax=5000, polechance=0;
  int catchchance=0;

  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
    act("You cease fishing.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops fishing.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  TThing *ss=ch->getStuff();

  // find our bait here
  t=findBait(ss);

  int m=WEAR_NOWHERE;
  while(!t && m<MAX_WEAR){
    ++m;
    t=findBait(ch->equipment[m]);
  }

  bait=dynamic_cast<TTool *>(t);

  if(!bait){
    ch->sendTo("You need to have some bait to fish.\n\r");
    ch->stopTask();
    return FALSE;
  }

  // find our pole here
  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
     !isname("fishingpole", tpole->name)){
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }
  if(!(pole=dynamic_cast<TObj *>(tpole))){
    vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }

  /*
    do generic checks here
   */

  if(rp && !rp->isWaterSector()){
    ch->sendTo("You can't fish on land!\n\r");
    ch->stopTask();
    return FALSE;
  }

  if (ch->task && ch->task->timeLeft < 0){
    ch->sendTo("You pack up and stop fishing.\n\r");
    ch->stopTask();
    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);

      switch (ch->task->timeLeft) {
	case 2:
	  // check for out of bait
	  bait->addToToolUses(-1);
	  if (bait->getToolUses() <= 0) {
	    act("Oops, you're out of bait.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n looks startled as $e realizes that $e is out of bait.",
		FALSE, ch, NULL, 0, TO_ROOM);
	    ch->stopTask();
	    delete bait;
	    return FALSE;
	  }

	  buf = fmt("You bait %s with $p.") % pole->shortDescr;
	  act(buf, FALSE, ch, bait, 0, TO_CHAR);

	  buf = fmt("$n baits %s with $p.") % pole->shortDescr;
          act(buf, TRUE, ch, bait, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You cast your line out.",
              FALSE, ch, NULL, 0, TO_CHAR);
	  act("$n casts $s line out.",
              TRUE, ch, NULL, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 0:
	  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)/(float)baitmax))*25);
	  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)/(float)polemax))*25);
	  catchchance=::number(1,100);

	  //	  vlogf(LOG_PEEL, fmt("fishing: baitcost=%i, bait=%i, pole=%i, catch=%i") %
	  //	bait->obj_flags.cost % baitchance % polechance % catchchance);

	  if((ch->bSuccess(SKILL_FISHING) ||
	      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&
	     (catchchance<(baitchance+polechance)) &&
	     (fish=catch_a_fish(rp)) &&
	     (::number(5,10) > rp->getFished())){
            *ch += *fish;

	    //	    gain_exp(ch, fish->getWeight() * 10, -1);
	    int lvl=ch->GetMaxLevel();
	    if(lvl>15)
	      lvl-=15;
	    else
	      lvl=1;

	    // 10% exp variance
	    double exp=mob_exp(lvl);
	    exp *= (1.0+((::number(0,20)-10)/100.0));

	    gain_exp(ch, exp/50, -1);

	    ch->doSave(SILENT_YES);

	    act("You reel in $p!",
		FALSE, ch, fish, 0, TO_CHAR);
	    act("$n reels in $p!",
		TRUE, ch, fish, 0, TO_ROOM);
	  } else {
	    if(fish)
	      delete fish;

	    act("You didn't catch anything.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n doesn't catch anything.",
		TRUE, ch, NULL, 0, TO_ROOM);

            // Don't reveal to the fisherman that there isn't any more fish
            // in the room.
            /*
	    if(rp->getFished()>10){
	      act("This place seems all fished out.",
		  FALSE, ch, NULL, 0, TO_CHAR);
	    }
            */
	  }
	  ch->stopTask();
          break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You cease fishing.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops fishing.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
      ch->stopTask();
      break;
    default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;
}

// procFishRespawning
procFishRespawning::procFishRespawning(const int &p)
{
  trigger_pulse=p;
  name="procFishRespawning";
}

void procFishRespawning::run(int pulse) const
{
  map <int, bool> ::iterator tIter     = mRoomsFished.begin(),
                             tLastGood = mRoomsFished.begin();

  while (tIter != mRoomsFished.end()) {
    TRoom * tRoom = real_roomp((*tIter).first);

    if (!tRoom) {
      vlogf(LOG_BUG, fmt("handleFishRespawning() handling non-existent room! (%d)") % (*tIter).first);
      continue;
    }

    // Make it only a chance.
    if ((tRoom->getFished() > 0) && !::number(0, 24))
      tRoom->setFished(tRoom->getFished() - 1);

    if (tRoom->getFished() < 1) {
      if (tIter == tLastGood) {
        mRoomsFished.erase(tIter);
        tIter = tLastGood = mRoomsFished.begin();
      } else {
        mRoomsFished.erase(tIter);
        tIter = tLastGood;
      }
    } else
      tLastGood = tIter;

    if (tIter == mRoomsFished.end())
      break;

    ++tIter;
  }
}
<|endoftext|>


<commit_before>#include "stdsneezy.h"
#include "obj_tool.h"

void TBeing::doFish(const char *direction){
  TRoom *rp;
  roomDirData *exitp;
  const int ROOM_FISHING_SHACK=31818;

  if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){
    rp=roomp;
  } else {
    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
      rp=roomp;
    }
  }

  if(rp->isUnderwaterSector()){
    sendTo("You can't fish underwater!\n\r");
    return;
  }
  if(!rp->isWaterSector()){
    sendTo("You can't fish on land!\n\r");
    return;
  }

  if(task){
    stopTask();
  }

  sendTo("You start fishing.\n\r");

  if(getCond(DRUNK) > 10 && !::number(0,3) &&
     (inRoom() < 31800 || inRoom() > 31899)){

    sendTo("All of this drunken fishing has caused you to pass out.\n\r");
    sendTo("Strange things begin running through your mind...\n\r");

    setPosition(POSITION_SLEEPING);

    TRoom *room = real_roomp(ROOM_FISHING_SHACK);
    --(*this);
    *room += *this;
  }

  start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}

TObj *catch_a_fish(TRoom *rp){
  TObj *fish=NULL;
  int nfresh=18, nmarine=25, nice=5;
  int num=0;
  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
			   13807, 13816, 13817, 13818, 13819, 13820, 13821,
			   13822, 13823, 13824, 13896};
  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,
			    13815, 13825, 13826, 13827, 13828, 13829, 13830,
			    13831, 13832, 13833, 13834, 13835, 13836, 13837,
			    13838, 13839, 13840, 13897};
  const int icefishes[]={13875, 13876, 13877, 13878, 13879};
  float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0;  // plus or minus 30%

  //  vlogf(LOG_PEEL, "weightmod=%f", weightmod);

  if(!::number(0,99)){  // 1 in 100
    // big one
    weightmod = 2 + ((float)::number(0,100)/100.0); // 2-3

    if(!::number(0,99)){ // 1 in 10000
      // real big one
      weightmod = 3 + ((float)::number(0,100)/100.0); // 3-4

      if(!::number(0,99)){ // 1 in 1000000
	// REAL big one
	weightmod = 4 + ((float)::number(0,100)/100.0); // 4-5

	if(!::number(0,99)){ // 1 in 100000000
	  // freak of nature
	  weightmod = 5 + ((float)::number(0,500)/100.0); // 5-10
	}
      }
    }
  }

  bool adjustsize=true;
  if(rp->getSectorType() == SECT_ICEFLOW){
    num=::number(0,nmarine+nice-1);
    if(num<nice)
      fish=read_object(icefishes[num], VIRTUAL);
    else
      fish=read_object(marinefishes[num-nice], VIRTUAL);
  } else if(rp->isOceanSector()){
    if(!::number(0,nmarine)){
      fish=read_object(12445, VIRTUAL); // some random crap item
      adjustsize=false;
    } else {
      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
    }
  } else { // if(rp->isRiverSector()){  // river or pond or lake or whatever
    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
  }

  if(adjustsize){
    fish->setWeight(fish->getWeight()*weightmod);
    fish->setVolume(fish->getWeight()*200);
  }

  rp->setFished(rp->getFished()+1);

  return fish;
}

TThing *findBait(TThing *stuff){
  TThing *tt;
  TTool *bait;
  TThing *ret;

  if(!stuff)
    return NULL;

  for(tt=stuff;tt;tt=tt->nextThing){
    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&
       (bait->getToolType() == TOOL_FISHINGBAIT))
      return tt;

    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))
      return ret;
  }

  return NULL;
}

int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
  TTool *bait=NULL;
  TThing *t=NULL, *tpole=NULL;
  char buf[256];
  TObj *fish=NULL, *pole=NULL;
  int baitmax=1000, baitchance=0;
  int polemax=5000, polechance=0;
  int catchchance=0;

  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
    act("You cease fishing.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops fishing.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  TThing *ss=ch->getStuff();

  // find our bait here
  t=findBait(ss);

  int m=WEAR_NOWHERE;
  while(!t && m<MAX_WEAR){
    ++m;
    t=findBait(ch->equipment[m]);
  }

  bait=dynamic_cast<TTool *>(t);

  if(!bait){
    ch->sendTo("You need to have some bait to fish.\n\r");
    ch->stopTask();
    return FALSE;
  }

  // find our pole here
  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
     !isname("fishingpole", tpole->name)){
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }
  if(!(pole=dynamic_cast<TObj *>(tpole))){
    vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }

  /*
    do generic checks here
   */

  if(rp && !rp->isWaterSector()){
    ch->sendTo("You can't fish on land!\n\r");
    ch->stopTask();
    return FALSE;
  }

  if (ch->task && ch->task->timeLeft < 0){
    ch->sendTo("You pack up and stop fishing.\n\r");
    ch->stopTask();
    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);

      switch (ch->task->timeLeft) {
	case 2:
	  // check for out of bait
	  bait->addToToolUses(-1);
	  if (bait->getToolUses() <= 0) {
	    act("Oops, you're out of bait.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n looks startled as $e realizes that $e is out of bait.",
		FALSE, ch, NULL, 0, TO_ROOM);
	    ch->stopTask();
	    delete bait;
	    return FALSE;
	  }

	  snprintf(buf, 256, "You bait %s with $p.", pole->shortDescr);
	  act(buf, FALSE, ch, bait, 0, TO_CHAR);

	  snprintf(buf, 256, "$n baits %s with $p.", pole->shortDescr);
          act(buf, TRUE, ch, bait, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You cast your line out.",
              FALSE, ch, NULL, 0, TO_CHAR);
	  act("$n casts $s line out.",
              TRUE, ch, NULL, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 0:
	  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)/(float)baitmax))*25);
	  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)/(float)polemax))*25);
	  catchchance=::number(1,100);

#if 0
	  vlogf(LOG_PEEL, "fishing: baitcost=%i, bait=%i, pole=%i, catch=%i",
		bait->obj_flags.cost, baitchance, polechance, catchchance);
#endif

	  if((bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) ||
	      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&
	     (catchchance<(baitchance+polechance)) &&
	     (fish=catch_a_fish(rp)) &&
	     (::number(5,10) > rp->getFished())){
            *ch += *fish;

	    ch->addToExp(fish->getWeight() * 5);

	    act("You reel in $p!",
		FALSE, ch, fish, 0, TO_CHAR);
	    act("$n reels in $p!",
		TRUE, ch, fish, 0, TO_ROOM);
	  } else {
	    act("You didn't catch anything.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n doesn't catch anything.",
		TRUE, ch, NULL, 0, TO_ROOM);

	    if(rp->getFished()>10){
	      act("This place seems all fished out.",
		  FALSE, ch, NULL, 0, TO_CHAR);
	    }
	  }
	  ch->stopTask();
          break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You cease fishing.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops fishing.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
      ch->stopTask();
      break;
    default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;
}

<commit_msg>fixed a memory link (discarded fish object not deleted)<commit_after>#include "stdsneezy.h"
#include "obj_tool.h"

void TBeing::doFish(const char *direction){
  TRoom *rp;
  roomDirData *exitp;
  const int ROOM_FISHING_SHACK=31818;

  if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){
    rp=roomp;
  } else {
    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
      rp=roomp;
    }
  }

  if(rp->isUnderwaterSector()){
    sendTo("You can't fish underwater!\n\r");
    return;
  }
  if(!rp->isWaterSector()){
    sendTo("You can't fish on land!\n\r");
    return;
  }

  if(task){
    stopTask();
  }

  sendTo("You start fishing.\n\r");

  if(getCond(DRUNK) > 10 && !::number(0,3) &&
     (inRoom() < 31800 || inRoom() > 31899)){

    sendTo("All of this drunken fishing has caused you to pass out.\n\r");
    sendTo("Strange things begin running through your mind...\n\r");

    setPosition(POSITION_SLEEPING);

    TRoom *room = real_roomp(ROOM_FISHING_SHACK);
    --(*this);
    *room += *this;
  }

  start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}

TObj *catch_a_fish(TRoom *rp){
  TObj *fish=NULL;
  int nfresh=18, nmarine=25, nice=5;
  int num=0;
  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
			   13807, 13816, 13817, 13818, 13819, 13820, 13821,
			   13822, 13823, 13824, 13896};
  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,
			    13815, 13825, 13826, 13827, 13828, 13829, 13830,
			    13831, 13832, 13833, 13834, 13835, 13836, 13837,
			    13838, 13839, 13840, 13897};
  const int icefishes[]={13875, 13876, 13877, 13878, 13879};
  float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0;  // plus or minus 30%

  //  vlogf(LOG_PEEL, "weightmod=%f", weightmod);

  if(!::number(0,99)){  // 1 in 100
    // big one
    weightmod = 2 + ((float)::number(0,100)/100.0); // 2-3

    if(!::number(0,99)){ // 1 in 10000
      // real big one
      weightmod = 3 + ((float)::number(0,100)/100.0); // 3-4

      if(!::number(0,99)){ // 1 in 1000000
	// REAL big one
	weightmod = 4 + ((float)::number(0,100)/100.0); // 4-5

	if(!::number(0,99)){ // 1 in 100000000
	  // freak of nature
	  weightmod = 5 + ((float)::number(0,500)/100.0); // 5-10
	}
      }
    }
  }

  bool adjustsize=true;
  if(rp->getSectorType() == SECT_ICEFLOW){
    num=::number(0,nmarine+nice-1);
    if(num<nice)
      fish=read_object(icefishes[num], VIRTUAL);
    else
      fish=read_object(marinefishes[num-nice], VIRTUAL);
  } else if(rp->isOceanSector()){
    if(!::number(0,nmarine)){
      fish=read_object(12445, VIRTUAL); // some random crap item
      adjustsize=false;
    } else {
      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
    }
  } else { // if(rp->isRiverSector()){  // river or pond or lake or whatever
    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
  }

  if(adjustsize){
    fish->setWeight(fish->getWeight()*weightmod);
    fish->setVolume(fish->getWeight()*200);
  }

  rp->setFished(rp->getFished()+1);

  return fish;
}

TThing *findBait(TThing *stuff){
  TThing *tt;
  TTool *bait;
  TThing *ret;

  if(!stuff)
    return NULL;

  for(tt=stuff;tt;tt=tt->nextThing){
    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&
       (bait->getToolType() == TOOL_FISHINGBAIT))
      return tt;

    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))
      return ret;
  }

  return NULL;
}

int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
  TTool *bait=NULL;
  TThing *t=NULL, *tpole=NULL;
  char buf[256];
  TObj *fish=NULL, *pole=NULL;
  int baitmax=1000, baitchance=0;
  int polemax=5000, polechance=0;
  int catchchance=0;

  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
    act("You cease fishing.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops fishing.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  TThing *ss=ch->getStuff();

  // find our bait here
  t=findBait(ss);

  int m=WEAR_NOWHERE;
  while(!t && m<MAX_WEAR){
    ++m;
    t=findBait(ch->equipment[m]);
  }

  bait=dynamic_cast<TTool *>(t);

  if(!bait){
    ch->sendTo("You need to have some bait to fish.\n\r");
    ch->stopTask();
    return FALSE;
  }

  // find our pole here
  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
     !isname("fishingpole", tpole->name)){
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }
  if(!(pole=dynamic_cast<TObj *>(tpole))){
    vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
    ch->sendTo("You need to hold a fishing pole to fish!\n\r");
    ch->stopTask();
    return FALSE;
  }

  /*
    do generic checks here
   */

  if(rp && !rp->isWaterSector()){
    ch->sendTo("You can't fish on land!\n\r");
    ch->stopTask();
    return FALSE;
  }

  if (ch->task && ch->task->timeLeft < 0){
    ch->sendTo("You pack up and stop fishing.\n\r");
    ch->stopTask();
    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);

      switch (ch->task->timeLeft) {
	case 2:
	  // check for out of bait
	  bait->addToToolUses(-1);
	  if (bait->getToolUses() <= 0) {
	    act("Oops, you're out of bait.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n looks startled as $e realizes that $e is out of bait.",
		FALSE, ch, NULL, 0, TO_ROOM);
	    ch->stopTask();
	    delete bait;
	    return FALSE;
	  }

	  snprintf(buf, 256, "You bait %s with $p.", pole->shortDescr);
	  act(buf, FALSE, ch, bait, 0, TO_CHAR);

	  snprintf(buf, 256, "$n baits %s with $p.", pole->shortDescr);
          act(buf, TRUE, ch, bait, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You cast your line out.",
              FALSE, ch, NULL, 0, TO_CHAR);
	  act("$n casts $s line out.",
              TRUE, ch, NULL, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 0:
	  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)/(float)baitmax))*25);
	  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)/(float)polemax))*25);
	  catchchance=::number(1,100);

#if 0
	  vlogf(LOG_PEEL, "fishing: baitcost=%i, bait=%i, pole=%i, catch=%i",
		bait->obj_flags.cost, baitchance, polechance, catchchance);
#endif

	  if((bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) ||
	      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&
	     (catchchance<(baitchance+polechance)) &&
	     (fish=catch_a_fish(rp)) &&
	     (::number(5,10) > rp->getFished())){
            *ch += *fish;

	    ch->addToExp(fish->getWeight() * 5);

	    act("You reel in $p!",
		FALSE, ch, fish, 0, TO_CHAR);
	    act("$n reels in $p!",
		TRUE, ch, fish, 0, TO_ROOM);
	  } else {
	    if(fish)
	      delete fish;

	    act("You didn't catch anything.",
		FALSE, ch, NULL, 0, TO_CHAR);
	    act("$n doesn't catch anything.",
		TRUE, ch, NULL, 0, TO_ROOM);

	    if(rp->getFished()>10){
	      act("This place seems all fished out.",
		  FALSE, ch, NULL, 0, TO_CHAR);
	    }
	  }
	  ch->stopTask();
          break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You cease fishing.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops fishing.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
      ch->stopTask();
      break;
    default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;
}

<|endoftext|>


<commit_before>#include "map.h"

#include <cassert>

void Map::load(FILE* map) {
	Tile t;
	uint32_t type, tileheight, point;
	uint8_t tilesize, field;
	uint8_t check[4] = "  ";
	uint16_t version;
	fread(&check, 1, 2, map);
	fread(&version, 2, 1, map);
	assert(strcmp(check, "RR") == 0);
//	assert(version == 1);
	fread(&width, 4, 1, map);
	fread(&height, 4, 1, map);
	for (unsigned int i = 0; i < width*height; i++) { // For every tile
		fread(&tilesize, 1, 1, map); // Read number of fields in tile
		for (unsigned int j = 0; j < tilesize; j++) { // For every field in the current tile
			fread(&field, 1, 1, map); // Read field type
			t.type = 0;
			t.height = 0;
			t.point = 0;
			switch(field) { // Decide on field type and read into appropriate variable
				case 0: fread(&type, 4, 1, map); break; // Field type 0 = tile type
				case 1: fread(&tileheight, 4, 1, map); break; // Field type 1 = tile height
				case 2: fread(&point, 4, 1, map); break; // Field type 2 = tile number for scripting
//				case 3: fread(&asdf, 1, 1, map); break; // Field type 3 = ????
				default: fseek(map, 4, SEEK_CUR); // Skip the value of the field if its type is unknown
			}
			t.type = type;
			t.height = tileheight;
			t.point = point;
		}
		tiles.push_back(t);
	}
}

#if UNIT_TEST
#include <iostream>
int main () {
	Map map;
	FILE* f;
	f = fopen("test.map", "rb");
	map.load(f);
	std::vector<Tile>::iterator it = map.tiles.begin();
	int x, y;
	for(x = 0; x<map.width ; x++) {
		for (y = 0; y<map.height; y++) {
			std::cout << it->type << "\t";
			it++;
		}
		std::cout << "\n";
	}
}
#endif
<commit_msg>Fixed check<commit_after>#include "map.h"

#include <cstring>
#include <cassert>

void Map::load(FILE* map) {
	Tile t;
	uint32_t type, tileheight, point;
	uint8_t tilesize, field;
	char* check[4] = new char[4];
	uint16_t version;
	fread(&check, 1, 2, map);
	fread(&version, 2, 1, map);
	assert(strcmp(check, "RR") == 0);
//	assert(version == 1);
	fread(&width, 4, 1, map);
	fread(&height, 4, 1, map);
	for (unsigned int i = 0; i < width*height; i++) { // For every tile
		fread(&tilesize, 1, 1, map); // Read number of fields in tile
		for (unsigned int j = 0; j < tilesize; j++) { // For every field in the current tile
			fread(&field, 1, 1, map); // Read field type
			t.type = 0;
			t.height = 0;
			t.point = 0;
			switch(field) { // Decide on field type and read into appropriate variable
				case 0: fread(&type, 4, 1, map); break; // Field type 0 = tile type
				case 1: fread(&tileheight, 4, 1, map); break; // Field type 1 = tile height
				case 2: fread(&point, 4, 1, map); break; // Field type 2 = tile number for scripting
//				case 3: fread(&asdf, 1, 1, map); break; // Field type 3 = ????
				default: fseek(map, 4, SEEK_CUR); // Skip the value of the field if its type is unknown
			}
			t.type = type;
			t.height = tileheight;
			t.point = point;
		}
		tiles.push_back(t);
	}
}

#if UNIT_TEST
#include <iostream>
int main () {
	Map map;
	FILE* f;
	f = fopen("test.map", "rb");
	map.load(f);
	std::vector<Tile>::iterator it = map.tiles.begin();
	int x, y;
	for(x = 0; x<map.width ; x++) {
		for (y = 0; y<map.height; y++) {
			std::cout << it->type << "\t";
			it++;
		}
		std::cout << "\n";
	}
}
#endif
<|endoftext|>


<commit_before>/* This file is part of the KDE project
   Copyright 2011 Hernan E. Grecco <hernan.grecco gmail com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

//BEGIN Includes
#include "kciplugin.h"
#include "kciplugin.moc"

#include "kciview.h"
#include "kciconfig.h"

#include "kciparser.h"

#include <kpluginfactory.h>
#include <kaboutdata.h>
#include <kdebug.h>

//END Includes

namespace KateCodeinfo
{

K_PLUGIN_FACTORY(KatecodeinfoFactory, registerPlugin<Plugin>();)
K_EXPORT_PLUGIN(KatecodeinfoFactory(KAboutData("katecodeinfoplugin", "katecodeinfoplugin", ki18n("Codeinfo"), "0.1", ki18n("Codeinfo"), KAboutData::License_LGPL_V2)))

Plugin* Plugin::s_self = 0L;

Plugin::Plugin(QObject* parent, const QList<QVariant>&)
  : Kate::Plugin((Kate::Application*)parent)
  , Kate::PluginConfigPageInterface()
{
  s_self = this;
}

Plugin::~Plugin()
{
  s_self = 0L;
}

Plugin& Plugin::self()
{
  return *s_self;
}

Kate::PluginView *Plugin::createView(Kate::MainWindow *mainWindow)
{
  View* pv = new View(mainWindow);
  connect(this, SIGNAL(actionsUpdated()),
          pv, SLOT(updateCmbActions()));
  return pv;
}

uint Plugin::configPages() const
{
  return 1;
}

Kate::PluginConfigPage* Plugin::configPage(uint number, QWidget *parent, const char *name)
{
  if(number == 0) {
    return new Config(parent, name);
  }

  return 0L;
}

QString Plugin::configPageName(uint number) const
{
  if(number == 0) {
    return i18n("Codeinfo");
  }
  return QString();
}

QString Plugin::configPageFullName(uint number) const
{
  if(number == 0) {
    return i18n("Codeinfo Settings");
  }
  return QString();
}

KIcon Plugin::configPageIcon(uint number) const
{
  Q_UNUSED(number)
  return KIcon("msg_info");
}

void Plugin::refreshActions()
{
  emit actionsUpdated();
}

};

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>About was showing the wrong license<commit_after>/* This file is part of the KDE project
   Copyright 2011 Hernan E. Grecco <hernan.grecco gmail com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

//BEGIN Includes
#include "kciplugin.h"
#include "kciplugin.moc"

#include "kciview.h"
#include "kciconfig.h"

#include "kciparser.h"

#include <kpluginfactory.h>
#include <kaboutdata.h>
#include <kdebug.h>

//END Includes

namespace KateCodeinfo
{

K_PLUGIN_FACTORY(KatecodeinfoFactory, registerPlugin<Plugin>();)
K_EXPORT_PLUGIN(KatecodeinfoFactory(KAboutData("katecodeinfoplugin", "katecodeinfoplugin", ki18n("Codeinfo"), "0.1", ki18n("Codeinfo"), KAboutData::License_GPL_V2)))

Plugin* Plugin::s_self = 0L;

Plugin::Plugin(QObject* parent, const QList<QVariant>&)
  : Kate::Plugin((Kate::Application*)parent)
  , Kate::PluginConfigPageInterface()
{
  s_self = this;
}

Plugin::~Plugin()
{
  s_self = 0L;
}

Plugin& Plugin::self()
{
  return *s_self;
}

Kate::PluginView *Plugin::createView(Kate::MainWindow *mainWindow)
{
  View* pv = new View(mainWindow);
  connect(this, SIGNAL(actionsUpdated()),
          pv, SLOT(updateCmbActions()));
  return pv;
}

uint Plugin::configPages() const
{
  return 1;
}

Kate::PluginConfigPage* Plugin::configPage(uint number, QWidget *parent, const char *name)
{
  if(number == 0) {
    return new Config(parent, name);
  }

  return 0L;
}

QString Plugin::configPageName(uint number) const
{
  if(number == 0) {
    return i18n("Codeinfo");
  }
  return QString();
}

QString Plugin::configPageFullName(uint number) const
{
  if(number == 0) {
    return i18n("Codeinfo Settings");
  }
  return QString();
}

KIcon Plugin::configPageIcon(uint number) const
{
  Q_UNUSED(number)
  return KIcon("msg_info");
}

void Plugin::refreshActions()
{
  emit actionsUpdated();
}

};

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: intro.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:19:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef GCC
#pragma hdrstop
#endif

#include "intro.hxx"

#include <tools/stream.hxx>
#include <tools/urlobj.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif

#include "sfxuno.hxx"

// -----------------------------------------------------------------------

void IntroWindow_Impl::Init()
{
    Size aSize = aIntroBmp.GetSizePixel();
    SetOutputSizePixel( aSize );
    Size  aScreenSize( GetDesktopRectPixel().GetSize() );
    Size  aWinSize( GetSizePixel() );
    Point aWinPos( ( aScreenSize.Width()  - aWinSize.Width() )  / 2,
                   ( aScreenSize.Height() - aWinSize.Height() ) / 2  );
    SetPosPixel( aWinPos );

    if ( GetColorCount() >= 16 )
    {
        Show();
        Update();
    }
}

// -----------------------------------------------------------------------

IntroWindow_Impl::IntroWindow_Impl( const Bitmap& rBmp ) :

    WorkWindow( NULL, (WinBits)0 ),

    aIntroBmp( rBmp )

{
    Hide();

    // load bitmap depends on productname ("StarOffice", "StarSuite",...)
    ::com::sun::star::uno::Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
    rtl::OUString aTmp;
    aRet >>= aTmp;
    String aBmpFileName = aTmp;
    aBmpFileName += String( DEFINE_CONST_UNICODE("_intro.bmp") );
    INetURLObject aObj( SvtPathOptions().GetModulePath(), INET_PROT_FILE );
    aObj.insertName( aBmpFileName );
    SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );
    if ( !aStrm.GetError() )
        aStrm >> aIntroBmp;

    Init();
}

// -----------------------------------------------------------------------

IntroWindow_Impl::~IntroWindow_Impl()
{
    Hide();
}

// -----------------------------------------------------------------------

void IntroWindow_Impl::Paint( const Rectangle& )
{
    DrawBitmap( Point(), aIntroBmp );
    Flush();
}

// -----------------------------------------------------------------------

void IntroWindow_Impl::Slide()
{
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.312); FILE MERGED 2006/09/01 17:38:34 kaib 1.4.312.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: intro.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:32:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef GCC
#endif

#include "intro.hxx"

#include <tools/stream.hxx>
#include <tools/urlobj.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif

#include "sfxuno.hxx"

// -----------------------------------------------------------------------

void IntroWindow_Impl::Init()
{
    Size aSize = aIntroBmp.GetSizePixel();
    SetOutputSizePixel( aSize );
    Size  aScreenSize( GetDesktopRectPixel().GetSize() );
    Size  aWinSize( GetSizePixel() );
    Point aWinPos( ( aScreenSize.Width()  - aWinSize.Width() )  / 2,
                   ( aScreenSize.Height() - aWinSize.Height() ) / 2  );
    SetPosPixel( aWinPos );

    if ( GetColorCount() >= 16 )
    {
        Show();
        Update();
    }
}

// -----------------------------------------------------------------------

IntroWindow_Impl::IntroWindow_Impl( const Bitmap& rBmp ) :

    WorkWindow( NULL, (WinBits)0 ),

    aIntroBmp( rBmp )

{
    Hide();

    // load bitmap depends on productname ("StarOffice", "StarSuite",...)
    ::com::sun::star::uno::Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
    rtl::OUString aTmp;
    aRet >>= aTmp;
    String aBmpFileName = aTmp;
    aBmpFileName += String( DEFINE_CONST_UNICODE("_intro.bmp") );
    INetURLObject aObj( SvtPathOptions().GetModulePath(), INET_PROT_FILE );
    aObj.insertName( aBmpFileName );
    SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );
    if ( !aStrm.GetError() )
        aStrm >> aIntroBmp;

    Init();
}

// -----------------------------------------------------------------------

IntroWindow_Impl::~IntroWindow_Impl()
{
    Hide();
}

// -----------------------------------------------------------------------

void IntroWindow_Impl::Paint( const Rectangle& )
{
    DrawBitmap( Point(), aIntroBmp );
    Flush();
}

// -----------------------------------------------------------------------

void IntroWindow_Impl::Slide()
{
}

<|endoftext|>


<commit_before>#include <stdio.h>

char *palindrome(char *string)
{
    if(string == NULL) return NULL;
}

int main(void)
{
}
<commit_msg>Solution of prob 6 (not yet completed)<commit_after>#include <stdio.h>

char *palindrome(char *string)
{
    if(string == NULL) return NULL;
}

int main(void)
{
    return 0;
}
<|endoftext|>


<commit_before>#include "player.hpp"
#include "lvl.hpp"
#include "../visnav/visgraph.hpp"
#include <vector>
#include <string>
#include <cstdio>

void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);

// Maxx is the maximum travel distance in the x-direction
// in a single frame.
static const double Maxx = Player::runspeed();

// Maxy is the maximum travel distance in the y-direction
// in a single frame.
static const double Maxy = Player::jmpspeed() > Body::Maxdy ? Player::jmpspeed() : Body::Maxdy;

// W is the minimum width of a tile in 'frames'.  I.e., at max
// speed how many frames does it require to traverse the
// width of a tile.
static const double W = Tile::Width / Maxx;

// H is the minimum height of a tile in 'frames'.
static const double H = Tile::Height /  Maxy;

struct Plat2d {

	static const unsigned int Ops[];
	static const unsigned int Nops;

	enum { UnitCost = true };

	typedef double Cost;
	static const double InfCost = -1;

	typedef int Oper;
	static const int Nop = -1;

	Plat2d(FILE*);

	~Plat2d(void);

	struct State {
		State(void) { }

		State(unsigned int x, unsigned int y, unsigned int z,
			unsigned int w, unsigned int h) : player(x, y, w, h) { }

		Player player;
	};

	struct PackedState {
		unsigned long hash(void) {
			static const unsigned int sz = sizeof(x) +
				sizeof(y) + sizeof(dy) + sizeof(jframes);
			unsigned char bytes[sz];
			unsigned int i = 0;
			char *p = (char*) &x;
			for (unsigned int j = 0; j < sizeof(x); j++)
				bytes[i++] = p[j];
			p = (char*) &y;
			for (unsigned int j = 0; j < sizeof(y); j++)
				bytes[i++] = p[j];
			p = (char*) &dy;
			for (unsigned int j = 0; j < sizeof(dy); j++)
				bytes[i++] = p[j];
			bytes[i++] = jframes;
			assert (i <= sz);
			return hashbytes(bytes, i);
		}

		bool eq(PackedState &o) const {
			return jframes == o.jframes &&
				doubleeq(x, o.x) &&
				doubleeq(y, o.y) &&
				doubleeq(dy, o.dy);
		}

		double x, y, dy;
		// The body's fall flag is packed as the high-order bit
		// of jframes.
		unsigned char jframes;
	};

	State initialstate(void);

	Cost h(State &s) { return 0; /* return hvis(s); */ }

	Cost d(State &s) { return h(s); }

	bool isgoal(State &s) {
		Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
		return bi.x == gx && bi.y == gy;
	}

	unsigned int nops(State &s) {
 		// If jumping will have no effect then allow left, right and jump.
		// This is a bit of a hack, but the 'jump' action that is allowed
		// here will end up being a 'do nothing' and just fall action.
		// Effectively, we prune off the jump/left and jump/right actions
		// since they are the same as just doing left and right in this case.
		if (!s.player.canjump())
			return 3;
		return Nops;
	}

	Oper nthop(State &s, unsigned int n) {
		return Ops[n];
	}

	struct Transition {
		Cost cost;
		Oper revop;
		State state;

		Transition(Plat2d &d, State &s, Oper op) : revop(Nop), state(s) {
			state.player.act(d.lvl, (unsigned int) op);
			cost = 1;
			if (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {
				if (op == Player::Left)
					revop = Player::Right;
				else if (op == Player::Right)
					revop = Player::Left;
			}
		}

	};

	void pack(PackedState &dst, State &src) {
		dst.x = src.player.body.bbox.min.x;
		dst.y = src.player.body.bbox.min.y;
		dst.dy = src.player.body.dy;
		dst.jframes = src.player.jframes;
		if (src.player.body.fall)
			dst.jframes |= 1 << 7;
	}

	State &unpack(State &buf, PackedState &pkd) {
		buf.player.jframes = pkd.jframes & 0x7F;
		buf.player.body.fall = pkd.jframes & (1 << 7);
		buf.player.body.dy = pkd.dy;
		buf.player.body.bbox.min.x = pkd.x;
		buf.player.body.bbox.min.y = pkd.y;
		buf.player.body.bbox.max.x = pkd.x + Player::Width;
		buf.player.body.bbox.max.y = pkd.y + Player::Height;
		return buf;
	}

	static void dumpstate(FILE *out, State &s) {
		fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
	}

	unsigned int gx, gy;	// goal tile location
	Lvl lvl;

private:

	// heuclidean computes the Euclidean distance of the center
	// point of the player to the goal.  That is, if the player is level
	// with the goal tile in the y direction or is level with it in the
	// x direction and above it then the Euclidean distance to the
	// nearest side is returned.  Otherwise, the minimum of the
	// Euclidean distances from the player's center point to the four
	// corners of the goal block is returned.
	Cost heuclidean(const State &s) const {
		const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
		if (bi.x == gx && bi.y == gy)
			return 0;

		const Point &loc = s.player.body.bbox.center();
		Point goal;
		if (bi.y == gy)
			goal.y = loc.y;
		else if (bi.y < gy)
			goal.y = (gy - 1) * H;
		else
			goal.y = gy * H;
		if (bi.x == gx)
			goal.x = loc.x;
		else if (bi.x < gx)
			goal.x = gx * W;
		else
			goal.x = (gx + 1) * W;

		return Point::distance(loc, goal);
	}

	struct Node {
		int v;		// vertex ID
		int prev;	// previous along path
		long i;	// prio queue index
		double d;	// distance to goal

		static void setind(Node *n, unsigned long ind) { n->i = ind; }
		static bool pred(const Node *a, const Node *b) { return a->d < b->d; }
	};

	void initvg(void);

	Cost hvis(const State &s) const {
		Point loc(s.player.body.bbox.center());
		loc.x /= Maxx;
		loc.y /= Maxy;
		if (vg->isvisible(loc, Point((gx+0.5) * W, (gy+0.5) * H)))
			return heuclidean(s);

		Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
		int c = centers[bi.x * lvl.height() + bi.y];

		// Length of a tile diagonal, subtracted from the visnav
		// distance to account for the fact that the goal vertex
		// is in the center of the goal cell, not on the side.
		static const double diag = sqrt((W/2)*(W/2) + (H/2)*(H/2));
		Cost h = togoal[c].d - Point::distance(loc, vg->verts[c].pt) -  diag;
		assert (h >= 0);
		return h < 0 ? 0 : h;
	}

	VisGraph *vg;
	std::vector<long> centers;
	std::vector<Node> togoal;
};

// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);

// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<commit_msg>plat2d: optimize distance instead of time again. The good results for optimizing time may have been because of a build error causing the heuristic to be wildly inadmissible.<commit_after>#include "player.hpp"
#include "lvl.hpp"
#include "../visnav/visgraph.hpp"
#include <vector>
#include <string>
#include <cstdio>

void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);

// Maxx is the maximum travel distance in the x-direction
// in a single frame.
static const double Maxx = 1; // Player::runspeed();

// Maxy is the maximum travel distance in the y-direction
// in a single frame.
static const double Maxy = 1; // Player::jmpspeed() > Body::Maxdy ? Player::jmpspeed() : Body::Maxdy;

// W is the minimum width of a tile in 'frames'.  I.e., at max
// speed how many frames does it require to traverse the
// width of a tile.
static const double W = Tile::Width / Maxx;

// H is the minimum height of a tile in 'frames'.
static const double H = Tile::Height /  Maxy;

struct Plat2d {

	static const unsigned int Ops[];
	static const unsigned int Nops;

	enum { UnitCost = false };

	typedef double Cost;
	static const double InfCost = -1;

	typedef int Oper;
	static const int Nop = -1;

	Plat2d(FILE*);

	~Plat2d(void);

	struct State {
		State(void) { }

		State(unsigned int x, unsigned int y, unsigned int z,
			unsigned int w, unsigned int h) : player(x, y, w, h) { }

		Player player;
	};

	struct PackedState {
		unsigned long hash(void) {
			static const unsigned int sz = sizeof(x) +
				sizeof(y) + sizeof(dy) + sizeof(jframes);
			unsigned char bytes[sz];
			unsigned int i = 0;
			char *p = (char*) &x;
			for (unsigned int j = 0; j < sizeof(x); j++)
				bytes[i++] = p[j];
			p = (char*) &y;
			for (unsigned int j = 0; j < sizeof(y); j++)
				bytes[i++] = p[j];
			p = (char*) &dy;
			for (unsigned int j = 0; j < sizeof(dy); j++)
				bytes[i++] = p[j];
			bytes[i++] = jframes;
			assert (i <= sz);
			return hashbytes(bytes, i);
		}

		bool eq(PackedState &o) const {
			return jframes == o.jframes &&
				doubleeq(x, o.x) &&
				doubleeq(y, o.y) &&
				doubleeq(dy, o.dy);
		}

		double x, y, dy;
		// The body's fall flag is packed as the high-order bit
		// of jframes.
		unsigned char jframes;
	};

	State initialstate(void);

	Cost h(State &s) { return hvis(s); }

	Cost d(State &s) { return 0; }

	bool isgoal(State &s) {
		Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
		return bi.x == gx && bi.y == gy;
	}

	unsigned int nops(State &s) {
 		// If jumping will have no effect then allow left, right and jump.
		// This is a bit of a hack, but the 'jump' action that is allowed
		// here will end up being a 'do nothing' and just fall action.
		// Effectively, we prune off the jump/left and jump/right actions
		// since they are the same as just doing left and right in this case.
		if (!s.player.canjump())
			return 3;
		return Nops;
	}

	Oper nthop(State &s, unsigned int n) {
		return Ops[n];
	}

	struct Transition {
		Cost cost;
		Oper revop;
		State state;

		Transition(Plat2d &d, State &s, Oper op) : revop(Nop), state(s) {
			state.player.act(d.lvl, (unsigned int) op);
			cost = Point::distance(s.player.body.bbox.min, state.player.body.bbox.min);
			if (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {
				if (op == Player::Left)
					revop = Player::Right;
				else if (op == Player::Right)
					revop = Player::Left;
			}
		}

	};

	void pack(PackedState &dst, State &src) {
		dst.x = src.player.body.bbox.min.x;
		dst.y = src.player.body.bbox.min.y;
		dst.dy = src.player.body.dy;
		dst.jframes = src.player.jframes;
		if (src.player.body.fall)
			dst.jframes |= 1 << 7;
	}

	State &unpack(State &buf, PackedState &pkd) {
		buf.player.jframes = pkd.jframes & 0x7F;
		buf.player.body.fall = pkd.jframes & (1 << 7);
		buf.player.body.dy = pkd.dy;
		buf.player.body.bbox.min.x = pkd.x;
		buf.player.body.bbox.min.y = pkd.y;
		buf.player.body.bbox.max.x = pkd.x + Player::Width;
		buf.player.body.bbox.max.y = pkd.y + Player::Height;
		return buf;
	}

	static void dumpstate(FILE *out, State &s) {
		fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
	}

	unsigned int gx, gy;	// goal tile location
	Lvl lvl;

private:

	// heuclidean computes the Euclidean distance of the center
	// point of the player to the goal.  That is, if the player is level
	// with the goal tile in the y direction or is level with it in the
	// x direction and above it then the Euclidean distance to the
	// nearest side is returned.  Otherwise, the minimum of the
	// Euclidean distances from the player's center point to the four
	// corners of the goal block is returned.
	Cost heuclidean(const State &s) const {
		const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
		if (bi.x == gx && bi.y == gy)
			return 0;

		const Point &loc = s.player.body.bbox.center();
		Point goal;
		if (bi.y == gy)
			goal.y = loc.y;
		else if (bi.y < gy)
			goal.y = (gy - 1) * H;
		else
			goal.y = gy * H;
		if (bi.x == gx)
			goal.x = loc.x;
		else if (bi.x < gx)
			goal.x = gx * W;
		else
			goal.x = (gx + 1) * W;

		return Point::distance(loc, goal);
	}

	struct Node {
		int v;		// vertex ID
		int prev;	// previous along path
		long i;	// prio queue index
		double d;	// distance to goal

		static void setind(Node *n, unsigned long ind) { n->i = ind; }
		static bool pred(const Node *a, const Node *b) { return a->d < b->d; }
	};

	void initvg(void);

	Cost hvis(const State &s) const {
		Point loc(s.player.body.bbox.center());
		loc.x /= Maxx;
		loc.y /= Maxy;
		if (vg->isvisible(loc, Point((gx+0.5) * W, (gy-0.5) * H)))
			return heuclidean(s);

		Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
		int c = centers[bi.x * lvl.height() + bi.y];

		// Length of a tile diagonal, subtracted from the visnav
		// distance to account for the fact that the goal vertex
		// is in the center of the goal cell, not on the side.
		static const double diag = sqrt((W/2)*(W/2) + (H/2)*(H/2));
		assert (Point::distance(loc, vg->verts[c].pt) <= diag + Epsilon);
		Cost h = togoal[c].d - Point::distance(loc, vg->verts[c].pt) - diag;
		assert (h >= 0);
		return h < 0 ? 0 : h;
	}

	VisGraph *vg;
	std::vector<long> centers;
	std::vector<Node> togoal;
};

// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);

// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<|endoftext|>


<commit_before>/*
 * *****************************************************************************
 *   Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not
 *   use this file except in compliance with the License. A copy of the License
 *   is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *   CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *   specific language governing permissions and limitations under the License.
 * *****************************************************************************
 */

#include "client.h"

Client::Client(std::string host,
	       std::string port,
	       std::string accessId,
	       std::string secretKey)
{
	m_creds = ds3_create_creds(accessId.c_str(), secretKey.c_str());

	std::string endpoint = "http://" + host + ":" + port;
	m_client = ds3_create_client(endpoint.c_str(), m_creds);
}

Client::~Client()
{
	ds3_free_creds(m_creds);
	ds3_free_client(m_client);
	ds3_cleanup();
}

ds3_get_service_response*
Client::GetService()
{
	ds3_get_service_response *response;
	ds3_request* request = ds3_init_get_service();
	ds3_error* error = ds3_get_service(m_client,
					   request,
					   &response);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return response;
}

ds3_get_bucket_response*
Client::GetBucket(std::string bucketName,
		  std::string prefix,
		  std::string delimiter,
		  std::string marker,
		  uint32_t maxKeys)
{
	ds3_get_bucket_response *response;
	ds3_request* request = ds3_init_get_bucket(bucketName.c_str());
	if (!prefix.empty()) {
		ds3_request_set_prefix(request, prefix.c_str());
	}
	if (!delimiter.empty()) {
		ds3_request_set_delimiter(request, delimiter.c_str());
	}
	if (!marker.empty()) {
		ds3_request_set_marker(request, marker.c_str());
	}
	if (maxKeys > 0) {
		ds3_request_set_max_keys(request, maxKeys);
	}
	ds3_error* error = ds3_get_bucket(m_client,
					  request,
					  &response);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return response;
}

void
Client::CreateBucket(std::string name)
{
	ds3_request* request = ds3_init_put_bucket(name.c_str());
	ds3_error* error = ds3_put_bucket(m_client, request);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return;
}
<commit_msg>Only add ":<port>" to the endpoint if a port was provided<commit_after>/*
 * *****************************************************************************
 *   Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not
 *   use this file except in compliance with the License. A copy of the License
 *   is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *   CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *   specific language governing permissions and limitations under the License.
 * *****************************************************************************
 */

#include "client.h"

Client::Client(std::string host,
	       std::string port,
	       std::string accessId,
	       std::string secretKey)
{
	m_creds = ds3_create_creds(accessId.c_str(), secretKey.c_str());

	std::string endpoint = "http://" + host;
	if (!port.empty()) {
		endpoint += ":" + port;
	}

	m_client = ds3_create_client(endpoint.c_str(), m_creds);
}

Client::~Client()
{
	ds3_free_creds(m_creds);
	ds3_free_client(m_client);
	ds3_cleanup();
}

ds3_get_service_response*
Client::GetService()
{
	ds3_get_service_response *response;
	ds3_request* request = ds3_init_get_service();
	ds3_error* error = ds3_get_service(m_client,
					   request,
					   &response);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return response;
}

ds3_get_bucket_response*
Client::GetBucket(std::string bucketName,
		  std::string prefix,
		  std::string delimiter,
		  std::string marker,
		  uint32_t maxKeys)
{
	ds3_get_bucket_response *response;
	ds3_request* request = ds3_init_get_bucket(bucketName.c_str());
	if (!prefix.empty()) {
		ds3_request_set_prefix(request, prefix.c_str());
	}
	if (!delimiter.empty()) {
		ds3_request_set_delimiter(request, delimiter.c_str());
	}
	if (!marker.empty()) {
		ds3_request_set_marker(request, marker.c_str());
	}
	if (maxKeys > 0) {
		ds3_request_set_max_keys(request, maxKeys);
	}
	ds3_error* error = ds3_get_bucket(m_client,
					  request,
					  &response);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return response;
}

void
Client::CreateBucket(std::string name)
{
	ds3_request* request = ds3_init_put_bucket(name.c_str());
	ds3_error* error = ds3_put_bucket(m_client, request);
	ds3_free_request(request);

	// TODO check the error
	ds3_free_error(error);

	return;
}
<|endoftext|>