简体   繁体   中英

Alternating between players in a connect four python game

I'm currently writing a function to play Connect Four in Python3. I've progressed well through much of it but am having trouble alternating between two players.

What I'm trying to do is run a function that will place a chip in the appropriate location as a function of the current player, playturn(curr). So what I'm trying to say is that while there's no tie and while there's no winner, the game will continue and alternate between the two players.

If it's Player 1's turn, curr=1 , and if it's Player 2's turn, curr=2 .

My current code isn't working, as it won't allow me to switch between players after each turn if there's no tie or no winner. My logic here was that if curr=1 is initially 1, then I'll have to set curr=2 after the first move. Then, when curr=2 , I have to switch curr equal back to 1. In the following code, checkforwinner and checkfortie are two functions that will return False if there is no winner and if there is no tie. playturn(curr) will place a chip in the correct column depending on the column chosen by either Player1 or Player2.

curr=1
while checkforwinner==False and checkfortie==False:
    if curr==1:
        curr==2
        print(playturn(curr))
    if curr==2:
        curr==1
        print(playturn(curr))

Can someone explain why this code is not working and what can be done to fix it?

curr==2 is a comparison. You probably want curr=2 . The second if should be an elif .

There are a couple ways to make this nicer!

To make your original code work, you should use jspcal's recommendation to turn the comparison operators ( == ) to assignment operators ( = ).

You also need to use an elif for the second comparison, or every single loop will switch the player twice.

curr=1
while not (checkforwinner() or checkfortie()):
    if curr==1:
        curr=2
        print(playturn(curr))
    elif curr==2:
        curr=1
        print(playturn(curr))

You can also clean up the code a little:

def switch_player(current_player):
    if current_player == 1:
        return 2
    elif current_player == 2:
        return 1

while not (checkforwinner() or checkfortie()):
    print(playerturn(curr))
    curr = switch_player(curr)

The last version you might go with is the shortest, but is a little harder to read:

while not (checkforwinner() or checkfortie()):
    print(playerturn(curr))
    curr = 1 if curr == 2 else 2

If checkforwinner and checkfortie are functions, you need parenthesis after them:

while checkforwinner()==False and checkfortie()==False:

Also, as @jspcal pointed out, you want to assign values with a single '=' and only use '==' for boolean comparison.

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