create account

Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API by dragosroua

View this thread on: hive.blogpeakd.comecency.com
· @dragosroua ·
$8.84
Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API
A week ago I made [a short review](https://steemit.com/bitcoin/@dragosroua/experimenting-with-machine-payable-apis-my-early-review-of-the-21-app) of a new site called 21.co. It's one of the most hyped Bitcoin startups, the makers of the first Bitcoin computer (a glorified Raspberry PI with an ASIC miner on top of it, basically). 

The Bitcoin computer didn't convince me, but their API did. To make a long story short, the platform created by 21.co _enables anyone to create machine-payable APIs_. In mundane terms, you can monetize, with Bitcoin, anything that sits behind a URL: a file, an image, a membership, a game.

What follows is a very simple - but fully functional - game made with this API. It's a version of the popular Rock, Paper, Scissor game, in which the opponent is the server.

# Prerequisites

You need to open an account at [21.co](https:/21.co), obviously. You will also need to download, install and configure (by logging yourself in) their SDK. Fortunately, they made this super easy, just visit this URL and you'll be set in minutes (or at least, that's how it took for me).

https://21.co/features/

# Game Architecture

The game contains 2 modules, a server and a client. The server is responsible for making and storing a choice (rock, paper or scissors) and the client is responsible for sending its choice. If both are choosing the same thing, the server issue the message "Tie!". If choices are different, then the winner is picked based on the Rock, Paper, Scissor traditional game mechanic (paper covers rock, scissors break paper, etc).

 For each call made by the client, a certain payment is made. If the client loses, there is no other payment incurred. If the client wins, it gets a small prize back, bigger than the amount invested.

# Source Code

You can download the entire source code from [this Github repo](https://github.com/dragosroua/21app-rock-paper-scissors). We will have a short look at both files in order to understand what's going on. The code is commented so it should be relatively easy.

**rock-paper-scissors.py**

```#!/usr/bin/env python3
import random

from flask import Flask
from flask import request

from two1.wallet import Wallet
from two1.bitserv.flask import Payment

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)

choices_array = {
    'Rock': '1',
    'Paper': '2',
    'Scissors': '3'
}

choices_list = list(choices_array.keys())
server_choice = random.choice(choices_list)

# endpoint to get the server's choice
@app.route('/choice')
def get_choice():
    return server_choice


# machine-payable endpoint that checks user's answer
@app.route('/play')
@payment.required(3000)
def pick_choice():

    # extract answer from client request
    answer = request.args.get('selection')

    # extract payout address from client address
    client_payout_addr = request.args.get('payout_address')

    # check if answer is correct

#   logic for determiining the winner
    if answer == '1':
        if choices_array[server_choice] == '1':
            return "Tie!"
        else:
            if choices_array[server_choice] == '2':
                return "Server chose Paper. Server wins, Paper covers Rock!"
            else:
                return "Server chose Scissors. You win, Rock crushes Scissors!"
                wallet.send_to(client_payout_addr, 5000, True, 1000)
    elif answer == '2':
        if choices_array[server_choice] == '2':
            return "Tie!"
        else:
            if choices_array[server_choice] == '1':
                return "Server chose Rock. You win, Paper covers Rock!"
                wallet.send_to(client_payout_addr, 5000, True, 1000)
            else:
                return "Server chose Scissors. Server wins, Scissors breaks Paper!"
    elif answer == '3':
        if choices_array[server_choice] == '3':
            return "Tie!"
        else:
            if choices_array[server_choice] == '2':
                return "Server chose Paper. You win, Scissors breaks Paper!"
                wallet.send_to(client_payout_addr, 5000, True, 1000)
            else:
                return "Server chose Rock. Server wins, Rock crushes Scissors!"
    else:
        return "Incorrect response."

if __name__ == '__main__':
    app.run(host='::', debug=True)
```
***
After we import the required dependencies, we define an array in which we hold the 3 options. We also generate a random choice and store it. The heavy lifting part is generated by this line:

```
@app.route('/play')
@payment.required(3000)
```
***
The ```play``` endpoint will issue a ```402 Payment Required``` header, which will ask for 3000 satoshi. Upon completion of the transaction, the server will get the user's input and decide the winner. If the client wins, the server sends back 5000 satoshi.

Here's how the play file looks like:

**play.py**

```
#!/usr/bin/env python3
from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests

# set up bitrequest client for BitTransfer requests
wallet = Wallet()
requests = BitTransferRequests(wallet)

# server address
server_url = 'http://[::1]:5000/'


def play():
    # show the selection to the user, waiting for input 

    ans = input("Your choice? Rock: 1, Paper: 2, Scissors: 3\n")
    sel_url = server_url + 'play?selection={0}&payout_address={1}'
    answer = requests.get(url=sel_url.format(ans, wallet.get_payout_address()))
    print(answer.text)

if __name__ == '__main__':
    play()
```
***
As you see, it's a very simple interface, in which the user is asked to make his pick. Here's an example screenshot:
***
![](http://dragosroua.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-09-at-11.33.25-AM.png)
***
If you want to see the transactions, issue the command ```21 log```. The output should look like this:
***
![](http://dragosroua.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-09-at-11.35.14-AM.png)
***
# Troubleshooting

It is possible that you will raise an exception if you don't have enough bitcoin in your local wallet. Please complete all the introductory tasks at the 21.co website after the signup, that will give you around $2 worth of bitcoin to play with.

Please note there are two sources of bitcoin in the 21.co setup: off-chain and on-chain (there are even payment channels, but this is too complex for this article). The off-chain balance is what you get when you complete the assignments in the 21.co website and there is an withdrawal limit if you want to take that out and make it available on-chain (the main Bitcoin network), you can't withdraw less than $2 worth of bitcoin.

# Potential

The 21.co API is more complex than that. I just wanted to showcase what you can do extremely fast in order to create a bitcoin-powered API. There are many examples at the 21.co website and some of them are mind-boggling.

Feedback, criticism, suggestions?
***
_I'm a serial entrepreneur, blogger and ultrarunner. You can find me mainly on my blog at [Dragos Roua](http://dragosroua.com) where I write about productivity, business, relationships and running. Here on Steemit you may stay updated by following me @dragosroua._<center>
![Dragos Roua](http://dragosroua.com/wp-content/uploads/2014/05/bamf-e1448824881306.png) </center>
***

<center>_**You can also vote for me as a Steemit witness here: 
https://steemit.com/~witnesses**_</center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 33 others
properties (23)
authordragosroua
permlinktutorial-create-a-rock-paper-scissors-bitcoin-game-in-python-using-21-app-machine-payable-api
categorybitcoin
json_metadata{"tags":["bitcoin","python","game","app21"],"users":["dragosroua"],"image":["http://dragosroua.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-09-at-11.33.25-AM.png","http://dragosroua.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-09-at-11.35.14-AM.png","http://dragosroua.com/wp-content/uploads/2014/05/bamf-e1448824881306.png"],"links":["https://steemit.com/bitcoin/@dragosroua/experimenting-with-machine-payable-apis-my-early-review-of-the-21-app","https:/21.co","https://21.co/features/","https://github.com/dragosroua/21app-rock-paper-scissors","http://dragosroua.com","https://steemit.com/~witnesses"],"app":"steemit/0.1","format":"markdown"}
created2017-02-09 09:44:27
last_update2017-02-09 09:44:27
depth0
children4
last_payout2017-03-12 10:28:33
cashout_time1969-12-31 23:59:59
total_payout_value7.920 HBD
curator_payout_value0.915 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,361
author_reputation372,798,229,806,288
root_title"Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id2,461,185
net_rshares31,169,093,402,538
author_curate_reward""
vote details (97)
@creatr ·
This is indeed *very* cool stuff...

I'm still shy of the fine print at http://21.co though...

Thanks a lot for the neat example!
properties (22)
authorcreatr
permlinkre-dragosroua-tutorial-create-a-rock-paper-scissors-bitcoin-game-in-python-using-21-app-machine-payable-api-20170210t073309727z
categorybitcoin
json_metadata{"tags":["bitcoin"],"links":["http://21.co"],"app":"steemit/0.1"}
created2017-02-10 07:33:09
last_update2017-02-10 07:33:09
depth1
children0
last_payout2017-03-12 10:28:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length130
author_reputation136,627,187,742,915
root_title"Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id2,469,372
net_rshares0
@lemouth ·
The example you picked looks like a slot machine to me :)
properties (22)
authorlemouth
permlinkre-dragosroua-tutorial-create-a-rock-paper-scissors-bitcoin-game-in-python-using-21-app-machine-payable-api-20170209t131123140z
categorybitcoin
json_metadata{"tags":["bitcoin"],"app":"steemit/0.1"}
created2017-02-09 13:11:24
last_update2017-02-09 13:11:24
depth1
children2
last_payout2017-03-12 10:28:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length57
author_reputation338,011,164,701,274
root_title"Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id2,462,392
net_rshares0
@dragosroua ·
Almost, but not. You gave me a nice idea, though :)
properties (22)
authordragosroua
permlinkre-lemouth-re-dragosroua-tutorial-create-a-rock-paper-scissors-bitcoin-game-in-python-using-21-app-machine-payable-api-20170209t160453213z
categorybitcoin
json_metadata{"tags":["bitcoin"],"app":"steemit/0.1"}
created2017-02-09 16:04:45
last_update2017-02-09 16:04:45
depth2
children1
last_payout2017-03-12 10:28:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length51
author_reputation372,798,229,806,288
root_title"Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id2,463,613
net_rshares0
@lemouth ·
Ahaha :)
properties (22)
authorlemouth
permlinkre-dragosroua-re-lemouth-re-dragosroua-tutorial-create-a-rock-paper-scissors-bitcoin-game-in-python-using-21-app-machine-payable-api-20170210t211838936z
categorybitcoin
json_metadata{"tags":["bitcoin"],"app":"steemit/0.1"}
created2017-02-10 21:18:39
last_update2017-02-10 21:18:39
depth3
children0
last_payout2017-03-12 10:28:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8
author_reputation338,011,164,701,274
root_title"Tutorial: Create A 'Rock, Paper, Scissors' Bitcoin Game in Python Using 21 app Machine-Payable API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id2,474,537
net_rshares0