summaryrefslogtreecommitdiff
path: root/cpp/demo/Freeze/casino/BetI.cpp
blob: db6f0db58db2b5ff8bee2570100e07705b3cadf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <BetI.h>

int
BetI::getAmount(const Ice::Current&) const
{
    return amount;
}

void
BetI::accept(const Casino::PlayerPrx& p, const Ice::Current&)
{
    if(!p)
    {
        throw Casino::OutOfChipsException();
    }

    CasinoStore::PersistentPlayerPrx player = CasinoStore::PersistentPlayerPrx::uncheckedCast(p);

    try
    {
        player->withdraw(amount);
        potentialWinners.push_back(player);
    }
    catch(const Ice::ObjectNotExistException&)
    {
        throw Casino::OutOfChipsException();
    }
}

int
BetI::getChipsInPlay(const Ice::Current&) const
{
    return amount * static_cast<int>(potentialWinners.size());
}

Ice::Long
BetI::getCloseTime(const Ice::Current&) const
{
    return closeTime;
}

void
BetI::complete(int random, const Ice::Current& current)
{
    if(random < 0)
    {
        random = -random;
    }

    int size = static_cast<int>(potentialWinners.size());

    //
    // Pick a winner using random
    //
    int winnerIndex = random % (size + (_bankEdge - 1));

    if(winnerIndex >= size)
    {
        winnerIndex = 0;
    }

    CasinoStore::WinnerPrx winner = potentialWinners[winnerIndex];

    try
    {
        winner->win(amount * size);
    }
    catch(const Ice::ObjectNotExistException&)
    {
        //
        // Goes to the bank
        //
        winner = potentialWinners[0];
        winner->win(amount * size);
    }

    //
    // Self-destroys
    //
    _evictor->remove(current.id);
}

BetI::BetI()
{
}

BetI::BetI(int amount, Ice::Long closeTime, const CasinoStore::PersistentBankPrx& bank,
           const Freeze::TransactionalEvictorPtr& evictor, int bankEdge)
{
    this->amount = amount;
    this->closeTime = closeTime;
    init(evictor, bankEdge);
    potentialWinners.push_back(bank);
}

void
BetI::init(const Freeze::TransactionalEvictorPtr& evictor, int bankEdge)
{
    _evictor = evictor;
    _bankEdge = bankEdge;
}