Creating An Online Casino Integrated With Steem | Python Casino Part #1

in #utopian-io6 years ago

Creating An Online Casino Integrated With Steem | Python Casino Part #1


Welcome everyone to this new tutorial in which I will be creating a full casino which uses Steem currency to power it. All of the casino will be created using Python language. I have planned to add many games to this website.

I have seen other tutorials of how to create casino but no one really went in depth with Python so I think I am the first one who is doing this.

Repository

Other Related Repositories

What I Will Learn?

In this series of tutorials, we will learn how we can use Beem and Flask to create a full casino that uses Steem as a currency. Flask will be used to create the website and Beem will be used to interact with Steem Blockchain.

Requirements

In order to follow along with this tutorial you will need to have these things installed.

  • Python 3.6
  • Flask
  • Beem
  • Basic knowledge of Python

Difficulty

  • Intermediate

Tutorial Contents

Introduction

Let's start by me explaining what are we going to be doing in this tutorial and how we are going to be approaching our goals. Here's a list of things we are going to be covering in this tutorial.

  • Creating a basic Flask application
  • Creating a simple homepage
  • Creating our first game (50-50)

Here are the things that we will be covering in our first game which is going to be really simple game 50-50. We'll start slow but reach the top!

  • Checking transactions using Beem
  • Finding duplicates
  • Giving results

Creating A Basic Flask Application

Let's start by creating a simple that will be dedicated to this project. You can name it anything you want, I will just name it "Casino" for the sake of simplicity. Inside it create two folders, one named "templates" and the other one named "static".

Templates folder will have all the templates (basically html files) of our website. Static folder will have all the "static" things like images, css and any other thing that does not change through out the website. You will learn more about each one of them when we actually use them.

Now create a file called "__init__.py", this file will contain all the routes for our project. We will get to routes some time later. This will also have all the configuration of our application. Now we have all basic files/folders that we need for now. Here's how category might look.

Casino
- templates
- statics
- __init__.py

Now that we have all the files, open up the file that we named "__init__.py" just few moments before. Now let's get to coding instead of talking. The first line on almost all flask applications will be from flask import Flask, render_template, url_for.

So what we have done by typing above line is that we have imported render_template and url_for functions. We have also imported main module Flask so we can use it. I recommend leaving comments as you go because they will help you in the future.

Now is the time to initialize the our app. We will name our application "app" for now for the sake of simplicity. Type this on next line. This will let Flask know that "app" is the name of our application.
app = Flask(__name__)

Move on to the next line because now is the time to create our first route. Routes are a way to tell our website what to show or do when a user visit's a specific page. There are two types of routes but we will go in depth with them later. Type this piece of code in next lines.

@app.route("/")
def index():
  return "Hello World"

We have create a simple route by typing above piece of code. Whenever user goes to "/" page or homepage, it will return a text which is "Hello World". I have named this route "index" because many developers use the word index for homepage so I'll just stick with the trend.

Now that we have a route, we just need to run it. Add this block of code after leaving a line. This will allow you to run your application. I have set debug to true so we can see the changes that we make in real time, saving us a lot of time.

if __name__ == "__main__":
  app.run(debug=True)

Now just run the python file by typing python \_\_init\_\_.py make sure you have changed the directory to the Casino folder. Type the command in the terminal.

Now the file must be running on the localhost. You can go to http://127.0.0.1:5000/ to check out your application and see the results!

This is the code that we have typed till now. I have added some extra comments to help you understand this better.

# Imports
from flask import Flask, render_template, url_for, redirect

# Initializing App
app = Flask(__name__)

# Routes
@app.route("/")
def index():
  return "Hello World"

# Running Application
if __name__ == "__main__":
  app.run(debug=True)

Creating a basic homepage

Now that we have a Flask application, we can start to modify it and start making it much more interactive. We'll now move on to creating our simple hompage (trust me, it's going to be very simple) that will just have a big heading and names of the games. I am not going to be going into designing aspects of the website as they are just repetitive and boring.

Before we move on, you have to understand one thing. We returned a simple text last time that was "Hello Word" but there is much more than that. We can also return html but doing so is not the best practices. Instead, we will create an external file that will have all the html.

For doing this we will use render_template function to render a html file. These HTML files are called templates in Flask. Open up the templates folder, this folder will contain all the templates. Create a new file called "index.html". Type this inside the html file.

<!DOCTYPE html>
<html>
<head>
  <title>Home - Steem Casino</title>
</head>
<body>
  <h1 style="text-align: center;">Steem Casino</h1>
  <h2 style="text-align: center;">
    <a href="/50-50">50-50</a>
  </h2>
</body>
</html>

This is just basic html and a bit of css. Even if you know minimal html, you will know what I have done up there but still let me explain to you what I have did there. I have created two heading (one big and one a little smaller).

The smaller heading has text "50-50" and bigger one has "Steem Casino". Small heading is a link and where when a user will click on this, it will redirect user to "/50-50" route which we haven't created (yet) but we will create right after showing you how page looks now.

It will look much better if we use more css but I already have explained to you why I won't go into styling...so that's the reason.

Creating our first game (50-50)

Now let's move towards the spicy part of this tutorial, creating our first game which is gonna be a simple 50-50 game. A person will transfer any amount of steem and they will have a 50-50 chance of winning. They will be able to choose between heads or tails and if they guess correct, they win.

First let's build the backend part, we'll focus on building the website after it. Create a new file called "steem_functions.py" in the main directory, this file will have all the functions that we will be needing for the games. Open it up and inside of it, type this.

# Imports
from beem import Steem
from beem.instance import set_shared_steem_instance
from beem.nodelist import NodeList
from beem.account import Account
from beem import Steem
from random import randint
import json

# Variables
nodes = NodeList()
nodes.update_nodes()
stm = Steem(keys=["ACTIVE_KEY"], node=nodes.get_nodes(), expiration=90) # Add Key!
set_shared_steem_instance(stm)
username = "USERNAME" # Add Username

# Main Function
def check_transactions():
  while True:
    try:
      acc = Account(username)
      max_op_count = acc.virtual_op_count()
      for i in acc.history_reverse(start=max_op_count, stop=max_op_count-100, use_block_num=False, only_ops=["transfer"]):
        memo = json.loads(i["memo"])
        if memo["game"] == "50-50":
          randguess = randint(0,1)
          amount = i["amount"]
          amount_list = amount.split(" ")
          if memo["guess"] == "head" and randguess == 1:
            acc.transfer(i["to"], float(amount[0])*2, amount[1], memo="You Won!")
          elif memo["guess"] == "tail" and randguess == 0:
            acc.transfer(i["to"], float(amount[0])*2, amount[1], memo="You Won!")
          else:
            acc.transfer(i["to"], 0.001, amount[1], memo="You Lost!")
    except KeyError, ValueError:
      pass

Okay! I might have speed up this tutorial a bit but let me try to explain this block of code that I have typed above. We have imported couple of things from beem library, from random library and json.

We have afterwards created some variables that will make our work easier. The first variable is called "node" and working node list is assigned to it using the NodeList() function that we just imported. In the next line we have just updated our nodes so we are able to use all the working nodes by typing nodes.update_nodes().

In the next line we have created a variable called "stm" and this will the steem_instance for our project. We have assigned Steem() function and we it has three perimeters that we have assigned to it. Since we will need to transfer Steem, the first parameter is "keys" and the value will be active key in a list. Second one is node and to it we have assigned the nodes which we want to use. Third one is expiration time, by default it is set to 30 but I know our process will be a bit slower so to stop the transaction from expiring 90 will work.

Now we have set the steem instance to be shared all over this file because we are going to be using this steem_instance in all this file. In the next line, we have created a variable called "username" and assigned a string that will be the username of the account that we are going to be using for this.

Now is the time to move on to explaining the main function that we are going to be using for this casino. The name of the function is "transaction_checker", this will work in the background and work for all the games at once but for now this function will only work for 50-50 game that we are creating.

First of all, we have declared the function and on the next line, started an infinite while loop so this will continuously do whatever is inside of it. The next thing, we want to do is check transactions but before it we will need to create account object. On the next line, create a variable called "acc" and assign it this value Account(username). "username" is the variable that we created earlier.

We will also need op count so let's create a variable for that in the next line called "max_op_count" and assign it the value acc.virtual_op_count(). Now we will loop through each transaction of the account. For this start a for loop by typing, for i in acc.history_reverse(start=max_block, stop=max_block-100, use_block_num=True, only_ops=["transfer"]):.

Here's a example memo that every transaction will have "{'game': '50-50', 'guess': 'tail'}". We can convert it to json to be able to easily use it in the functions. We have already imported json so just type memo = json.loads(i["memo"]). Now json created from memo string is stored in a variable called "memo".

Now we will check if the user wants to play the "50-50" game and we can do that by typing a simple if statement and that is this if memo["game"] == "50-50":. Now that we know the user wants to let's move forward. We are now going to generate a random integer using the randint() function we imported earlier.

The random integer will either be 0 or 1. 0 will represent tail and 1 will represent head so if user guessed tail and random integer is 0 then that means user guessed correctly. Create a new variable on the next line called "randguess" and then assign it the value randint(0,1).

The amount in the transaction looks like this "1 STEEM" so we will need to split it so we can use it. Create a variable called "amount" in the next line and assign it the value i["amount"]. On next line, create another variable, this time called "amount_list" and assign it the value amount.split(" "). Now a list is assigned to that variable with at 0 index is the amount like "1" and at index 1 there will be the currency.

Now we can check if the user has guessed correctly or not by typing an if statement. This is the first if statement if memo["guess"] == "head" and randguess == 1:. If the guess is correct the inside this will run, which is acc.transfer(i["to"], float(amount[0])*2, amount[1], memo="You Won!"). This will allow us to transfer double the amount, user sent us.

The same is happening in second if statement and then on there is the else statement in which we are just sending 0.001 Steem to tell the user that they have lost. We have also used try and except so we can ignore some errors that can occur.

Now only thing we need is to implement this in the website but first of all, we want to start this function with the start of this website. So open up __init__.py and where app.run() was written, above it type check_transactions(). There is another thing we have to do and that is to import this function so all the way up and type from steem_functions import check_transactions.

Now that we have the game in the background, we will just need to create a route that will redirect the user to sign the steemconnect link and send transaction. So under the last route, create another one. Type this.

@app.route("/50-50")
def 50-50():
  return redirect(f"https://steemconnect.com/sign/transfer?to={username}&amount=1.000%20STEEM&memo=%22%7B'game'%3A%20'50-50'%2C%20'guess'%3A%20'tail'%7D%22")

Now when user will click on the "50-50" text, they will move on to the Steem Connect page to broadcast the action. This is what the page of steemconnect will look like.
screenshot.JPG

End

Thank you for reading this tutorial, hopefully you found this interesting and helpful. I will see you in the next one!

Sort:  

Thank you for your contribution @alexios.
We've been reviewing your tutorial and suggest the following points to improve on your next tutorial:

  • Include proof of work under the shape of a gist or your own github repository containing your code.

  • Good job explaining your code, however, it's important to put comments in your code so the reader can understand what you're developing.

Thanks for your work on developing this tutorial. We are waiting for your next tutorial.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Thank you very much for sharing this newsletter! By the way, I'm willing to declare I haven't been able to locate the most suitable casino source to me for some time, but then began to seek and look at this onehttps://pmcasino-win.com/ money. Use this too

Hi @alexios!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Congratulations @alexios! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You got a First Reply

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Be ready for the next contest!
Trick or Treat - Publish your scariest halloween story and win a new badge

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @alexios! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 10 upvotes. Your next target is to reach 50 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Meet the Steemians Contest - The results, the winners and the prizes
Meet the Steemians Contest - Special attendees revealed
Meet the Steemians Contest - Intermediate results

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @alexios! You received a personal award!

DrugWars Early Access
Thank you for taking part in the early access of Drugwars.

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @alexios! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63470.48
ETH 2544.22
USDT 1.00
SBD 2.72