473,486 Members | 2,429 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Go to do with a List

Avatar19
43 New Member
My question is:
I have written a program to take input in the format e.g.

0 0 0
X 0 X
X X 0


the program is supposed to simulate "noughts and crosses" or "Tic Tac Toe" ,depending where you are from, and decide who is the winner i.e. "X" or "0" or if there is no winner, "draw". I am at the point where i can output for each 8 possibilities either "True" if X won or "False" if 0 won in the form of a list. What i don't know how to do is iterate over the elements in the list and get the program
to evaluate if there are both True and False in list to output "draw", if there is only True, to output "X is the winner", or if there is only False, 0 is the winner.
This is my code

Expand|Select|Wrap|Line Numbers
  1. def EvalC(A,B,C,V,K):
  2.     #Evaluates each row or column to determine True or False
  3.     if A== V:
  4.         i = 1
  5.         if B == V:
  6.             i = 2
  7.             if C == V:
  8.                 i = 3
  9.                 return True
  10.     elif A == K:
  11.         n = 1
  12.         if B == K:
  13.             n = 2
  14.             if C ==K:
  15.                 n = 3
  16.                 return False
  17. Matrix = []
  18. while True:
  19.     Input = raw_input()
  20.     if Input:
  21.         Input = Matrix.append(Input.split())
  22.     else:
  23.         break
  24. #takes the input an put it into a list
  25. #e.g.[['X', '0', '0'], ['X', '-', '-'], ['X', '0', '0']]
  26. TRow = Matrix[0][0] + Matrix[0][1] + Matrix[0][2]
  27. MRow = Matrix[1][0] + Matrix[1][1] + Matrix[1][2]
  28. BRow = Matrix[2][0] + Matrix[2][1] + Matrix[2][2]
  29. LCol = TRow[0] + MRow[0] + BRow[0]
  30. MCol = TRow[1] + MRow[1] + BRow[1]
  31. RCol = TRow[2] + MRow[2] + BRow[2]
  32. VertR = TRow[0] + MRow[1] + BRow[2]
  33. VertL = TRow[2] + MRow[1] + BRow[0]
  34. #above are all the possible combos for wins
  35. List1 =[(EvalC(TRow[0],MRow[0],BRow[0],"X","0")),(EvalC(TRow[1],MRow[1],BRow[1],"X","0")),(EvalC(TRow[2],MRow[2],BRow[2],"X","0")),
  36. (EvalC(TRow[0],MRow[1],BRow[2],"X","0")),(EvalC(TRow[2],MRow[1],BRow[0],"X","0")),
  37. (EvalC(Matrix[0][0],Matrix[0][1],Matrix[0][2],"X","0")),(EvalC(Matrix[1][0],Matrix[1][1],Matrix[1][2],"X","0")),
  38. (EvalC(Matrix[2][0],Matrix[2][1],Matrix[2][2],"X","0"))]
  39. #the function applied to each possible win combo
  40. A possible output at this level would be:
  41. List1=[True, None, None, None, None, None, None, None]
Thanks you for any help and also please suggest ways to neaten and shorten my code with more productive functions. Thank you!!!
Apr 16 '10 #1
6 1456
Glenton
391 Recognized Expert Contributor
Hi

Good job on the coding! A couple of points on simplifying the code. A class structure can be very helpful in organising the data.

Also the 8 possible straight lines can be put into a list of some sort, so that you can go through them with a for structure. Personally I tend to use a for structure if there's >=2 items in the list, so I might be a bit extreme! But it is easier to understand and debug. Eg create a blank list (List1 = []), and then cycle through the possibilities appending the result to that. But since you've done the typing anyway, you might as well run with it!

Now as I understand it, the central problem for you is that you've got a list of eight items, each of which can be True, False, or None, and you want to return something sensible.

Add this to bottom of your code!
Expand|Select|Wrap|Line Numbers
  1. List1=[True,None,None,None]
  2.  
  3. #Start with both players having lost
  4. Awon=False
  5. Bwon=False
  6.  
  7. #Go through all the events and update the winner
  8. for i in List1:
  9.     if i==True: Awon=True
  10.     elif i==False: Bwon=True
  11.  
  12. #Check if A won:
  13. if Awon:
  14.     #Check if B also won
  15.     if Bwon:
  16.         print "both won!"
  17.     else:
  18.         print "A won!"
  19. else:
  20.     if Bwon:
  21.         print "B won!"
  22.     else:
  23.         print "Neither won!"
Good luck, and post back to let us know how it goes!
Apr 19 '10 #2
Avatar19
43 New Member
Thanks so much for the input Glenton.. if its not too much trouble could i ask you to demonstrate what you would do with this?, When u talked about class structure and for loops?
Apr 24 '10 #3
Glenton
391 Recognized Expert Contributor
@Avatar19
Have you got the thing working overall? I'll try to have a look next week - since it's for a fellow saffa!
Apr 24 '10 #4
Avatar19
43 New Member
Yah i did get it working i used a very similar if statement like you suggested in your first response so the program does work, but I am very interested to see different ways of doing this.. thanks any help is greatly appreciated
Apr 24 '10 #5
Glenton
391 Recognized Expert Contributor
@Avatar19
Okay, so this is not terribly sophisticated at this point. Object orientation takes a bit of getting used to. It doesn't do anything differently, it's just a way of structuring everything that's ultimately more convenient.

You could then import this code to another script and use the class there, wrap it in a simple GUI or just into a game loop, include some logic for the computer to play some of the moves, alternate the tokens automatically etc.

But I've just put in the basic code here to give you a feel for how it works. If you're not used to class structures it may take a while to get the feel for it. Please try to understand it quite hard before questions. But after bona fide effort, questions welcome!

Expand|Select|Wrap|Line Numbers
  1. class OX:
  2.     """Class for noughts and crosses"""
  3.     def __init__(self,startPos=None):
  4.         """Optional parameter of startPos (blank board if omitted)"""
  5.  
  6.         if startPos==None:  #create startPos with blank position
  7.             startPos = [['-','-','-'],['-','-','-'],['-','-','-']]
  8.         self.pos = startPos #self.pos is variable holding board structure
  9.  
  10.     def move(self,row,col,token):
  11.         "Add token (O or X) to (row,col) position (if allowed)"
  12.         if token in "oO0": token = "O"
  13.         if token in "xX": token = "X"
  14.         if token not in ['O','X']:
  15.             print "Token must be an 'O' or an 'X'"
  16.             return
  17.         if self.pos[row][col]=='-':
  18.             self.pos[row][col]=token
  19.         else:
  20.             print "Must move onto a blank space"
  21.  
  22.     def __repr__(self):
  23.         "Used for printing the position"
  24.         out=""
  25.         for i in range(3):
  26.             for j in range(3):
  27.                 out+=self.pos[i][j]+'\t'
  28.             out+='\n'
  29.         return out
  30.  
  31.     def _lines(self):
  32.         "Generates a list of all 8 lines"
  33.         p=self.pos
  34.         l=[]
  35.         d1=[]
  36.         d2=[]
  37.         for i in range(3):
  38.             l.append([p[i][0],p[i][1],p[i][2]])
  39.             l.append([p[0][i],p[1][i],p[2][i]])
  40.             d1.append(p[i][i])
  41.             d2.append(p[i][2-i])
  42.         l.append(d1)
  43.         l.append(d2)
  44.         return l
  45.  
  46.     def testwinner(self):
  47.         "returns result of game so far"
  48.         l=self._lines()
  49.         xwin = (['X','X','X'] in l)
  50.         owin = (['O','O','O'] in l)
  51.         if xwin and owin:
  52.             return "Oops. Both win!"
  53.         if xwin:
  54.             return "X wins!"
  55.         if owin:
  56.             return "O wins!"
  57.         return "No winner"
  58.  
  59.  
  60. def main():
  61.     "Shows basic class functionality"
  62.     game=OX()
  63.     print "blank game created"
  64.     print game  #This prints the output from __repr__ function
  65.     print
  66.  
  67.     print "second game with pre-defined position created"
  68.     game1=OX([['X', 'O', 'O'], ['X', '-', '-'], ['X', 'O', 'O']])
  69.     print game1
  70.     print
  71.  
  72.     print "Test who's won in second game"
  73.     print game1.testwinner()
  74.     print
  75.  
  76.     print "Move made in second game with invalid token"
  77.     game1.move(1,1,'b')
  78.     print
  79.  
  80.     print "Move made in second game on occupied square"
  81.     game1.move(0,0,'O')
  82.     print
  83.  
  84.     print "Valid move made in second game"
  85.     game1.move(1,1,'O')
  86.     print
  87.  
  88.     print "Second game position"
  89.     print game1
  90.     print "Test who's won in second game"
  91.     print game1.testwinner()
  92.     print
  93.  
  94.     print "First game is still blank"
  95.     print game
  96.     print
  97.  
  98.     print "Make move in first game"
  99.     game.move(1,1,"x")
  100.     print game
  101.     print
  102.  
  103.     print "Test who's won first game"
  104.     print game.testwinner()
  105.  
  106.  
  107.  
  108. if __name__=="__main__": main()
  109.  
Helpful hint: Just copy paste and run at first. Then go through main function and you should be able to follow what it's doing!
Apr 26 '10 #6
Avatar19
43 New Member
Cool thanks a lot, I am going to give it a good look tomorrow and I'll let you know once I get to grips with it!!
Apr 26 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
3065
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesnąt matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone...
10
15097
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy...
24
5715
by: Robin Cole | last post by:
I'd like a code review if anyone has the time. The code implements a basic skip list library for generic use. I use the following header for debug macros: /* public.h - Public declarations and...
4
3582
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; }; ...
3
2690
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h>...
0
1803
by: drewy2k12 | last post by:
Heres the story, I have to create a doubly linked list for class, and i have no clue on how to do it, i can barely create a single linked list. It has to have both a head and a tail pointer, and...
10
6552
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
0
8604
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be...
12
3990
by: kalyan | last post by:
Hi, I am using Linux + SysV Shared memory (sorry, but my question is all about offset + pointers and not about linux/IPC) and hence use offset's instead on pointers to store the linked list in...
7
5756
by: QiongZ | last post by:
Hi, I just recently started studying C++ and basically copied an example in the textbook into VS2008, but it doesn't compile. I tried to modify the code by eliminating all the templates then it...
0
7105
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6967
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7132
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7180
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3076
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3071
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
266
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.