Trying to run a function in a game loop, and then exit that function and run a separate function

Andrew Ely

I'm creating a connect four game using pygame. I created a function called playerOne that contains all the code for that player's turn. I have a second function called playerTwo that contains all the code for the second player's turn. in my game loop, i want to call the first function, have that player make a move, and then have the second player make a move. This should cycle until the game is over. The issue is that its only running one function and never moving onto the next, no matter how much I try. In the following code, I cut out most of my functions code because its just repeating itself. Thank you in advanced to anyone who looks over this code!

import pygame as pg 

#window Size, Sprites, Colors, etc.
display = pg.display.set_mode((500, 500))
white = (255, 255 , 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
board = pg.image.load('board.png')
chipRed = pg.Rect(10, 10, 10, 10)
chipBlack = pg.Rect(10, 10, 10, 10)
display.fill(white)
display.blit(board, (100, 100)) # draws the blank board
playerOneOver = False # Defaults to having player one's turn be NOT over


#board in list form, so the game can later store were chips are located 
boardRowOne = ['b', 'b', 'b', 'b', 'b', 'b', 'b']
boardRowTwo = ['b', 'b', 'b', 'b', 'b', 'b', 'b']
boardRowThree = ['b', 'b', 'b', 'b', 'b', 'b', 'b']
boardRowFour = ['b', 'b', 'b', 'b', 'b', 'b', 'b']
boardRowFive = ['b', 'b', 'b', 'b', 'b', 'b', 'b']
boardRowSix = ['b', 'b', 'b', 'b', 'b', 'b', 'b']

#Player ones move
def playerOne():
    #player settings
    chipColor = red

    #display player one is up
    pg.draw.rect(display, chipColor, (230, 5, 20, 20))

    #Colum selection
    mousePressed = pg.mouse.get_pressed()
    mousePos = pg.mouse.get_pos()   
    for event in pg.event.get():
        if event.type == pg.QUIT: #Exit Out
            pg.quit()
            exit()
        if columOne.collidepoint(mousePos) and mousePressed[0]: # if colum one was selected
            if 'b' in boardRowSix[0]: # if nothing is in row 6 colum one
                del(boardRowSix[0])
                boardRowSix.insert(0, 'r')
                pg.draw.rect(display, chipColor, (110, 320, 20, 20))
                playerOneOver = True
            elif 'b' in boardRowFive[0]: # if nothing is in row 5 colum one
                del(boardRowFive[0])
                boardRowFive.insert(0, 'r')
                pg.draw.rect(display, chipColor, (110, 280, 20, 20))
                playerOneOver = True
            #The above elif is repated for every other colum and row, but I cut it out for my post

#player two move
def playerTwo():
    #player settings
    chipColor = black

    #display player one is up
    pg.draw.rect(display, chipColor, (230, 5, 20, 20))

    #Colum selection
    mousePressed = pg.mouse.get_pressed()
    mousePos = pg.mouse.get_pos()   
    for event in pg.event.get():
        if event.type == pg.QUIT: #Exit Out
            pg.quit()
            exit()
        if columOne.collidepoint(mousePos) and mousePressed[0]: # if colum one was selected
            if 'b' in boardRowSix[0]: # if nothing is in row 6 colum one
                del(boardRowSix[0])
                boardRowSix.insert(0, 'B')
                pg.draw.rect(display, chipColor, (110, 320, 20, 20))
            elif 'b' in boardRowFive[0]: # if nothing is in row 5 colum one
                del(boardRowFive[0])
                boardRowFive.insert(0, 'B')
                pg.draw.rect(display, chipColor, (110, 280, 20, 20))
            #The above elif is repated for every other colum and row, but I cut it out for my post

#game loop
while True:

    #Draw the colum selection
    columOne = pg.Rect(105, 70, 30, 30)
    columTwo = pg.Rect(150, 70, 30, 30)
    columThree = pg.Rect(190, 70, 30, 30)
    columFour = pg.Rect(235, 70, 30, 30)
    columFive = pg.Rect(280, 70, 30, 30)
    columSix = pg.Rect(320, 70, 30, 30)
    columSeven = pg.Rect(365, 70, 30, 30)
    pg.draw.rect(display, blue, (105, 70, 30, 30))
    pg.draw.rect(display, blue, (150, 70, 30, 30))
    pg.draw.rect(display, blue, (190, 70, 30, 30))
    pg.draw.rect(display, blue, (235, 70, 30, 30))
    pg.draw.rect(display, blue, (280, 70, 30, 30))
    pg.draw.rect(display, blue, (320, 70, 30, 30))
    pg.draw.rect(display, blue, (365, 70, 30, 30))

    if playerOneOver == False: # only run if player ones move is over
        playerOne()
    if playerOneOver == True: # run when player ones move is over
        playerTwo() 
    pg.display.flip() # updates the drawings

    #print the board list
    print(boardRowOne)
    print(boardRowTwo)
    print(boardRowThree)
    print(boardRowFour)
    print(boardRowFive)
    print(boardRowSix)
mitoRibo

Try printing out playerOneOver in your while loop. You'll see that it's always False.

Its a problem of scope. You are trying to update the playerOneOver variable inside of the playerOne() function, but because of scope what is actually happening is that a new playerOneOver is being created in your function, its not updating the one you define at the start.

This is desired behavior. You can read lots and lots about scope, for example here.

A more pythonic way to update a variable would be by storing the return value of a function. Consider the code below to fix your problem.

a = 'woo'

def update_bad():
    a = 'wee'

def update_good():
    return 'wee'

print 'Before bad update:',a
update_bad()
print 'After bad update:',a

print 'Before good update:',a
a = update_good()
print 'After good update:',a

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Run Function in Loop in R

Run a function in a loop until

Run a function after a loop

How to run a function in a r loop

Perl run function on script exit/die

run async function before process exit

Run two separate transactions in one PostgreSQL function

Is there a better way to run this function on two separate elements?

How to run a function on a separate thread in Julia?

Make for loop change after 4 iterations--ie run for loop in sets of four, with separate function in between

Unexpected symbol error when trying to run a function

Trying to figure out the run time of my function

passing unknown class as parameter and trying to run function on it

Parse error when trying to run haskell function?

trying to make a menu for a program and run a specific function

TypeError when trying to run function on Pandas Dataframe

Error while trying to run standard deviation function

Error when trying to run a max function in ocaml

Asynchronous function with for loop exit

Python: Trying to run a function multiple times and save values for each run

How do I timeout only a specific function while the rest of the game loop continues to run

Separate function as for loop in R

Run a function inside a while loop inside a string?

SetTimeout infinite loop and run function once

Can this loop in a numba function be optimized to run faster?

run df.apply with lambda function in a loop

How to run function after each FOR loop step

For loop run once or before function is complete?

How to run a function within a loop grouped by a factor?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive