Jump to content

Creating a "dice" game using python

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
taabistan

taabistan

    Newbie

  • Members
  • Pip
  • 7 posts
The following is a link to a python assignment:

CMPT 165 Assignment 4

Here is my attempt at the solution. I have been having difficulties as it is not working:

import cgi
form=cgi.FieldStorage()
import cgi
form=cgi.FieldStorage()

import random

name=form.getvalue("name")
value=(form.getvalue ("value"))
die1=random.randint(1,6)
die2=random.randint(1,6)
die3=random.randint(1,6)
die4=random.randint(1,6)
die5=random.randint(1,6)
total=int(die1+die2+die3+die4+die5)


print """Content-type:text/html

<!DOCTYPE html Public "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Dice Game</title>
</head>
<body>
"""


print "<p>Thanks for playing, "".</p>"
print "<p>You bet the total would be at least "+ "str(value)" +" .</p>"
print '"<p>The total rolled was " + str(total) +".</p>"'
if die1==1:
    print "<p><img src='dice-1.png" + "str(die1)" + "die.png' alt='" + "str(die1)" + "' /></p>"
elif diel == 2:
    print "<p><img src='dice-2.png"+"str(die2)" + "' /></p>"
elif diel == 3:
    print "<p><img src='dice-3.png"+"str(die4)" + "' /></p>"
elif diel == 4:
    print "<p><img src='dice-4.png"+"str(die4)" + "' /></p>"
elif diel == 5:
    print "<p><img src='dice-5.png"+"str(die5)" + "' /></p>"
elif diel == 6:
    print "<p><img src='dice-6.png"+"str(die6)" + "' /></p>"
total == value
print "<p> You Won! </p>"
value < total
print "<p> You Won! </p>"
else:
    print "<p> Sorry... You Lost.</p>
    print "</body></html>

Edited by Alexander, 23 November 2010 - 10:21 PM.
[code tags]


#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
The last portion of your code is a bit unclear, did you mean to wrap IF statements around total == value and value < total?
total == value
print "<p> You Won! </p>"
value < total
print "<p> You Won! </p>"
else:
    print "<p> Sorry... You Lost.</p>
    print "</body></html>

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Vladimir

Vladimir

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Hi,

You can check my code that implements basic HttpServer and logic of the game:


import cgi

import cgitb; cgitb.enable()

import random

from BaseHTTPServer import HTTPServer

from BaseHTTPServer import BaseHTTPRequestHandler



class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):

        self.send_response(200)

        self.send_header('Content-type', 'text/html')

        self.end_headers()


        html = """

        <html>

        <body>

        <form method="post">

        <p>

          Name: <input type="text" name="name" id="name" />

        </p>

        <p>

          Value: <input type="text" name="value" id="value" />

        </p>

        <p>

          <input type="submit" value="Submit" />

        </p>

        </form>

        </body>

        </html>

        """


        self.wfile.write(html)


    def do_POST(self):

        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

        if ctype == 'multipart/form-data':

            postvars = cgi.parse_multipart(self.rfile, pdict)

        elif ctype == 'application/x-www-form-urlencoded':

            length = int(self.headers.getheader('content-length'))

            postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)

        else:

            postvars = {}


        self.send_response(200)

        self.send_header('Content-type', 'text/html')

        self.end_headers()


        name = postvars['name'].pop()

        value = postvars['value'].pop()


        html = """

        <html>

        %s

        </html>

        """


        if name and value:

            value = int(value)


            dices_html = []

            sum = 0

            for i in range(5):

                dice = random.randint(1, 6)

                sum += dice

                dices_html.append('%d' % dice)

            dices_html = '<p>Dices: %s</p>' % ' '.join(dices_html)


            result = '<p>Hello, %s. You bet the total would be at least %s. The total rolled was %s. ' % (name, value, sum)

            if value <= sum:

                result += 'You won!</p>'

            else:

                result += 'You lost!</p>'


            self.wfile.write(html % dices_html + result)

        else:

            self.wfile.write(html % '<p>Please enter name and value.</p>')



def main():

    try:

        server = HTTPServer(('', 80), MyHandler)

        print 'started httpserver...'

        server.serve_forever()

    except KeyboardInterrupt:

        print '^C received, shutting down server'

        server.socket.close()



if __name__ == '__main__':

    main()


Can you use any framework to create the game or it should be implemented using stdlib?

#4
taabistan

taabistan

    Newbie

  • Members
  • Pip
  • 7 posts
Sorry mate, all those q's went straight over my head.

Okay, here's a link to my attempt at the game:

Dice Game

Here is the actual game. Compare:

Dice Game

Here is the revised python code which made the aforementioned:

import cgi

form = cgi.FieldStorage()

import cgi

form = cgi.FieldStorage()


import random


name = form.getvalue("name")

value= form.getvalue ("value")

die_1 = random.randint (1, 6)

die_2 = random.randint (1, 6)

die_3 = random.randint (1, 6)

die_4 = random.randint (1, 6)

die_5 = random.randint (1, 6)

die_6 = random.randint (1, 6)

total = int(die_1+die_2+die_3+die_4+die_5+die_6)


# print HTTP/HTML headers

print """Content-type: text/html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>Dice Game</title>

</head>

<body>

"""


#print HTML body using form data

print "<p>Thanks for playing, " + str(name) + ". </p>"

print "<p>You bet the total would be at least " + str(value) +" . </p>"

print "<p>The total rolled was " + str(total) + ". </p>"

if die_1 == 1:

    print "<p><img src='die_1.png"  + str(die_1) + "die_1.png' alt='" + str(die_1) + "' /></p>"

elif die_1 == 2:

    print "<p><img src='die_2.png" + str(die_2) + "die_2.png' alt='" + str(die_2) + "' /></p>"

elif die_1 == 3:

    print "<p><img src='die_3.png" + str(die_3) + "die_3.png' alt='" + str(die_3) + "' /></p>"

elif die_1 == 4:

    print "<p><img src='die_4.png" + str(die_4) + "die_4.png' alt='" + str(die_4) + "' /></p>"

elif die_1 == 5:

    print "<p><img src='die_5.png" + str(die_5) + "die_5.png' alt='" + str(die_5) + "' /></p>"

elif die_1 == 6:

    print "<p><img src='die_6.png" + str(die_6) + "die_6.png' alt='" + str(die_6) + "' /></p>"

if total == value:

    print "<p> You Won! </p>"

if value < total:

    print "<p> You Won! </p>"

if value > total:

    print "<p> Sorry....You Lost.</p>"

    print "</body></html>" 


Again, here is the xHTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<title>Dice Game</title>

<link rel="stylesheet" href="a4.css" />

</head>

<body>

<h1>Dice Game</h1>

<form action="sample.py">

<div class="formin">Enter your name:

<input type="text" size="6" maxlength="30" name= "name" />

</div>

<div class="formin"> You bet the total will be at least:

<input type= "text" size="6" maxlength="3" name="value" />

</div>

<div class="formin">

<input type= "submit" value="Go!" />

</div>

</form>

</body>

</html>


Hopefully, someone can explain why the images are not appearing and my game always results in me losing...?

#5
Vladimir

Vladimir

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
It looks like there is built-in server... How do you run this script on your local machine?

Quote

someone can explain why the images are not appearing
First of all images appear on both links you provided. But you roll the dices 6 times instead of 5. I don't understand why your code works, because you always comparing die_1, but I hope this code should work (rewrite it using loop):

print "<p><img src="die_%s.png" /></p>" % die_1

print "<p><img src="die_%s.png" /></p>" % die_2

print "<p><img src="die_%s.png" /></p>" % die_3

print "<p><img src="die_%s.png" /></p>" % die_4

print "<p><img src="die_%s.png" /></p>" % die_5

Quote

and my game always results in me losing...
You have to convert value to int. Now you compare str with int.

value = form.getfirst('value')

if value:

    value = int(value)