简体   繁体   中英

Checking if all items in a list contain (or rather are) the same string.

I'm almost done making a tic tac toe game, and now I want to write a function that checks if there is a winner. My board is a list of lists :

lst = ['1','2','3','4','5','6','7','8','9']

def board():
print (lst[0:3])
print (lst[3:6])
print (lst[6:])

['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

And this is the function I use for the gameplay:

def move2():
    move2=(input('Player 2: Type a number!'))
    for x in lst:
    if move2 == x:
        lst[int(move2)-1] = 'o'
        board()
        move()
    elif move2.isdigit() and move2 not in lst:
        print('Not that number!')
        break
        board()
        move2()
    elif not move2.isdigit():
        print('Not that number!')
        break
        board()
        move2()

I then split up the original list for the possible winning scenarios:

climax1 = lst[0:3]
climax2 = lst[3:6]
climax3 = lst[6:] 
climax4 = [lst[0],lst[3],lst[6]]
climax5 = [lst[1],lst[4],lst[7]]
climax6 = [lst[2],lst[5],lst[8]]
climax7 = [lst[0],lst[4],lst[8]]

And tried this to check if any of these contain either all 'x's or all 'o's:

def conclusion():
    if all(item == 'x' for item in climax1) or all(item == 'x' for item in climax2) or all(item == 'x' for item in climax3) or all(item == 'x' for item in climax4) or all(item == 'x' for item in climax5) or all(item == 'x' for item in climax6) or all(item == 'x' for item in climax7):
    print('Player 1 wins!')
   elif all(item == 'o' for item in climax1) or all(item == 'o' for item in climax2) or all(item == 'o' for item in climax3) or all(item == 'o' for item in climax4) or all(item == 'o' for item in climax5) or all(item == 'o' for item in climax6) or all(item == 'o' for item in climax7):
    print('Player 2 wins!')
else:
    move()

But when I try to integrate this into the function for the gameplay it says it's not defined. And when I try something like:

all('o' == item for item in climax1)

It returns False every time, even if all the items in that list are an 'o'.

Sorry for the long chunks of code. If any of you have any advice it would be much appreciated.

your assignments:

climax1 = lst[0:3]
climax2 = lst[3:6]
climax3 = lst[6:] 

copy the original list; so when you're updating list, you're not updating the copies. Fix that and your code will work.

(to debug, try adding print(climax1) as a debug statement)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM