Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Apr 27th, 2005, 12:40 AM   #1
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,086
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
My Detours In Python

Everyonce in a while I'll decide to put down my RPG for an hour and program something completely pointless. I'll post all that I do during those periods, here:

MSN ASCII GENERATOR
def display(x,y):
    print
    for a in range(len(x)):
        for b in range(len(x[a])):
            if x[a][b]==" ":y.append(blank)
            elif x[a][b]=="#":y.append(fill)
        print"".join(y);y=[]
    print
a=raw_input("Load or Draw Your Design? (L/D) ")
if a=="D" or a=="d":
    display(x,[]);a=raw_input("Save? (Y/N) ")
    if a=="Y" or a=="y":print;b=input("Save Slot? ");the_file=open("designs_"+str(b),'w');the_text="("+str(b)+") "+str(x);the_file.write(the_text)
else:
    print;b=input("Load Slot Number? ");the_file=open("designs_"+str(b),'r');the_contents=the_file.read();r=[]
    for c in range(len(the_contents)):
        if the_contents[c:c+len(str(b))]==str(b):r.append(c)
        elif the_contents[c:c+len(str(b))]==int:r.append(c)   
    if len(r)==1:r.append(len(the_contents));x=[];f=[]
    for a in range(len(the_contents[r[0]+4+len(str(b)):r[1]-2])):
        if the_contents[r[0]+4+len(str(b))+a]=="'":f.append(a)
    x.append(the_contents[r[0]+4+len(str(b)):r[0]+4+len(str(b))+f[0]])
    for a in range(1,len(f)):
        if a%2==0:x.append(the_contents[r[0]+5+len(str(b))+f[a-1]:r[0]+4+len(str(b))+f[a]])
    x.append(the_contents[r[0]+5+len(str(b))+f[len(f)-1]:r[1]-2])
    if r!=[]:display(x,[])

That was actually pretty hard and complicated to make. Lots of trial and error. And lots of unecessary listing (my style of doing things).

How to run the program:
###########################################################################




#DRAW ASCII HERE
x = [
    ' ######## ',
    '##########',
    '### ## ###',
    '##########',
    ' ###  ### ',
    '  ##  ##  ',
    '  ######  ',
    ]

#REPLACE WITH EMOTIONS OF YOUR CHOICE
blank = "<>"
fill = "(@)"





###########################################################################

The output of the program would be:
<>(@)(@)(@)(@)(@)(@)(@)(@)<>
(@)(@)(@)(@)(@)(@)(@)(@)(@)(@)
(@)(@)(@)<>(@)(@)<>(@)(@)(@)
(@)(@)(@)(@)(@)(@)(@)(@)(@)(@)
<>(@)(@)(@)<><>(@)(@)(@)<>
<><>(@)(@)<><>(@)(@)<><>
<><>(@)(@)(@)(@)(@)(@)<><>

Which can then be copy pasted into MSN to make a skull (if you have <> set to a custom blank box emotion). You could easily modify this program to make tons of really cool pictures with your own emotions.

The reason the program is bigger then it would really be, is because you can save and load all your designs from the Shell (practically to an infinite extent!).

More pointless stuff to come.

Last edited by Sane; Apr 27th, 2005 at 12:43 AM.
Sane is offline   Reply With Quote
Old Apr 27th, 2005, 2:02 AM   #2
bl00dninja
Programming Guru
 
bl00dninja's Avatar
 
Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 6 bl00dninja is on a distinguished road
sounds really cool, keep us updated.
__________________
i put on my robe and wizard hat...

Have you ever heard of Plato, Aristotle, Socrates?...Morons.
bl00dninja is offline   Reply With Quote
Old Apr 27th, 2005, 3:07 AM   #3
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
A Code Critique - no offence intended.
  1. Use spaces and returns. The ONLY reason for not using them should be if you are deliberately obfuscating/golfing.
  2. Use meaningful names. "b" means nothing - it should be called something like "slot". (An exception can be made for loop variables and temporary values)
  3. Don't use input() - always use raw_input(). input() is not only insecure, it's likely to make your code blow up accidently. Not only that, but since you want your slot to be a string anyway, using raw_input() will allow you to change all those str(b) calls to just slot.
  4. Use string formatting rather than string addition. Conversions get done automatically, and they tend to be more readable.
  5. If you find yourself checking for both lower and upper case versions of a letter, you should be using the upper()method.
  6. "\n" is used for new lines.
  7. if you're just doing a check of whether a list has any contents, you don't need to compare it against a list - you can just use "if mylist:" or "if not mylist:"
  8. Given that you're using the slot for the filename, you don't need to store the slot in your savefile. This significantly simplifies things.
  9. passing in a blank list to y in display() is unnecessary - parameters should only be for things which can be different values.
  10. You don't check for errors when loading the file - if an incorrect slot is given, it will blow up.
  11. In general, if you are explicitly using a lot of string indexing, and you never need to go backward, you probably shouldn't be.
  12. If you assign an open file to a variable, you should probably close() it (in theory the closing is automatic, in practice it may not be... Hence I try not to assign open files to variables ;-)

Money where my mouth is time :
#DRAW ASCII HERE
drawing = [
    ' ######## ',
    '##########',
    '### ## ###',
    '##########',
    ' ###  ### ',
    '  ##  ##  ',
    '  ######  ',
    ]

#REPLACE WITH EMOTIONS OF YOUR CHOICE
BLANK = "< >"
FILL = "(@)"

def format(lines):
    trans_tbl = {" ": BLANK,
                 "#": FILL}
    try:
        return ["".join([trans_tbl[char] for char in line])
                for line in lines]
    except KeyError:
        raise ValueError("Invalid character '%s' found in drawing.")

def display(lines):
    print
    for line in format(lines):
        print line
    print

def main():
    global drawing
    choice = raw_input("Load or Draw Your Design? (L/D) ").upper()

    if choice == "L":
        slot = raw_input("\nLoad Slot Number? ")
        try:
            drawing = open("designs_%s"%slot, 'r').read().split("\n")
        except IOError:
            print "Invalid Slot Number"
            return

    display(drawing)

    if choice == "D":
        choice = raw_input("Save? (Y/N) ").upper()
        if choice == "Y":
            slot = raw_input("\nSave Slot? ")
            open("designs_%s"%slot,'w').write("\n".join(drawing))
            
if __name__ == "__main__":
    main()
--OH.
hydroxide is offline   Reply With Quote
Old May 13th, 2005, 10:43 PM   #4
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,086
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
Here's another pointless program, but fun to make nonetheless.

Tic-Tac-Toe, use the num-pad to select your piece.

I programmed an AI for this once, it was long and pointless, I won't bother this time.

There may be some un-noticed bugs, but it works fine, and it's easy to maintain. I don't care if the variables mean nothing or if it's difficult to read, I understand it fine.

class Board(object):    
    def __init__(self):
        self.a1="_";self.b1="_";self.c1="_";self.a2="_";self.b2="_";self.c2="_";self.a3="_";self.b3="_";self.c3="_";self.board=[" %s | %s | %s "%(self.a1, self.b1, self.c1)," %s | %s | %s "%(self.a2, self.b2, self.c2)," %s | %s | %s "%(self.a3, self.b3, self.c3)]        
        self.Update() ; self.Status=self.Check()

    def AddPiece(self, piece, place):       
        if place == 7:
            if self.a1 == "_":self.a1 = piece;ret = 'Move'
            else:ret = 'NoMove'
        if place == 8:
            if self.b1 == "_":self.b1 = piece;ret = 'Move'
            else:ret = 'NoMove'
        if place == 9:
            if self.c1 == "_":self.c1 = piece;ret = 'Move'
            else:ret = 'NoMove'        
        if place == 4:
            if self.a2 == "_":self.a2 = piece;ret = 'Move'
            else:ret = 'NoMove'
        if place == 5:
            if self.b2 == "_":self.b2 = piece;ret = 'Move'
            else:ret = 'NoMove'
        if place == 6:
            if self.c2 == "_":self.c2 = piece;ret = 'Move'
            else:ret = 'NoMove'        
        if place == 1:
            if self.a3 == "_":self.a3 = piece;ret = 'Move'
            else:ret = 'NoMove'                
        if place == 2:
            if self.b3 == "_":self.b3 = piece;ret = 'Move'
            else:ret = 'NoMove'                
        if place == 3:
            if self.c3 == "_":self.c3 = piece;ret = 'Move'
            else:ret = 'NoMove'
        self.board = [" %s | %s | %s "%(self.a1, self.b1, self.c1)," %s | %s | %s "%(self.a2, self.b2, self.c2)," %s | %s | %s "%(self.a3, self.b3, self.c3)];return ret

    def Check(self):
        for a in range(2):
            if a == 0:p = "X"
            else:p = "O"                
            if self.a1 == p:
                if self.a2 == p:
                    if self.a3 == p:return p+' Won!'
            if self.b1 == p:
                if self.b2 == p:
                    if self.b3 == p:return p+' Won!'
            if self.c1 == p:
                if self.c2 == p:
                    if self.c3 == p:return p+' Won!'                    
            if self.a1 == p:
                if self.b1 == p:
                    if self.c1 == p:return p+' Won!'
            if self.a2 == p:
                if self.b2 == p:
                    if self.c2 == p:return p+' Won!'
            if self.a3 == p:
                if self.b3 == p:
                    if self.c3 == p:return p+' Won!'
            if self.a1 == p:
                if self.b2 == p:
                    if self.c3 == p:return p+' Won!'
            if self.c1 == p:
                if self.b2 == p:
                    if self.a3 == p:return p+' Won!'                    
        if self.a1 != "_":
            if self.a2 != "_":
                if self.a3 != "_":
                    if self.b1 != "_":
                        if self.b2 != "_":
                            if self.b3 != "_":
                                if self.c1 != "_":
                                    if self.c2 != "_":
                                        if self.c3 != "_":return 'Stalemate'
        return 'NoWin'        

    def Update(self):
        for a in range(3):print self.board[a]
        
Board = Board()

import random;a = random.randrange(1, 3)

while Board.Status == 'NoWin':
    if a == 1: a = 2 ; piece = "O"
    else: a = 1 ; piece = "X"  
    m = 'NoMove'
    while m == 'NoMove':        
        b = raw_input("Player %s Turn! "%(a));m = Board.AddPiece(piece, int(b))
    Board.Update() ; Board.Status = Board.Check()

print Board.Status

Just for fun I made the program pointlessly short, which is tres cool:

class Board(object):    
    def __init__(self):self.a1="_";self.b1="_";self.c1="_";self.a2="_";self.b2="_";self.c2="_";self.a3="_";self.b3="_";self.c3="_";self.board=[" %s | %s | %s "%(self.a1, self.b1, self.c1)," %s | %s | %s "%(self.a2, self.b2, self.c2)," %s | %s | %s "%(self.a3, self.b3, self.c3)];self.pie=["X","O"];self.Move='NoMove';self.Update();self.Status=self.Check()
    def AddPiece(self,piece,place):
        p2=[self.a3,self.b3,self.c3,self.a2,self.b2,self.c2,self.a1,self.b1,self.c1];p=p2[place-1]
        if p=="_":p=piece;p2[place-1]=p;ret='Move';self.a1=p2[6];self.b1=p2[7];self.c1=p2[8];self.a2=p2[3];self.b2=p2[4];self.c2=p2[5];self.a3=p2[0];self.b3=p2[1];self.c3=p2[2];return ret
        return'NoMove'
    def Check(self):
        for b in range(16):
            if [[self.a1,self.a2,self.a3],[self.b1,self.b2,self.b3],[self.c1,self.c2,self.c3],[self.a1,self.b1,self.c1],[self.a2,self.b2,self.c2],[self.a3,self.b3,self.c3],[self.a1,self.b2,self.c3],[self.c1,self.b2,self.a3]][((b+1)/2)-1][0]==self.pie[b%2] and [[self.a1,self.a2,self.a3],[self.b1,self.b2,self.b3],[self.c1,self.c2,self.c3],[self.a1,self.b1,self.c1],[self.a2,self.b2,self.c2],[self.a3,self.b3,self.c3],[self.a1,self.b2,self.c3],[self.c1,self.b2,self.a3]][((b+1)/2)-1][1]==self.pie[b%2] and [[self.a1,self.a2,self.a3],[self.b1,self.b2,self.b3],[self.c1,self.c2,self.c3],[self.a1,self.b1,self.c1],[self.a2,self.b2,self.c2],[self.a3,self.b3,self.c3],[self.a1,self.b2,self.c3],[self.c1,self.b2,self.a3]][((b+1)/2)-1][2]==self.pie[b%2]:return self.pie[b%2]+' Won!'
            if self.a1!="_"and self.a2!="_"and self.a3!="_"and self.b1!="_"and self.b2!="_"and self.b3!="_"and self.c1!="_"and self.c2!="_"and self.c3!="_":return'Stalemate'
        return'NoWin'
    def Update(self):self.board=[" %s | %s | %s "%(self.a1,self.b1,self.c1)," %s | %s | %s "%(self.a2,self.b2,self.c2)," %s | %s | %s "%(self.a3,self.b3,self.c3)];print self.board[0];print self.board[1];print self.board[2]
Board=Board();import random;a=random.randrange(1,3)
while Board.Status=='NoWin':   
    while Board.Move=='NoMove':b=raw_input("Player %s Turn! "%((a%2)+1));Board.Move=Board.AddPiece(Board.pie[(a%2)-1],int(b))
    Board.Update();Board.Status=Board.Check();Board.Move='NoMove';a+=1
print Board.Status

17 lines, wachaa .

Last edited by Sane; May 14th, 2005 at 8:34 PM.
Sane is offline   Reply With Quote
Old May 14th, 2005, 9:46 PM   #5
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,086
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
while 1:import random;print"Rock,";print"Paper,";Move=raw_input("Scissors! ");Move=Move.lower();Comp=random.choice([0,1,2]);print[["Tie","Beat by Paper.","Rock beats Scissors."][Comp],["Paper beats Rock.","Tie","Beat by Scissors."][Comp],["Beat by Rock.","Scissors beats Paper.","Tie"][Comp]][int(round(int(len(Move))/2.8)-1)];print


Woohoo, lol.

Check the link in my siggy for all ze pointless programs.
__________________
Looking for tough programming challenges? Try participating in Sane's Monthly Algorithms Challenges!
Composing Techno is a little side hobby of mine. Techno by DJ Sane. All free for download.
Sane is offline   Reply With Quote
Old May 14th, 2005, 10:01 PM   #6
andy_m
Newbie
 
Join Date: Feb 2005
Posts: 8
Rep Power: 0 andy_m is on a distinguished road
dude, that's freakin' awesome
andy_m is offline   Reply With Quote
Old May 15th, 2005, 2:22 AM   #7
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by Sane
Tic-Tac-Toe, use the num-pad to select your piece.
My version - a pleasant 70 lines of code:
import random
from itertools import cycle

class Board(object):    
    def __init__(self):
        self.layout = [[0 for i in range(3)]
                          for j in range(3)]
        self.players = cycle([1,2])
        self.winner = 0

    def get_move(self):
        prompt = "Player %s's turn: "%self.player
        pos = raw_input(prompt)
        while True:
            try:
                ipos = int(pos)
                if len(pos) != 1:
                    raise ValueError
            except ValueError:
                pass
            else:
                if 1 <= ipos <= 9:
                    return ipos
            pos = raw_input("Error in position.  "+prompt)

    def add_piece(self, place):
        row, col = divmod(place - 1, 3)
        row = 2 - row
        if self.layout[row][col]:
            return False
        else:
            self.layout[row][col] = self.player
            return True

    def check_line(self, line):
        s = set(line)
        if len(s) == 1:
            p = s.pop()
            if p:
                self.winner = p
                return True
        return False
    
    def check(self):
        rows = self.layout
        columns = [[self.layout[i][j] for i in range(3)]
                      for j in range(3)]
        nw_se_diag = [[self.layout[i][i] for i in range(3)]]
        sw_ne_diag = [[self.layout[i][2-i] for i in range(3)]]
        for line in rows + columns + nw_se_diag + sw_ne_diag:
            if self.check_line(line):
                return True
        for row in rows:
            if 0 in row:
                return False
        return True

    def run(self):
        if random.choice([True, False]):
            self.player = self.players.next()

        while not self.check():
            print self
            self.player = self.players.next()
            while True:
                move = self.get_move()
                if self.add_piece(move):
                    break
        print self
        if self.winner:
            print "Player %s won!"%self.winner
        else:
            print "Stalemate"

    def make_row(self, row):
        return " | ".join(["_", "X", "O"][pos] for pos in row)

    def __str__(self):
        return "\n".join(self.make_row(row) for row in self.layout)

if __name__ == "__main__":
    Board().run()

...or an unpleasant 1 line of code:
for elem in ["import random","from itertools import cycle","""class Board(object):    \n    def __init__(self):\n        self.layout = [[0 for i in range(3)]\n                          for j in range(3)]\n        self.players = cycle([1,2])\n        self.winner = 0\n\n    def get_move(self):\n        prompt = "Player %s\'s turn: "%self.player\n        pos = raw_input(prompt)\n        while True:\n            try:\n                ipos = int(pos)\n                if len(pos) != 1:\n                    raise ValueError\n            except ValueError:\n                pass\n            else:\n                if 1 <= ipos <= 9:\n                    return ipos\n            pos = raw_input("Error in position.  "+prompt)\n\n    def add_piece(self, place):\n        row, col = divmod(place - 1, 3)\n        row = 2 - row\n        if self.layout[row][col]:\n            return False\n        else:\n            self.layout[row][col] = self.player\n            return True\n\n    def check_line(self, line):\n        s = set(line)\n        if len(s) == 1:\n            p = s.pop()\n            if p:\n                self.winner = p\n                return True\n        return False\n    \n    def check(self):\n        rows = self.layout\n        columns = [[self.layout[i][j] for i in range(3)]\n                      for j in range(3)]\n        nw_se_diag = [[self.layout[i][i] for i in range(3)]]\n        sw_ne_diag = [[self.layout[i][2-i] for i in range(3)]]\n        for line in rows + columns + nw_se_diag + sw_ne_diag:\n            if self.check_line(line):\n                return True\n        for row in rows:\n            if 0 in row:\n                return False\n        return True\n\n    def run(self):\n        if random.choice([True, False]):\n            self.player = self.players.next()\n\n        while not self.check():\n            print self\n            self.player = self.players.next()\n            while True:\n                move = self.get_move()\n                if self.add_piece(move):\n                    break\n        print self\n        if self.winner:\n            print "Player %s won!"%self.winner\n        else:\n            print "Stalemate"\n\n    def make_row(self, row):\n        return " | ".join(["_", "X", "O"][pos] for pos in row)\n\n    def __str__(self):\n        return "\\n".join(self.make_row(row) for row in self.layout)""","Board().run()"]:exec elem

--OH.
hydroxide is offline   Reply With Quote
Old May 15th, 2005, 8:26 AM   #8
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,086
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
Hydro, none of your programs actually run.
return " | ".join(["_", "X", "O"][pos] for pos in row)
I guess it's because I have 2.3

To shorten it down, I didn't just write it horizantally though, the code is actually way different, which shortened file size. And the longest line horizantally can actually be split up into two more lines which shorten's file size even more:
    def Check(self):
        for b in range(16):
            W = [[self.a1,self.a2,self.a3],[self.b1,self.b2,self.b3],[self.c1,self.c2,self.c3],[self.a1,self.b1,self.c1],[self.a2,self.b2,self.c2],[self.a3,self.b3,self.c3],[self.a1,self.b2,self.c3],[self.c1,self.b2,self.a3]][((b+1)/2)-1]
            if W[0]==self.pie[b%2]and W[1]==self.pie[b%2]and W[2]==self.pie[b%2]:return self.pie[b%2]+' Won!'
            if self.a1!="_"and self.a2!="_"and self.a3!="_"and self.b1!="_"and self.b2!="_"and self.b3!="_"and self.c1!="_"and self.c2!="_"and self.c3!="_":return'Stalemate'

I'm now making checkers/draughts.
__________________
Looking for tough programming challenges? Try participating in Sane's Monthly Algorithms Challenges!
Composing Techno is a little side hobby of mine. Techno by DJ Sane. All free for download.

Last edited by Sane; May 15th, 2005 at 8:31 AM.
Sane is offline   Reply With Quote
Old May 15th, 2005, 8:47 PM   #9
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by Sane
Hydro, none of your programs actually run.
I guess it's because I have 2.3
Yup - my code may use a 2.4 idiom or two (gencomps can be turned into listcomps, though by wrapping them in [])

yrs All-my-programs-run-provided-I'm-the-one-running-them-ly, --OH.
hydroxide is offline   Reply With Quote
Old May 16th, 2005, 8:46 PM   #10
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,086
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
Operation PySane

I've started building my own Module for completing easy tasks even easier. These are the functions I have already built.

| ================================================================== |
 %  %  %  %  %  %  %  %    Determine Module    %  %  %  %  %  %  %  % 
| ================================================================== |

  PySane.Determine.Prime(x)
  
    - Returns "True" if Prime, otherwise "False".

| ================================================================== |
 %  %  %  %  %  %  %  %    Calculate Module    %  %  %  %  %  %  %  % 
| ================================================================== |

  PySane.Calculate.Exponent(Base,Product)[PySane.Result.Exponent]

    - Returns the Exponent needed to satisfy the equation
      Base**Exponent <= Product

| ------------------------------------------------------------------ |

  PySane.Calculate.Exponent(Base,Product)[PySane.Result.Modulus]

    - Returns the Modulus/Remainder, of the equation Base**Exponent
      <= Product, which can add to the primary Product to equal the
      given product.

| ------------------------------------------------------------------ |

  PySane.Calculate.Quadratic.Roots([a, b, c])

    - Returns the roots of the Quadratic Function according to the
      given abc values.

| ------------------------------------------------------------------ |

  PySane.Calculate.Quadratic.Solve([a, b, c], x)

    - Solves the Y value of a quadratic function, according to the
      abc values (equation definition), and the x value you give it.

| ================================================================== |
 %  %  %  %  %  %  %  %      Game Module      %  %  %  %  %  %  %  % 
| ================================================================== |

  PySane.Game.TicTacToe()

    - Loads the Two-Player ASCII Tic-Tac-Toe. To be played with the
      NumPad.

| ------------------------------------------------------------------ |

And here is PySane v0.01 . lol .

class Determine(object):
   def Prime(self,x):
       prime=0
       if x<3:return ["False", "True"][int(round((float(x)/2)-0.499999999999999))]
       for b in range(1,x+1):
           if x%b!=0:prime+=1
       return["True","False"][(int(round(((float(x)-2)/prime)+0.499999999999999)))-1]
class Calculate(object):
    def Exponent(self,base,number):
        b=1
        while base**b<=number:b+=1
        b-=1
        return[b,number-(base**b)]
    class Quadratic(object):
        def Roots(self, equation):
            a = float(equation[0]);b = float(equation[1]);c = float(equation[2])
            o = (b**2.00)-(4.00*a*c)
            if o < 0.00000000000001:
                print "Invalid Inputs"
            else:
                import math
                x1 = (-b + ( math.sqrt(o) ))/(2.00*a)
                x2 = (-b - ( math.sqrt(o) ))/(2.00*a)
                return [x1, x2]
        def Solve(self, equation, x):
            a = float(equation[0]);b = float(equation[1]);c = float(equation[2]);x = float(x)
            return float( (a*(x**2))+(b*x)+(c) )
    Quadratic = Quadratic()
class Result(object):
    def __init__(self):
        self.Exponent = 0
        self.Modulus = 1
class Game(object):
    def TicTacToe(self):
        class Board(object):    
            def __init__(self):self.a1="_";self.b1="_";self.c1="_";self.a2="_";self.b2="_";self.c2="_";self.a3="_";self.b3="_";self.c3="_";self.board=[" %s | %s | %s "%(self.a1, self.b1, self.c1)," %s | %s | %s "%(self.a2, self.b2, self.c2)," %s | %s | %s "%(self.a3, self.b3, self.c3)];self.pie=["X","O"];self.Move='NoMove';self.Update();self.Status=self.Check()
            def AddPiece(self,piece,place):
                p2=[self.a3,self.b3,self.c3,self.a2,self.b2,self.c2,self.a1,self.b1,self.c1];p=p2[place-1]
                if p=="_":p=piece;p2[place-1]=p;ret='Move';self.a1=p2[6];self.b1=p2[7];self.c1=p2[8];self.a2=p2[3];self.b2=p2[4];self.c2=p2[5];self.a3=p2[0];self.b3=p2[1];self.c3=p2[2];return ret
                return'NoMove'
            def Check(self):
                for b in range(16):
                    W = [[self.a1,self.a2,self.a3],[self.b1,self.b2,self.b3],[self.c1,self.c2,self.c3],[self.a1,self.b1,self.c1],[self.a2,self.b2,self.c2],[self.a3,self.b3,self.c3],[self.a1,self.b2,self.c3],[self.c1,self.b2,self.a3]][((b+1)/2)-1]
                    if W[0]==self.pie[b%2]and W[1]==self.pie[b%2]and W[2]==self.pie[b%2]:return self.pie[b%2]+' Won!'
                    if self.a1!="_"and self.a2!="_"and self.a3!="_"and self.b1!="_"and self.b2!="_"and self.b3!="_"and self.c1!="_"and self.c2!="_"and self.c3!="_":return'Stalemate'
                return'NoWin'
            def Update(self):self.board=[" %s | %s | %s "%(self.a1,self.b1,self.c1)," %s | %s | %s "%(self.a2,self.b2,self.c2)," %s | %s | %s "%(self.a3,self.b3,self.c3)];print self.board[0];print self.board[1];print self.board[2]
        Board=Board();import random;a=random.randrange(1,3)
        while Board.Status=='NoWin':   
            while Board.Move=='NoMove':b=raw_input("Player %s Turn! "%((a%2)+1));Board.Move=Board.AddPiece(Board.pie[(a%2)-1],int(b))
            Board.Update();Board.Status=Board.Check();Board.Move='NoMove';a+=1
        print Board.Status

Determine = Determine()
Calculate = Calculate()
Result = Result()
Game = Game()

This is not a full-time project. Just another detour for when I run out of things to program for the game. Please give me more simple functions to program. I want to make this really big and really complete (and really pointless).

Ideas please!
__________________
Looking for tough programming challenges? Try participating in Sane's Monthly Algorithms Challenges!
Composing Techno is a little side hobby of mine. Techno by DJ Sane. All free for download.
Sane is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 2:19 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC