click here if you want to see your banner on this site

Author Topic: Paglikha ng Guess Game sa Algorand Gamit ang Python  (Read 544 times)

Polar91

  • Novice
  • *
  • Posts: 35
  • Karma: +0/-0
    • View Profile
Paglikha ng Guess Game sa Algorand Gamit ang Python
« on: July 22, 2020, 11:28:46 AM »
Tandaan: Ito ay pagsasalin lamang

Narito ang orihinal na artikulo: Create A Guess Game On Algorand Using Python. na akda ni Ddev


src

Sa solusyon na ito, magagawa mong:

  • Mai-install at makapagsulat ng program gamit ang Python SDK ng Althand.
  • Pagkonekta sa Algorand testnet gamit ang REST API call.
  • Paglikha ng isang simpleng guess game gamit ang Python at pag-deploy sa Algorand blockchain.
  • Pag-aralan ang batayan ng ligtas na paraan ng pag-program sa Python

Upang makagawa ng guess game, kakailanganin nating:

  • I-install ang Algorand Python SDK (at matutunan na lumikha ng iyong unang transaksyon sa Algorand)
  • Pang-edit sa code
  • Katamtamang kaalaman sa pag-proram ng Python

Gumawa ako ng isang .py file na nagngangalang guessgame.py na naglalaman ng lahat ng source code para sa Guessgame. Pinahihintulutan ng program ang isang gumagamit na pumasok bilang isang player na may dribbling algorithm bilang kalaban. Maaari lamang maging isang manlalaro para sa ating Guessgame na nangangailangan na magsumite ng address na katugma sa tinukoy na protocol sa oras na inilunsad ang program, marahil isang public key ng Algorand. Karaniwan ang public key ay ginagamit sa address ng wallet. Kailangang hanapin ng manlalaro ang nanalong numero na may haba na katumbas sa 7. Ang numero ng panalo ay binubuo gamit ang isang mababang antas ng pagkalkula sa halaga na 8 [1][2] ng type int sa impormasyon ng account ng default na address. Ang isang listahan ng mga saklaw ng numero ay nagmumungkahi sa manlalato upang magamit ang hirap sa paghula. Kung tumutugma ang argumento ng nanalong numero, ang manlalaro ay padadalhan ng 100 ALGO bilang gantimpala.

Code: [Select]
//guessgame.py


from sendtransaction import defaultAddr, private_key_alc
from algosdk import algod
from algosdk import  transaction
import time, sys, random

# Setup HTTP client w/guest key provided by PureStake
class Connect():
    def __init__(self):
        self.algod_address = "https://testnet-algorand.api.purestake.io/ps1"# declaring the third party API
        self.algod_token = "eVXi2wPlDE8uF15mkil5Z2FzRm20GTJg8r3R7ldv" # <-----shortened - my personal API token
        self.headers = {"X-API-Key": self.algod_token}

    def connectToNetwork(self):       
        # establish connection
        return algod.AlgodClient(self.algod_token, self.algod_address, self.headers)

# Player address and private key for testing
testPlayer = "32KTOUGLIPPEZTJZ4BP423LKXEURMAHK3QRHBZVIJSWPWPQED26GKHPD4Q"
playerKey = "5jCryvD1BE3R0akY48j1++dyMGWwrE97n7kmMizcjAPelTdQy0PeTM054F/NbWq5KRYA6twicOaoTKz7PgQevA=="
# usual algorand wallet for testing purpose
contractAlc = "K5UUTXMOU5CB77UHGEPBTUVKTZYZ37TJHAGYS3VIU2YMO6GGACFNJK4QD4"
toConnect = Connect()
forParam = toConnect.connectToNetwork()
# Get suggeted parameters from the network
params = forParam.suggested_params()
note = "Congratulation, you just won 100 ALGO".encode()

randomSeal = random.randint(int(49799), int(50001))
print("Random seal = {}".format(randomSeal))
winRounds = int(0)
playRound = int(0)
ACTIVE = True
max_reward = (int(100000000))

  • Huwag pansinin ang sendtransaction na module. Ang "defaultAddr" at "private_key_alc" ay na-import mula sa parehong file.
  • Ang Connect() ay nagtatatag ng koneksyon sa algorithm at testnet. Kung magpapatakbo ng isang node upang magamit ang layunin - ang command-line ay, tingnan ang gabay sa kung paano mag-set up ng isang node.
  • Upang makapag test-run, kailangan natin ng isang manlalaro at private key - nasa linyang 17 at 18.
  • Pagkatapos ng linyang 24, ang pagsasama ng transaksyon ay nangangailangan ng arbitrary na mga argumento ng type dict  na hihiling ng ilang mga parameter mula sa network tulad ng:
    • genesishashb64
    • genesis ID
    • first round
    • last round
    • min fee

Code: [Select]
...snippet>

# transfering Algo from one account to another
def payAlgo(senderAddr, rec, prvKey):
    global ACTIVE
    min_pay_1 = int(5000000)
    min_pay_2 = int(2000000)
    if ACTIVE:
        # Get account balance of supposedly contract account
        balance = forParam.account_info(defaultAddr)['amountwithoutpendingrewards']
        check = bool(balance >= (min_pay_1+min_pay_2))
        # transaction parameters
        txn = {
            "sender": senderAddr,
            "receiver": rec,
            "fee": params.get('minFee'),
            "flat_fee": True,
            "amt": max_reward,
            "first": params.get('lastRound'),
            "last": params.get('lastRound') + 1000,
            "note": note,
            "gen": params.get('genesisID'),
            "gh": params.get('genesishashb64')
        }
        # validate token transfer
        if((senderAddr != (defaultAddr or contractAlc)) and ((playRound == int(0)) and winRounds == int(0))):
            if(len(senderAddr) == int(58) and (check == True)):
                ACTIVE = True
                txn["amt"] = min_pay_1
                preTrxn = transaction.PaymentTxn(**txn)
                trxn = preTrxn.sign(prvKey)
                try:
                    return("Transaction was signed with ID : ", forParam.send_transaction(trxn, headers={'content-type': 'application/x-binary'}))
                except Exception as e:
                    print(e)
            elif(playRound > int(0) and winRounds > 0):
                ACTIVE = True
                txn["amt"] = min_pay_2
                preTrxn = transaction.PaymentTxn(**txn)
                trxn = preTrxn.sign(prvKey)
                try:
                    return("Transaction was signed with ID : ", forParam.send_transaction(trxn, headers={'content-type': 'application/x-binary'}))
                except Exception as e:
                    print(e)
        elif(senderAddr == (defaultAddr or contractAlc)):
            preTrxn = transaction.PaymentTxn(**txn)
            trxn = preTrxn.sign(prvKey)
            try:
                return("Transaction was signed with ID : ", forParam.send_transaction(trxn, headers={'content-type': 'application/x-binary'}))
            except Exception as e:
                print(e)

Gamit ang payAlgo(), Pinahihintulutan ang manlalaro na magpatuloy pagkatapos magbayad ng minimum na bayad na mga 5000000 microAlgo (5 Algo) na sumasang-ayon sa ilang mga kundisyon na tama tulad ng playRound at winRounds na sumusuri sa 0. Kung ang manlalaro ay isa pang maliban sa default o contract address, Ang halaga na ipadala bilang pass (i.e Txn["amt"]) ay itatakda sa 5 Algo kung hindi naman, kung saan ang manlalaro ay manghuhula o higit pa, nais nating bawasan ang pass. At kung ang tumatawag ay contract account o anumang account kung saan nais nating pahintulutan ang pagbabayad ng gantimpala, ang gantimpala na 100 Algo ay ipapadala sa manlalaro. Maaari lamang itong dumaan kung ang player ay nakatama ng hula.


Code: [Select]
# A class for all guessgame attributes
class GuessGame():
    """Prototyping Guessgame"""
    def __init__(self):
        self.players = []
        self.alcInfo = forParam.account_info(defaultAddr)
        self.alcdetailList = [self.alcInfo]
        self.threshold = int(self.alcdetailList[0]['thisassettotal']['9604118']['total'])
        self.round = [int((self.alcdetailList[0]['round'] -int(1)) -self.threshold)]
        self.suggestedNumbers = range(self.round[0]-(int(self.threshold) +int(150000)), self.round[0]+randomSeal, randomSeal)
        self.active = False

    # returns a series of suggested numbers where winning number lies
    def printSuggestedNNumbers(self):
        sug_nums_len = []
        print("Winning numbers is spotted among range : \n")
        for num in self.suggestedNumbers:
            sug_nums_len.append(num)
        print(sug_nums_len)
        print(len(sug_nums_len))

    # function for guessgame
    def guessByRound(self, arg):
        global winRounds
        global playRound
        i = GuessGame()
        i.printSuggestedNNumbers()
        self.luckyNum = self.round[0]
        while ACTIVE:
            player = input("Enter Your Algorand Wallet Address: ")
            key = input("Enter Your Pkey: ")
            keyList = [key]
            # assert(len(player) == 58)
            self.players.append(player)
            guessLists = []
            pay = payAlgo(player, defaultAddr, key)
            time.sleep(int(5))
            if arg != self.luckyNum:
                winRounds = winRounds
                guessLists.append(arg)
                print("Oop! This roll does not match.")
                self.active = self.active
                print("Last guess was: " + str(arg))
            elif arg == self.round[0]:
                self.active = True
                playRound = playRound+int(1)
                winRounds = winRounds+int(1)
                guessLists.append(arg)
                print("Congratulations! You won!" + "\n" + "100 Algo was sent to you.")
                pay = payAlgo(defaultAddr, player, private_key_alc)
                time.sleep(int(5))
                print("You are in the {} round and {} playround.".format(winRounds, playRound))
            print("Do you want to make more guess? '\n'")           
            replay = input("Press 'y' to continue, 'n' to quit: ")
            replay = replay.lower()
            if(replay == "n"):
                self.active = False
                print("That was really tough right?", "\n", "Algorand Blockchain is awesome!.")
                print("Your total balance is {}".format(forParam.account_info(player)['amountwithoutpendingrewards']))
                sys.exit(int(1))
            elif(replay == "y"):
                self.active == True
                continue

toGuess = GuessGame()
d = toGuess.round[0]
m = toGuess.guessByRound(<arg>)


Patakbuhin ang code na ito sa iyong editor upang makita ang resulta. Kung ang lahat ng mga bagay ay maayos na nararapat sa, manlalaro, ay dapat makatanggap ng gantimpala pagkatapos na makatama ng huli kung hindi man, ang code block ay hihinto at ang proseso ay muling uulit nang tuloy-tuloy.



Bakit Algorand?

Ang ASC1 ay Layer-1 ng smart contract na awtomatikong nagpapatupad ng mga pasadyang patakaran at lohika, karaniwang sa halos kung paano maililipat ang mga asset (Algorand Standard Assets o Algos) na maaaring mailipat. Ang mga ito ay kumplikadong mga ugnayang pang-ekonomiya na binubuo ng mga pangunahing tagapag-ayos ng transaksyon na nakasulat sa isang bagong wika na tinatawag na Transaction Exmission Approval Language (TEAL).

Mayroong karaniwang tatlong paraan na maaari mong isulat na smart contract sa Algorand. Maaari kang sumulat gamit ang Python SDK o paggamit ng Pyteal na kung saan ay pythonic ang paraan ng pagkakatawan sa mga program ng Teal o direktang pagsulat mula sa scratch gamit ang mga Teal opcode. Sa susunod na artikulo, malalaman mo kung paano magsagawa ng transaksyon gamit ang pyteal.

Mga mapagkukunan.

Website

Developer

Blog ni Ddev


 

Bitcoin Garden 2013-2024, All rights reserved | Privacy Policy | DMCA | About Bitcoin Garden | Support & Services