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 - def EvalC(A,B,C,V,K):
-
#Evaluates each row or column to determine True or False
-
if A== V:
-
i = 1
-
if B == V:
-
i = 2
-
if C == V:
-
i = 3
-
return True
-
elif A == K:
-
n = 1
-
if B == K:
-
n = 2
-
if C ==K:
-
n = 3
-
return False
-
Matrix = []
-
while True:
-
Input = raw_input()
-
if Input:
-
Input = Matrix.append(Input.split())
-
else:
-
break
-
#takes the input an put it into a list
-
#e.g.[['X', '0', '0'], ['X', '-', '-'], ['X', '0', '0']]
-
TRow = Matrix[0][0] + Matrix[0][1] + Matrix[0][2]
-
MRow = Matrix[1][0] + Matrix[1][1] + Matrix[1][2]
-
BRow = Matrix[2][0] + Matrix[2][1] + Matrix[2][2]
-
LCol = TRow[0] + MRow[0] + BRow[0]
-
MCol = TRow[1] + MRow[1] + BRow[1]
-
RCol = TRow[2] + MRow[2] + BRow[2]
-
VertR = TRow[0] + MRow[1] + BRow[2]
-
VertL = TRow[2] + MRow[1] + BRow[0]
-
#above are all the possible combos for wins
-
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")),
-
(EvalC(TRow[0],MRow[1],BRow[2],"X","0")),(EvalC(TRow[2],MRow[1],BRow[0],"X","0")),
-
(EvalC(Matrix[0][0],Matrix[0][1],Matrix[0][2],"X","0")),(EvalC(Matrix[1][0],Matrix[1][1],Matrix[1][2],"X","0")),
-
(EvalC(Matrix[2][0],Matrix[2][1],Matrix[2][2],"X","0"))]
-
#the function applied to each possible win combo
-
A possible output at this level would be:
-
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!!!
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! - List1=[True,None,None,None]
-
-
#Start with both players having lost
-
Awon=False
-
Bwon=False
-
-
#Go through all the events and update the winner
-
for i in List1:
-
if i==True: Awon=True
-
elif i==False: Bwon=True
-
-
#Check if A won:
-
if Awon:
-
#Check if B also won
-
if Bwon:
-
print "both won!"
-
else:
-
print "A won!"
-
else:
-
if Bwon:
-
print "B won!"
-
else:
-
print "Neither won!"
Good luck, and post back to let us know how it goes!
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?
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!
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
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! - class OX:
-
"""Class for noughts and crosses"""
-
def __init__(self,startPos=None):
-
"""Optional parameter of startPos (blank board if omitted)"""
-
-
if startPos==None: #create startPos with blank position
-
startPos = [['-','-','-'],['-','-','-'],['-','-','-']]
-
self.pos = startPos #self.pos is variable holding board structure
-
-
def move(self,row,col,token):
-
"Add token (O or X) to (row,col) position (if allowed)"
-
if token in "oO0": token = "O"
-
if token in "xX": token = "X"
-
if token not in ['O','X']:
-
print "Token must be an 'O' or an 'X'"
-
return
-
if self.pos[row][col]=='-':
-
self.pos[row][col]=token
-
else:
-
print "Must move onto a blank space"
-
-
def __repr__(self):
-
"Used for printing the position"
-
out=""
-
for i in range(3):
-
for j in range(3):
-
out+=self.pos[i][j]+'\t'
-
out+='\n'
-
return out
-
-
def _lines(self):
-
"Generates a list of all 8 lines"
-
p=self.pos
-
l=[]
-
d1=[]
-
d2=[]
-
for i in range(3):
-
l.append([p[i][0],p[i][1],p[i][2]])
-
l.append([p[0][i],p[1][i],p[2][i]])
-
d1.append(p[i][i])
-
d2.append(p[i][2-i])
-
l.append(d1)
-
l.append(d2)
-
return l
-
-
def testwinner(self):
-
"returns result of game so far"
-
l=self._lines()
-
xwin = (['X','X','X'] in l)
-
owin = (['O','O','O'] in l)
-
if xwin and owin:
-
return "Oops. Both win!"
-
if xwin:
-
return "X wins!"
-
if owin:
-
return "O wins!"
-
return "No winner"
-
-
-
def main():
-
"Shows basic class functionality"
-
game=OX()
-
print "blank game created"
-
print game #This prints the output from __repr__ function
-
print
-
-
print "second game with pre-defined position created"
-
game1=OX([['X', 'O', 'O'], ['X', '-', '-'], ['X', 'O', 'O']])
-
print game1
-
print
-
-
print "Test who's won in second game"
-
print game1.testwinner()
-
print
-
-
print "Move made in second game with invalid token"
-
game1.move(1,1,'b')
-
print
-
-
print "Move made in second game on occupied square"
-
game1.move(0,0,'O')
-
print
-
-
print "Valid move made in second game"
-
game1.move(1,1,'O')
-
print
-
-
print "Second game position"
-
print game1
-
print "Test who's won in second game"
-
print game1.testwinner()
-
print
-
-
print "First game is still blank"
-
print game
-
print
-
-
print "Make move in first game"
-
game.move(1,1,"x")
-
print game
-
print
-
-
print "Test who's won first game"
-
print game.testwinner()
-
-
-
-
if __name__=="__main__": main()
-
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!
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!!
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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...
|
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...
|
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;
};
...
|
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>...
| |
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...
|
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 {
|
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...
|
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...
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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...
|
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,...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |