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 1459 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 has any advices??
#include <iostream>
using namespace std;
|
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 *enemydata; // Holds information about an enemy (in a game)
// Its a double linked list node
|
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 macros
*/
#ifndef PUBLIC
#define PUBLIC
|
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;
};
struct pcb *pcb_pointer;
|
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>
#include<stdlib.h>
int main(void)
{
| |
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 each node in the list must contain two pointers, one pointing
forward and one pointing backwards.
Each node in the list will contain 3 data values:...
|
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 anything from a short integer value to a complex struct type, also has a pointer to
the next node in the single-linked list. That pointer will be NULL...
|
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 the shared
memory. I run fedora 9 and gcc 4.2. I am able to insert values in to
the list, remove values from the list, but the problem is 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 compiled no problem. But I can't find the what the problem is with templates? Please help. The main is in test-linked-list.cpp. There are two template...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |