本文整理汇总了C++中Train类的典型用法代码示例。如果您正苦于以下问题:C++ Train类的具体用法?C++ Train怎么用?C++ Train使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Train类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: initAllTrainsVec
void initAllTrainsVec(std::string initialInTrainsFilePath)
{
// get all the initial in trains
FILE * pFile = fopen(initialInTrainsFilePath.c_str(), "r");
if(pFile == NULL)
perror ("Error opening file");
else
{
// get arriving trains
for(int i=0; i<allArrivalsVec.size(); i++)
{
Train t;
t.setupFromAnArrival(allArrivalsVec[i]);
allTrainsVec.push_back(t);
}
ignoreFirstLine(pFile);
while(true)
{
if(feof(pFile)) break;
Train t;
t.setupTheInitialInTrainFromFile(pFile);
allTrainsVec.push_back(t);
}
fclose(pFile);
}
}
开发者ID:BonnieBBS,项目名称:TrainStation,代码行数:29,代码来源:train.hpp
示例2: fromTrainToQueue
Passenger Station::fromTrainToQueue()
{
Passenger curr;
Train *train = aTrain;
//This for loop goes through all train cars, finds everyone who needs to transfer at B3 and brings them to the appropriate station queue.
for(int j=1;j<4;j++)
{
for(int i=1; i<=train->getNumberInCar(j); i++)
{
curr=train->find(j, i);
if(stationName=="B3R" && (curr.destination=="B1" || curr.destination=="B2" || curr.destination=="A5")) //If the station is B3-RED && Passenger wants to go to BLUE stations
{
curr=train->remove(j,i); //Remove the passenger at Car 1, pos i
return curr; //Return the temp pointer for the removed passenger to transferB3()
}
//Else if north train is on a blue line.
else if(stationName=="B3B" && (curr.destination=="A1" || curr.destination=="A2" ||
curr.destination=="A3" || curr.destination=="A4" || curr.destination=="B4" ||
curr.destination=="B5")) //If the station is B3-BLUE && Passenger wants to go to RED stations
{
curr=train->remove(j,i); //Car 1, at pos i
return curr; //Return temp to transferB3()
}
}
}
//If nobody else wants to transfer, the desination is set to -1. This is used to end the loop in the caller function transferB3().
curr.destination = "-1";
return curr;
}
开发者ID:helloye,项目名称:HunterCSCI,代码行数:32,代码来源:station_final.cpp
示例3: run
Train * ArrivalEvent :: run()
{
int i = 0;
Train * currentTrain = dynamic_cast<Train *>((activeQueue)->get(i));
if((activeQueue)->length() > 0)
{
while(i < (activeQueue)->length() && currentTrain->arrivalTime() > currentTime)
{
i++;
(activeQueue)->insert(currentTrain);
currentTrain = dynamic_cast<Train *>((activeQueue)->get(i));
}
if(i == (activeQueue)->length())
{
currentTrain = NULL;
}
}
else
{
currentTrain = NULL;
}
if(i == (activeQueue)->length())
{
currentTrain = NULL;
}
return currentTrain;
}
开发者ID:KajMoroz,项目名称:assignments,代码行数:32,代码来源:ArrivalEvent.cpp
示例4: main
int main(int argc,char** argv) {
Train tr;
Test te;
std::cout << argv[1] << std::endl;
string s = argv[1];
if (s == "train")
tr.train();
else if (s == "test")
te.test();
system("pause");
}
开发者ID:lengmm,项目名称:SFM-LDA,代码行数:11,代码来源:main.cpp
示例5: Records
Records:: Records(const Real scale,
const Matrix<Real> &neurodata,
const size_t num_neurons) :
Object(scale),
RecordsBase( __get_num_trials(neurodata.rows,num_neurons), num_neurons ),
trials(rows),
neurones(cols),
maxCount(0),
tauMin(0),
tauMax(0)
{
build_with<Train*>(NULL);
RecordsBase &self = *this;
size_t iTrain = 0;
size_t count = 0;
Unit tMin = 0;
Unit tMax = 0;
bool init = true;
for(size_t iN = 0; iN < neurones; ++iN )
{
for(size_t iT = 0; iT < trials; ++iT )
{
Train *tr = new Train(scale,neurodata,iTrain);
self[iT][iN].reset(tr);
const size_t trSize = tr->size();
if(init)
{
if(trSize>0)
{
tMin = (*tr)[0];
tMax = (*tr)[trSize-1];
init = false;
}
}
else
{
if(trSize>0)
{
tMin = min_of(tMin,(*tr)[0]);
tMax = max_of(tMax,(*tr)[trSize-1]);
}
}
++iTrain;
if(trSize>count) count = trSize;
}
}
(size_t&)maxCount = count;
(size_t&)tauMin = tMin;
(size_t&)tauMax = tMax;
}
开发者ID:ybouret,项目名称:neuro-stat,代码行数:50,代码来源:records.cpp
示例6:
// The = operator is used to perform a deep copy of the Train contained
// on the right hand side of the statement to the current instance. It
// copies the residing primitive element values to a new Node instance
// so therefore it doesn't just simply copy the pointers.
Train Train::operator=(Train & rhs) {
// Invokes the copy method corresponding to the internal list. It
// passes the head Node of the train enabling for the list to be
// traversed.
this->linked_list->copy(rhs.getList()->getHead());
// Returns the pointer to the current Train instance.
return *this;
}
开发者ID:izuc,项目名称:SENG1120_assignment2,代码行数:12,代码来源:Train.cpp
示例7: HighlightDragPosition
/**
* Highlight the position where a rail vehicle is dragged over by drawing a light gray background.
* @param px The current x position to draw from.
* @param max_width The maximum space available to draw.
* @param selection Selected vehicle that is dragged.
* @param chain Whether a whole chain is dragged.
* @return The width of the highlight mark.
*/
static int HighlightDragPosition(int px, int max_width, VehicleID selection, bool chain)
{
bool rtl = _current_text_dir == TD_RTL;
assert(selection != INVALID_VEHICLE);
int dragged_width = WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
for (Train *t = Train::Get(selection); t != NULL; t = chain ? t->Next() : (t->HasArticulatedPart() ? t->GetNextArticulatedPart() : NULL)) {
dragged_width += t->GetDisplayImageWidth(NULL);
}
int drag_hlight_left = rtl ? max(px -dragged_width, 0) : px;
int drag_hlight_right = rtl ? px : min(px + dragged_width, max_width);
int drag_hlight_width = max(drag_hlight_right - drag_hlight_left, 0);
if (drag_hlight_width > 0) {
GfxFillRect(drag_hlight_left + WD_FRAMERECT_LEFT, WD_FRAMERECT_TOP + 1,
drag_hlight_right - WD_FRAMERECT_RIGHT, ScaleGUITrad(13) - WD_FRAMERECT_BOTTOM, _colour_gradient[COLOUR_GREY][7]);
}
return drag_hlight_width;
}
开发者ID:tony,项目名称:openttd,代码行数:29,代码来源:train_gui.cpp
示例8: if
void
PulseClusterer::allHitsLoaded()
{
if (!isComplete()) {
// scan multi-map in mid-bin order
Train cluster;
bool first = true;
TripletList::iterator i;
// cout << (dec) << tripletList.size() << " triplets" << endl;
lock();
for (i = tripletList.begin(); i!= tripletList.end(); i++) {
bool switchClusters = false;
if (first)
switchClusters = true;
else if (!absorb(cluster, *i))
switchClusters = true;
if (switchClusters) {
if (!first)
clusterDone(cluster);
first = false;
// start new cluster
cluster.pulses.clear();
cluster.histogram.clear();
int period = (*i).second.pulses[1].spectrum
- (*i).second.pulses[0].spectrum;
cluster.histogram[period].val += 1;
for (int j=0; j<TSZ; j++)
cluster.addPulse((*i).second.pulses[j]);
cluster.loBin = cluster.hiBin = (*i).first;
}
}
if (!first)
clusterDone(cluster);
ChildClusterer::allHitsLoaded();
unlock();
}
}
开发者ID:Vintharas,项目名称:SonATA,代码行数:40,代码来源:PulseClusterer.cpp
示例9: _tmain
int _tmain(int argc, _TCHAR* argv[])
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Rus");
Train *trains = nullptr;
int count = 0;
cout << "¬ведите количество поездов: ";
cin >> count;
trains = new Train[count];
cout << "=========================================================================\n";
for (int i = 0; i < count; ++i) {
trains[i].Show();
cout << "=========================================================================\n";
}
Train *maxTrain = GetMaxTrain(trains, count);
cout << "Ќаибольшее количество пассажиров в поезде номер " << maxTrain->GetTrainNumber() << endl;
cout << " оличество пассажиров: " << maxTrain->GetPassengersCount() << endl;
Train *minTrain = GetMinTrain(trains, count);
cout << "Ќаименьшее количество пассажиров в поезде номер " << minTrain->GetTrainNumber() << endl;
cout << " оличество пассажиров: " << minTrain->GetPassengersCount() << endl;
delete[] trains;
system("pause");
return 0;
}
开发者ID:CAHbl4,项目名称:CPP,代码行数:34,代码来源:Trains_Program.cpp
示例10: main
int main(int argc, char* argv[])
{
char c;
int numStations, numCars, numActions;
Action *actions = new Action[1000000];
ifstream inf(argv[1]);
inf >> numStations >> c >> numCars;
Station *stations = new Station[numStations];
Station *stations2 = new Station[numStations];
Car *cars = new Car[numCars];
readFile(inf, stations, numStations, numCars, cars);
memcpy(stations2, stations, sizeof(Station) * numStations);
CPUTimer ct;
Train *train = new Train(stations, numStations);
delete [] stations;
train->run((const Car*) cars, numCars, actions, &numActions);
double time = ct.cur_CPUTime();
int totalDistance = checkActions(actions, numActions, stations2,
numStations,cars, numCars);
cout << "CPU time: " << time << " Total distance: " << totalDistance << endl;
return 0;
} // main()
开发者ID:hshidara,项目名称:Algorithms-in-C-,代码行数:22,代码来源:trainRunner.cpp
示例11: fromQueueToTrain
void Station::fromQueueToTrain()
{
Train *train = aTrain;
Queue *queue = aQueue;
if(!train)
return; //If there is no train, end the function.
for(int i=0; i<12; i++)
{
// all i that are less than 4 will be rounded to zero
double cabin = floor(i/4);
//convert the double to an int type
int car= static_cast<int>(cabin);
//get that number in car+1= from 1-3
int numberInCar = train->getNumberInCar(car+1);
//This while loop loads all passengers waiting on the queues into the trains.
while(numberInCar != 64 && emptyQueues(car*4))
{
for(int i=car*4; i<((car*4)+4); i++)
{
if((queue)[i].isEmpty()==false && numberInCar < 64)
{
train->load((queue)[i].dequeue(),car+1);
numberInCar=train->getNumberInCar(car+1);
}
}
}
}
}
开发者ID:helloye,项目名称:HunterCSCI,代码行数:38,代码来源:station_final.cpp
示例12:
bool
PulseClusterer::absorb(Train &cluster, const pair<float, Triplet>&i)
{
if (i.first > cluster.hiBin + clusterRange)
return false;
// adjust signal
Tr(detail,("absorb triplet at %f into train max %f",
i.first, cluster.hiBin + clusterRange));
int period = i.second.pulses[1].spectrum
- i.second.pulses[0].spectrum;
cluster.histogram[period].val += 1;
cluster.hiBin = i.first;
for (int j=0; j<TSZ; j++)
cluster.addPulse(i.second.pulses[j]);
return true;
}
开发者ID:Vintharas,项目名称:SonATA,代码行数:16,代码来源:PulseClusterer.cpp
示例13: main
int main(int argc, const char* argv[])
{
/** preprocessing **/
srand( 0 );
const char train_file[] = "../train_edges.bpr";
const int K = 10;
const double learning_rate = 0.1;
const double reg_user = 0.01;
const double reg_item = 0.01;
/** data part **/
Train train;
train.Read_File(train_file);
cerr << train.Nuser() << " " << train.Nitem() << endl;
/** model declaration **/
Model model(train.Nuser(), train.Nitem(), K);
for (int iter = 0; iter < 1000; iter++) {
cout << iter << endl;
vector<Pair> sample = train.draw_sample(1);
model.update(sample, learning_rate, reg_user, reg_item);
if (iter % 100 == 99) {
fstream f;
f.open("../test_nodes.txt", ios::in);
fstream p;
char filename[100];
sprintf(filename, "predict_%d.txt", iter);
p.open(filename, ios::out);
size_t u;
while (f >> u)
{
p << u << ":";
vector<Pair_i_y> predict = predict_top_N(train, model, u, 30);
p << predict[0].i;
for (size_t n = 1; n < 30; n++)
{
p << "," << predict[n].i;
}
p << endl;
}
}
}
开发者ID:mark86092,项目名称:bprmf,代码行数:47,代码来源:bprmf.cpp
示例14: printList
void IncomingSwitch :: printList()
{
int i = 0;
cout << "Train #" << " " << "Arrival Time" << " " << "InSwitch Time"
<< " " << "Station Time" << " " << "Departure Time" << " "
<< "OutSwitch Time" << " " << "Total Wait Time" << endl;
while(i < length())
{
Train * activeTrain = dynamic_cast<Train *>(get(i));
cout << activeTrain->trainNumber() << " " << activeTrain->arrivalTime() //Does the formating for the text block output
<< activeTrain->getInTime() << " " << activeTrain->waitTime() << " "
<< activeTrain->departureTime() << " " << activeTrain->getOutTime()
<< " " << activeTrain->getTotalWait() << endl;
i++;
}
}
开发者ID:KajMoroz,项目名称:assignments,代码行数:20,代码来源:IncomingSwitch.cpp
示例15: ConnectMultiheadedTrains
/*
* Link front and rear multiheaded engines to each other
* This is done when loading a savegame
*/
void ConnectMultiheadedTrains()
{
Train *v;
FOR_ALL_TRAINS(v) {
v->other_multiheaded_part = NULL;
}
FOR_ALL_TRAINS(v) {
if (v->IsFrontEngine() || v->IsFreeWagon()) {
/* Two ways to associate multiheaded parts to each other:
* sequential-matching: Trains shall be arranged to look like <..>..<..>..<..>..
* bracket-matching: Free vehicle chains shall be arranged to look like ..<..<..>..<..>..>..
*
* Note: Old savegames might contain chains which do not comply with these rules, e.g.
* - the front and read parts have invalid orders
* - different engine types might be combined
* - there might be different amounts of front and rear parts.
*
* Note: The multiheaded parts need to be matched exactly like they are matched on the server, else desyncs will occur.
* This is why two matching strategies are needed.
*/
bool sequential_matching = v->IsFrontEngine();
for (Train *u = v; u != NULL; u = u->GetNextVehicle()) {
if (u->other_multiheaded_part != NULL) continue; // we already linked this one
if (u->IsMultiheaded()) {
if (!u->IsEngine()) {
/* we got a rear car without a front car. We will convert it to a front one */
u->SetEngine();
u->spritenum--;
}
/* Find a matching back part */
EngineID eid = u->engine_type;
Train *w;
if (sequential_matching) {
for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;
/* we found a car to partner with this engine. Now we will make sure it face the right way */
if (w->IsEngine()) {
w->ClearEngine();
w->spritenum++;
}
break;
}
} else {
uint stack_pos = 0;
for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;
if (w->IsEngine()) {
stack_pos++;
} else {
if (stack_pos == 0) break;
stack_pos--;
}
}
}
if (w != NULL) {
w->other_multiheaded_part = u;
u->other_multiheaded_part = w;
} else {
/* we got a front car and no rear cars. We will fake this one for forget that it should have been multiheaded */
u->ClearMultiheaded();
}
}
}
}
}
}
开发者ID:oshepherd,项目名称:openttd-progsigs,代码行数:79,代码来源:vehicle_sl.cpp
示例16: ConvertOldMultiheadToNew
/**
* Converts all trains to the new subtype format introduced in savegame 16.2
* It also links multiheaded engines or make them forget they are multiheaded if no suitable partner is found
*/
void ConvertOldMultiheadToNew()
{
Train *t;
FOR_ALL_TRAINS(t) SetBit(t->subtype, 7); // indicates that it's the old format and needs to be converted in the next loop
FOR_ALL_TRAINS(t) {
if (HasBit(t->subtype, 7) && ((t->subtype & ~0x80) == 0 || (t->subtype & ~0x80) == 4)) {
for (Train *u = t; u != NULL; u = u->Next()) {
const RailVehicleInfo *rvi = RailVehInfo(u->engine_type);
ClrBit(u->subtype, 7);
switch (u->subtype) {
case 0: // TS_Front_Engine
if (rvi->railveh_type == RAILVEH_MULTIHEAD) u->SetMultiheaded();
u->SetFrontEngine();
u->SetEngine();
break;
case 1: // TS_Artic_Part
u->subtype = 0;
u->SetArticulatedPart();
break;
case 2: // TS_Not_First
u->subtype = 0;
if (rvi->railveh_type == RAILVEH_WAGON) {
/* normal wagon */
u->SetWagon();
break;
}
if (rvi->railveh_type == RAILVEH_MULTIHEAD && rvi->image_index == u->spritenum - 1) {
/* rear end of a multiheaded engine */
u->SetMultiheaded();
break;
}
if (rvi->railveh_type == RAILVEH_MULTIHEAD) u->SetMultiheaded();
u->SetEngine();
break;
case 4: // TS_Free_Car
u->subtype = 0;
u->SetWagon();
u->SetFreeWagon();
break;
default: NOT_REACHED();
}
}
}
}
}
开发者ID:oshepherd,项目名称:openttd-progsigs,代码行数:54,代码来源:vehicle_sl.cpp
示例17: AddArticulatedParts
void AddArticulatedParts(Vehicle *first)
{
VehicleType type = first->type;
if (!HasBit(EngInfo(first->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) return;
Vehicle *v = first;
for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
bool flip_image;
EngineID engine_type = GetNextArticPart(i, first->engine_type, first, &flip_image);
if (engine_type == INVALID_ENGINE) return;
/* In the (very rare) case the GRF reported wrong number of articulated parts
* and we run out of available vehicles, bail out. */
if (!Vehicle::CanAllocateItem()) return;
const Engine *e_artic = Engine::Get(engine_type);
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN: {
Train *front = Train::From(first);
Train *t = new Train();
v->SetNext(t);
v = t;
t->subtype = 0;
t->track = front->track;
t->railtype = front->railtype;
t->tcache.first_engine = front->engine_type; // needs to be set before first callback
t->spritenum = e_artic->u.rail.image_index;
if (e_artic->CanCarryCargo()) {
t->cargo_type = e_artic->GetDefaultCargoType();
t->cargo_cap = e_artic->u.rail.capacity; // Callback 36 is called when the consist is finished
} else {
t->cargo_type = front->cargo_type; // Needed for livery selection
t->cargo_cap = 0;
}
t->SetArticulatedPart();
} break;
case VEH_ROAD: {
RoadVehicle *front = RoadVehicle::From(first);
RoadVehicle *rv = new RoadVehicle();
v->SetNext(rv);
v = rv;
rv->subtype = 0;
rv->rcache.first_engine = front->engine_type; // needs to be set before first callback
rv->rcache.cached_veh_length = 8; // Callback is called when the consist is finished
rv->state = RVSB_IN_DEPOT;
rv->roadtype = front->roadtype;
rv->compatible_roadtypes = front->compatible_roadtypes;
rv->spritenum = e_artic->u.road.image_index;
if (e_artic->CanCarryCargo()) {
rv->cargo_type = e_artic->GetDefaultCargoType();
rv->cargo_cap = e_artic->u.road.capacity; // Callback 36 is called when the consist is finished
} else {
rv->cargo_type = front->cargo_type; // Needed for livery selection
rv->cargo_cap = 0;
}
rv->SetArticulatedPart();
} break;
}
/* get common values from first engine */
v->direction = first->direction;
v->owner = first->owner;
v->tile = first->tile;
v->x_pos = first->x_pos;
v->y_pos = first->y_pos;
v->z_pos = first->z_pos;
v->build_year = first->build_year;
v->vehstatus = first->vehstatus & ~VS_STOPPED;
v->cargo_subtype = 0;
v->max_speed = 0;
v->max_age = 0;
v->engine_type = engine_type;
v->value = 0;
v->cur_image = SPR_IMG_QUERY;
v->random_bits = VehicleRandomBits();
if (flip_image) v->spritenum++;
VehicleMove(v, false);
}
}
开发者ID:jemmyw,项目名称:openttd,代码行数:92,代码来源:articulated_vehicles.cpp
示例18: CmdAutoreplaceVehicle
/**
* Autoreplaces a vehicle
* Trains are replaced as a whole chain, free wagons in depot are replaced on their own
* @param tile not used
* @param flags type of operation
* @param p1 Index of vehicle
* @param p2 not used
* @param text unused
* @return the cost of this operation or an error
*/
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(p1);
if (v == NULL) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
if (!v->IsInDepot()) return CMD_ERROR;
if (v->vehstatus & VS_CRASHED) return CMD_ERROR;
bool free_wagon = false;
if (v->type == VEH_TRAIN) {
Train *t = Train::From(v);
if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
free_wagon = !t->IsFrontEngine();
if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
} else {
if (!v->IsPrimaryVehicle()) return CMD_ERROR;
}
const Company *c = Company::Get(_current_company);
bool wagon_removal = c->settings.renew_keep_length;
/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
Vehicle *w = v;
bool any_replacements = false;
while (w != NULL) {
EngineID e;
CommandCost cost = GetNewEngineType(w, c, e);
if (cost.Failed()) return cost;
any_replacements |= (e != INVALID_ENGINE);
w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
}
CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
bool nothing_to_do = true;
if (any_replacements) {
bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
/* Stop the vehicle */
if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
if (cost.Failed()) return cost;
assert(v->IsStoppedInDepot());
/* We have to construct the new vehicle chain to test whether it is valid.
* Vehicle construction needs random bits, so we have to save the random seeds
* to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
SavedRandomSeeds saved_seeds;
SaveRandomSeeds(&saved_seeds);
if (free_wagon) {
cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, ¬hing_to_do));
} else {
cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, ¬hing_to_do));
}
RestoreRandomSeeds(saved_seeds);
if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
CommandCost ret;
if (free_wagon) {
ret = ReplaceFreeUnit(&v, flags, ¬hing_to_do);
} else {
ret = ReplaceChain(&v, flags, wagon_removal, ¬hing_to_do);
}
assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
}
/* Restart the vehicle */
if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
}
if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
return cost;
}
开发者ID:benjeffery,项目名称:openttd,代码行数:86,代码来源:autoreplace_cmd.cpp
示例19: ReplaceChain
/**
* Replace a whole vehicle chain
* @param chain vehicle chain to let autoreplace/renew operator on
* @param flags command flags
* @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
* @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
* @return cost or error
*/
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
{
Vehicle *old_head = *chain;
assert(old_head->IsPrimaryVehicle());
CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
if (old_head->type == VEH_TRAIN) {
/* Store the length of the old vehicle chain, rounded up to whole tiles */
uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
int num_units = 0; ///< Number of units in the chain
for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
Money *new_costs = MallocT<Money>(num_units); ///< Costs for buying and refitting the new vehicles
/* Collect vehicles and build replacements
* Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
int i;
Train *w;
for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
assert(i < num_units);
old_vehs[i] = w;
CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
cost.AddCost(ret);
if (cost.Failed()) break;
new_costs[i] = ret.GetCost();
if (new_vehs[i] != NULL) *nothing_to_do = false;
}
Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
/* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
if (cost.Succeeded()) {
/* Separate the head, so we can start constructing the new chain */
Train *second = Train::From(old_head)->GetNextUnit();
if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
assert(Train::From(new_head)->GetNextUnit() == NULL);
/* Append engines to the new chain
* We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
* That way we also have less trouble when exceeding the unitnumber limit.
* OTOH the vehicle attach callback is more expensive this way :s */
Train *last_engine = NULL; ///< Shall store the last engine unit after this step
if (cost.Succeeded()) {
for (int i = num_units - 1; i > 0; i--) {
Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
if (new_vehs[i] != NULL) {
/* Move the old engine to a separate row with DC_AUTOREPLACE. Else
* moving the wagon in front may fail later due to unitnumber limit.
* (We have to attach wagons without DC_AUTOREPLACE.) */
CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
}
if (last_engine == NULL) last_engine = append;
cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
if (cost.Failed()) break;
}
if (last_engine == NULL) last_engine = new_head;
}
/* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);
/* Append/insert wagons into the new vehicle chain
* We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
*/
if (cost.Succeeded()) {
for (int i = num_units - 1; i > 0; i--) {
assert(last_engine != NULL);
Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
/* Insert wagon after 'last_engine' */
CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);
/* When we allow removal of wagons, either the move failing due
* to the train becoming too long, or the train becoming longer
* would move the vehicle to the empty vehicle chain. */
if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
break;
}
cost.AddCost(res);
//.........这里部分代码省略.........
开发者ID:benjeffery,项目名称:openttd,代码行数:101,代码来源:autoreplace_cmd.cpp
示例20: cmpDescNum
// Функция сортировки поездов в порядке убывания
// по номеру поезда
bool cmpDescNum(Train &tr1, Train &tr2)
{
return tr1.Num() > tr2.Num();
}
开发者ID:maxchv,项目名称:cpp,代码行数:6,代码来源:01.Lists.cpp
注:本文中的Train类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论