pygame soccer game help

pygame soccer game help

Postby vinceja » Wed Jul 27, 2016 5:40 pm

can someone please review this code I've been writing. it's suppose to be a ball kicking around another ball into a white patch (the net). it worked perfectly until I added the code to keep score that's:
Code: Select all
 # Draw points
    for point in range(points):
        pointX = 0 + point * 5
        pygame.draw.rect(screen, white, (pointX, 3, 4, 10))

and
Code: Select all
print "Total points: " + str(points)

now the program won't work. I'm going to post the complete program next, forgive me if that is not proper coding forum edict but I'm new to this.
Code: Select all
import random
import random
import pygame
pygame.init()
# Window setup
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

# player position
x = size[0] / 2
y = size[1] / 2

# ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])

# Goal position
goalX = size[0] / 2 - 10
goalY = size[1] / 2 - 10
goalW = 20
goalH = 20

# points
points = 0

# colours
red = pygame.color.Color('#FF8080')
blue = pygame.color.Color('#8080FF')
white = pygame.color.Color('#FFFFFF')
black = pygame.color.Color('#000000')

def checkOffScreenX(x):
    if x > size[0]:
        x = 0
    elif x < 0:
        x = size[0]
    return x

def checkOffScreenY(y):
    if y > size[1]:
        y = 0
    elif y < 0:
        y = size[1]
    return y

#Game loop
done = False
while not done:
    screen.fill(black)

    # Draw the goal
    pygame.draw.rect(screen, white, (goalX, goalY, goalW, goalH))

    # Check ball is in goal
    if goalX <= ballX <= goalX + goalH and goalY <= ballY <= goalY + goalH:
        points += 1
        ballX = random.randrange(0, size[0])
        ballY = random.randrange(0, size[0])

    keys = pygame.key.get_pressed()

    #player movement
    if keys [pygame.K_w]:
        y -= 1
    if keys[pygame.K_a]:
        x-= 1
    if keys[pygame.K_s]:
        y += 1
    if keys[pygame.K_d]:
        x += 1

    ballX = checkOffScreenX(ballX)
    ballY = checkOffScreenY(ballY)


    # Check off screen
    x = checkOffScreenX(x)
    y = checkOffScreenY(y)

def checkTouching():
    """Causes a mini explosion of the players are touching"""
    global x
    global ballX
    global y
    global ballY

    # Check if player and ball are touching
    if -10 < y - ballY < 10 and -10 < x - ballX < 10:
       
        #draw an explosion
        pygame.draw.circle(screen, white, [x,y], 15)
       
        xDiff = x - ballX
        yDiff = y - ballY

        # check if ball is on edge of screen
        if ballX == 0:
            xDiff -= 5
        elif ballX == size[0]:
            xDiff += 5
        if ballY == 0:
            yDiff -= 5
        elif ballY == size[1]:
            yDiff += 5

        # move the ball and player
        x += xDiff * 3
        ballX -= xDiff * 3

        y += yDiff * 3
        ballY -= yDiff * 3

    # draw player
    pygame.draw.circle(screen, red, [x,y], 6)

    # check if player is touching th ball
    checkTouching()

    # Draw points
    for point in range(points):
        pointX = 0 + point * 5
        pygame.draw.rect(screen, white, (pointX, 3, 4, 10))
       

    #draw ball
    pygame.draw.circle(screen, blue, [ballX, ballY], 6)
   
    pygame.display.flip()
   
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    clock.tick(72)
pygame.quit()
print "Total points: " + str(points)

again I would really like to get this worked out, any help would much appreciated. Thanks!
Last edited by Yoriz on Wed Jul 27, 2016 5:51 pm, edited 1 time in total.
Reason: First post lock. Added code tags.
vinceja
 
Posts: 1
Joined: Wed Jul 27, 2016 4:24 pm

Re: pygame soccer game help

Postby Ofnuts » Thu Jul 28, 2016 8:24 am

Your programs seems to endlessly loop, and when I interrupt it (Ctrl-C) it it is always in screen.fill(black) so your while loop could be missing something.
This forum has been moved to http://python-forum.io/. See you there.
User avatar
Ofnuts
 
Posts: 2659
Joined: Thu May 14, 2015 9:46 am
Location: Paris, France, EU, Earth, Solar system, Milky Way, Local Cluster, Universe #32987440940987

Re: pygame soccer game help

Postby Mekire » Fri Jul 29, 2016 12:56 pm

So, this is one of those times. You can change a few lines and maybe it will do what you want.
But...
The problem here is a lack of organization.

The following is a bare-bones template for how you should try to structure a pygame application:
Code: Select all
import sys
import pygame as pg


BACKGROUND 
= pg.Color("darkslategray")
SCREEN_SIZE = (500, 500)
FPS = 60


class App
(object):
    def __init__(self):
        self.screen = pg.display.get_surface()
        self.screen_rect = self.screen.get_rect()
        self.clock = pg.time.Clock()
        self.done = False

    def update
(self):
        """
        All updates to all actors occur here.
        Exceptions include things that are direct results of events which
        may occasionally occur in the event loop.

        For example, updates based on held keys should be found here, but
        updates to single KEYDOWN events would be found in the event loop.
        """
        pass

    def render
(self):
        """
        All calls to drawing functions here.
        No game logic.
        """
        self.screen.fill(BACKGROUND)
        pg.display.update()

    def event_loop(self):
        """
        Event handling here.  Only things that are explicit results of the
        given events should be found here.  Do not confuse the event and update
        phases.
        """
        for event in pg.event.get():
           if event.type == pg.QUIT:
               self.done = True

    def main_loop
(self):
        """
        Main loop for your whole app.  This doesn't need to be touched until
        you start writing framerate independant games.
        """
        while not self.done:
            self.event_loop()
            self.update()
            self.render()
            self.clock.tick(FPS)


def main():
    """
    Prepare pygame and the display and create an App instance.
    Call the app instance's main_loop function to begin the App.
    """
    pg.init()
    pg.display.set_mode(SCREEN_SIZE)
    App().main_loop()
    pg.quit()
    sys.exit()


if __name__ == "__main__":
    main()


Also, if you are curious about the "simple" fix to your current code, this gets it to do something.
Whether or not it is what you want, I couldn't say:
Code: Select all
import random
import random
import pygame
pygame
.init()
# Window setup
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

# player position
= size[0] / 2
= size[1] / 2

# ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])

# Goal position
goalX = size[0] / 2 - 10
goalY 
= size[1] / 2 - 10
goalW 
= 20
goalH 
= 20

# points
points = 0

# colours
red = pygame.color.Color('#FF8080')
blue = pygame.color.Color('#8080FF')
white = pygame.color.Color('#FFFFFF')
black = pygame.color.Color('#000000')

def checkOffScreenX(x):
    if x > size[0]:
        x = 0
    elif x 
< 0:
        x = size[0]
    return x

def checkOffScreenY
(y):
    if y > size[1]:
        y = 0
    elif y 
< 0:
        y = size[1]
    return y



def checkTouching
():
    """Causes a mini explosion of the players are touching"""
    global x
    global ballX
    global y
    global ballY

    
# Check if player and ball are touching
    if -10 < y - ballY < 10 and -10 < x - ballX < 10:
        
        
#draw an explosion
        pygame.draw.circle(screen, white, [x,y], 15)
        
        xDiff 
= x - ballX
        yDiff 
= y - ballY

        
# check if ball is on edge of screen
        if ballX == 0:
            xDiff -= 5
        elif ballX 
== size[0]:
            xDiff += 5
        if ballY 
== 0:
            yDiff -= 5
        elif ballY 
== size[1]:
            yDiff += 5

        
# move the ball and player
        x += xDiff * 3
        ballX 
-= xDiff * 3

        y 
+= yDiff * 3
        ballY 
-= yDiff * 3

    
# draw player
    pygame.draw.circle(screen, red, [x,y], 6)

    # Draw points
    for point in range(points):
        pointX = 0 + point * 5
        pygame
.draw.rect(screen, white, (pointX, 3, 4, 10))
        

    
#draw ball
    pygame.draw.circle(screen, blue, [ballX, ballY], 6)
    
    pygame
.display.flip()
   
    for event in pygame
.event.get():
        if event.type == pygame.QUIT:
            done = True
    clock
.tick(72)


#Game loop
done = False
while not done
:
    screen.fill(black)

    # Draw the goal
    pygame.draw.rect(screen, white, (goalX, goalY, goalW, goalH)) 

    
# Check ball is in goal
    if goalX <= ballX <= goalX + goalH and goalY <= ballY <= goalY + goalH:
        points += 1
        ballX 
= random.randrange(0, size[0])
        ballY = random.randrange(0, size[0])

    keys = pygame.key.get_pressed()

    #player movement
    if keys [pygame.K_w]:
        y -= 1
    if keys
[pygame.K_a]:
        x-= 1
    if keys
[pygame.K_s]:
        y += 1
    if keys
[pygame.K_d]:
        x += 1

    ballX 
= checkOffScreenX(ballX)
    ballY = checkOffScreenY(ballY)

    # Check off screen
    x = checkOffScreenX(x)
    y = checkOffScreenY(y)
    checkTouching()
    
pygame
.quit()
print "Total points: " + str(points)

My honest advice is that you start over and try to fit it to the above template; rather than move forward with this spaghetti.
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Mekire
 
Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Re: pygame soccer game help

Postby metulburr » Fri Jul 29, 2016 1:37 pm

Your code looks very much similar to the way books describe how to make a game. I must share with you that there is no book out there that describes with pygame on how to structure a game properly.

You are not using classes. Classes alone will clean up your code and make is easier for you and us to read, but to just organize it in general...which also makes it more maintainable for you. As well as easier for us to spot problems for you. For example, It will organize your ball logic and data into one area. It will separate out the drawing, logic, data, from ball and put them into a class, this in turn will have that much less code in the main game loop allowing it to be more maintainable.

You need to use pygame rects. You can use them to use coordinates to move the object as well as draw the object to the screen. This basically removes all the x, y, ballx, and bally coords scattered amongst your code. This will in the end make something like this

Code: Select all
f -10 < y - ballY < 10 and -10 < x - ballX < 10:


look more like this

Code: Select all
if player.rect.colliderect(ball.rect):


Which is a lot more maintainable and simple for us to fix and read as well as yourself.
we will be moving to python-forum.io on October 1 2016
more details here
User avatar
metulburr
 
Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest

cron