Jump to content

  • Log In with Google      Sign In   
  • Create Account


Nuorah

Member Since 03 Jul 2013
Offline Last Active Jul 20 2013 07:18 AM
-----

Topics I've Started

Python Pygame Pong

05 July 2013 - 02:41 AM

Hello, i just finished to code a pong in python with pygame, and i'd like you to tell me what you think of my code and what could be made better. Thanks!

 

I also have a problem with the text. It's sort of "flashing". I think i know where the problem come from, I think it's because the screen is refreshed before the text without the text, so each frame we see two image, one with the text, one without. I don't know how to solve this problem. 

import pygame, sys, time, random
from pygame.locals import *

pygame.init()
mainClock = pygame.time.Clock()

#Constant of the board of the game
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
SIZESIDES = 20
MIDDLESIZE = 10

#Speed of the game constants
FPS = 30
PADDLESPEED = 10

#Rects of the board of the game
TOPSIDE = pygame.Rect(0, 0, WINDOWWIDTH, SIZESIDES)
BOTTOMSIDE = pygame.Rect(0, WINDOWHEIGHT - SIZESIDES, WINDOWWIDTH, SIZESIDES)
MIDDLE = []
for i in range(0, 31):
    MIDDLE.append(pygame.Rect(WINDOWWIDTH/2 - MIDDLESIZE/2,15 + i*20, MIDDLESIZE, MIDDLESIZE))    

windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)

pygame.display.set_caption('Running_window')

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

gameIsPlaying = False

#These are used to print the scores
CHIFFRES =[
'''WWWWW
W   W
W   W
W   W
WWWWW''',
'''    W
    W
    W
    W
    W''',
'''WWWWW
    W
WWWWW
W    
WWWWW''',
'''WWWWW
    W
WWWWW
    W
WWWWW''',
'''W   W
W   W
WWWWW
    W
    W''',
'''WWWWW
W    
WWWWW
    W
WWWWW''',
'''WWWWW
W    
WWWWW
W   W
WWWWW''',
'''WWWWW
    W
  WWW
    W
    W''',
'''WWWWW
W   W
WWWWW
W   W
WWWWW''',
'''WWWWW
W   W
WWWWW
    W
WWWWW''',
'''''']

#Functions

    #Draw the score (in fact return a list with the rect to draw, drawn later with drawGame())
def drawChiffre(a, x, y):
    countx = 0
    county = 0
    rectList = []
    for piece in CHIFFRES[a]:
        if countx % 7 == 5 or countx % 7 == 6:
            countx +=1
            county +=0.5
        if piece == '''W''':
            rectList.append(pygame.Rect(x + (countx%7)*10, y + county*15, MIDDLESIZE, MIDDLESIZE*1.5))
            countx +=1
        elif piece == ''' ''':
            countx +=1
    return rectList

    #Doesn't work, meant to change the score in case of a win from either side
def score(ball, scoreP1, scoreP2):
    if ball.l <= 0:
        scoreP1 +=1
        ball = Ball(WINDOWHEIGHT/2, WINDOWWIDTH/2, 15, 15, 5, 5)
    if ball.l >= WINDOWWIDTH:
        scoreP2 +=1
        ball = Ball(WINDOWHEIGHT/2, WINDOWWIDTH/2, 15, 15, 5, 5)

    #This function draws everything in the game. 
def drawGame(Paddle1, scoreP1, Paddle2, scoreP2, Ball):
    windowSurface.fill(BLACK)

    Paddle1.draw()
    Paddle2.draw()
    Ball.draw() 

    drawScoreP2 = drawChiffre(scoreP2, 450, 50)
    for piece in drawScoreP2:
        pygame.draw.rect(windowSurface, WHITE, piece)

    drawScoreP1 = drawChiffre(scoreP1, 300, 50)
    for piece in drawScoreP1:
        pygame.draw.rect(windowSurface, WHITE, piece)
        
    pygame.draw.rect(windowSurface, WHITE, TOPSIDE) 
    pygame.draw.rect(windowSurface, WHITE, BOTTOMSIDE)

    for piece in MIDDLE :
        pygame.draw.rect(windowSurface, WHITE, piece)

    pygame.display.update()

    #A function for writing a text with the most basic font
def write(text, fontSize, x, y):
    font = pygame.font.SysFont(None, fontSize)
    
    textR = font.render(text, True, WHITE, None)
    textRect = textR.get_rect()
    textRect.centerx = x
    textRect.centery = y
    windowSurface.blit(textR, textRect)

#Classes
        
    #The paddles
class Paddle:
    rect = pygame.Rect(0, 0, 0, 0)
    movement = 0

    def __init__(self, l, t, w, h):
        self.l = l
        self.t = t
        self.w = w
        self.h = h
    def setRect(self):
        self.rect = pygame.Rect(self.l, self.t, self.w, self.h)
    def setPosition(self):
        self.position = self.t
    def setMovement(self, x):
        self.movement = x
    def move(self):
        self.t = self.t + self.movement*PADDLESPEED
        self.setPosition()
        self.setRect()
    def draw(self):
        pygame.draw.rect(windowSurface, WHITE, self.rect)
    def collideWithSide(self, upSide, downSide):
        if (self.t + self.h) > downSide:
            self.setMovement(0)
        if (self.t) < upSide:
            self.setMovement(0)

    #The ball
class Ball:
    rect = pygame.Rect(0, 0, 0, 0)
    position = [0, 0]

    def __init__(self, l, t, w, h, x, y):
        self.speed = [x, y]
        self.l = l
        self.t = t
        self.w = w
        self.h = h
    def setRect(self):
        self.rect = pygame.Rect(self.l, self.t, self.w, self.h)
    def setPosition(self):
        self.position = [self.l, self.t]
    def setSpeed(self, x, y):
        self.speed = [x, y]
    def draw(self):
        pygame.draw.rect(windowSurface, WHITE, self.rect)
    def move(self):
        self.l = self.l + self.speed[0]
        self.t = self.t + self.speed[1]
        self.setRect()
        self.setPosition()
    def bounce(self, paddle):
        if self.rect.colliderect(paddle.rect):
            self.setSpeed(-self.speed[0], self.speed[1])
    def collideWithSide(self, upSide, downSide):
        if (self.t + self.h) > downSide or (self.t) < upSide:
            self.setSpeed(self.speed[0], -self.speed[1])

#Now the core of the game
while True:

    #Initialization of the score and of the paddles and ball
    scoreP1 = 0
    scoreP2 = 0

    paddle1 = Paddle(0, WINDOWHEIGHT/2 - 40, 15, 80)
    paddle2 = Paddle(WINDOWWIDTH - 15, WINDOWHEIGHT/2 - 40, 15, 80)
    ball = Ball(WINDOWWIDTH/2, WINDOWHEIGHT/2, 15, 15, 5, 5)

    #This is the "menu"
    while not gameIsPlaying:
        for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN:
                    if event.key == ord('s'):
                        gameIsPlaying = True
                if event.type == KEYUP:
                    if event.key == ord('q'):
                        pygame.quit()
                        sys.exit()
        

        drawGame(paddle1, scoreP1, paddle2, scoreP2, ball)

        write('Press s', 120, WINDOWWIDTH/4, WINDOWHEIGHT/2)
        write('to play!', 120, 3*WINDOWWIDTH/4, WINDOWHEIGHT/2)

        write('Press q', 60, 3*WINDOWWIDTH/8, 3*WINDOWHEIGHT/4)
        write('to quit.', 60, 5*WINDOWWIDTH/8, 3*WINDOWHEIGHT/4)

        write('UP', 30, 20, WINDOWHEIGHT/4)
        write('DOWN', 30, 36, 3*WINDOWHEIGHT/4)
        
        write('e', 60, WINDOWWIDTH - 15, WINDOWHEIGHT/4)
        write('d', 60, WINDOWWIDTH - 15, 3*WINDOWHEIGHT/4)

        pygame.display.update()
        mainClock.tick(FPS)
        
    #This is the game playing
    while gameIsPlaying:

    
    
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE or event.key == ord('a'):
                    gameIsPlaying = False
                if event.key == K_UP:
                    paddle1.setMovement(-1)
                if event.key == K_DOWN:
                    paddle1.setMovement(1)
                if event.key == ord('e'):
                    paddle2.setMovement(-1)
                if event.key == ord('d'):
                    paddle2.setMovement(1)
            if event.type == KEYUP:
                if event.key == K_UP:
                    paddle1.setMovement(0)
                if event.key == K_DOWN:
                    paddle1.setMovement(0)
                if event.key == ord('e'):
                    paddle2.setMovement(0)
                if event.key == ord('d'):
                    paddle2.setMovement(0)
                

        #Move the ball and the paddles
        paddle1.move()
        paddle2.move()
        ball.move()

        #Collision between the ball and the paddles
        ball.bounce(paddle1)
        ball.bounce(paddle2)

        #Check if score and incrementation
        if ball.l <= 0:
            scoreP1 +=1
            ball = Ball(WINDOWWIDTH/2, WINDOWHEIGHT/2, 15, 15, random.randint(3, 5), random.randint(3, 5))
        if ball.l >= WINDOWWIDTH:
            scoreP2 +=1
            ball = Ball(WINDOWWIDTH/2, WINDOWHEIGHT/2, 15, 15, random.randint(3, 5), random.randint(3, 5))

        #Check if winner and displaying and back to the menu
        if scoreP1 >= 10:
            write('WINNER', 60, WINDOWWIDTH/8, 2*WINDOWHEIGHT/8)
            pygame.display.update()
            time.sleep(1)
            gameIsPlaying = False

        if scoreP2 >= 10:
            write('WINNER', 60, 5*WINDOWWIDTH/8, 2*WINDOWHEIGHT/8)
            pygame.display.update()
            time.sleep(1)
            gameIsPlaying = False
            
        #Collision of the paddles and the ball with the sides
        paddle1.collideWithSide(20, 580)
        paddle2.collideWithSide(20, 580)
        ball.collideWithSide(20, 580)

        
        drawGame(paddle1, scoreP1, paddle2, scoreP2, ball)

        #Acceleration of the ball
        ball.setSpeed(ball.speed[0]*1.001, ball.speed[1])

        write('Press escape to give up this game', 15, WINDOWWIDTH/8, WINDOWHEIGHT-SIZESIDES*2)

        pygame.display.update()
        mainClock.tick(FPS)

    pygame.display.update()
    mainClock.tick(FPS)
                


I made a snake

03 July 2013 - 02:34 PM

Hello!

I had a (very) little experience of programming with python from my classes and i decided to start making game. I did a crappy attempt at pong that i will post later because it has a lot of problem, and then i did this very simplistic snake, which i ask you to criticize without mercy. 

 

I went through the tutorial "Invent Your Own Computer Games With Python" and stop just before the part where he explains how to implement sound an images. I felt that i could already do many games and gain some experience with what i read. 

 

I plan to add a menu and the possiblility to start again a game after losing, also a victory message (when you have filled the entire screen) and a score. Also the possibility to chose the difficulty. 

I plan to first finish my pong and then work into adding theses into the snake. 

 

If you could point how i could improve my code it would be great. I especially think i could have used more function and i ant to know you opinion about what could be functionized. 

 

Thanks!

import pygame, sys, time, random
from pygame.locals import *

pygame.init()
mainClock = pygame.time.Clock()

WINDOWWIDTH = 480
WINDOWHEIGHT = 480
SPEED = 5

windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)

pygame.display.set_caption('Running_window')

basicFont = pygame.font.SysFont(None, 48)
headPosition = [240 , 240]
foodPos = [20 + random.randint(0, 19)*22, 20 + random.randint(0, 19)*22]
head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
tail = [pygame.Rect(headPosition[0] ,headPosition[1] ,10 ,10)]
tailPosition = [240, 240]
food = pygame.Rect(foodPos[0] + 5, foodPos[1] + 5, 10, 10)
square = [pygame.Rect(16, 16, 444, 2), pygame.Rect(16, 16, 2, 444), pygame.Rect(460, 16, 2, 444),  pygame.Rect(16, 460, 446, 2)]

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
position2 = []

updates = 0
seconds = 0
foodEaten = 0

moveUp = False
moveDown = False
moveLeft = False
moveRight = False
foodIsHere = False

lose = False



while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # events for changing the direction of the snake
            if moveRight: 
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_LEFT:
                    pygame.quit()
                    sys.exit()
            if moveLeft:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    pygame.quit()
                    sys.exit()
            if moveDown:
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP:
                    pygame.quit()
                    sys.exit()
            if moveUp:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_DOWN:
                    pygame.quit()
                    sys.quit()
            else:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    #eating of food

    if head.colliderect(food):
        foodEaten += 1
        foodIsHere = False
        while foodPos in tailPosition:
            foodPos = [20 + random.randint(0, 19)*22, 20 + random.randint(0, 19)*22]
        tail.append(head)
        tailPosition.append(headPosition)

    #apparitions of food
    if foodIsHere == False:
        food = pygame.Rect(foodPos[0] + 5, foodPos[1] + 5, 10, 10)
        foodIsHere = True

    #movement of the tail of the snake

    if tail != []:
        tail.reverse()
        tailPosition.reverse()
        tail.pop(0)
        tailPosition.pop(0)
        tail.append(pygame.Rect(headPosition[0] + 5,headPosition[1] + 5 ,10 ,10))
        tailPosition.append(headPosition)
        tail.reverse()
        tailPosition.reverse()     
                
    # movements of the head of the snake

    if moveRight and (not moveLeft):
        headPosition[0] += 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveLeft and (not moveRight):
        headPosition[0] -= 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveUp and (not moveDown):
        headPosition[1] -= 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveDown and (not moveUp):
        headPosition[1] += 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)

    #collision ith the tail

    for piece in tail[1:]:
        if head.colliderect(piece):
            lose = True

    # collision with the border of the screen
    for bord in square :
        if head.colliderect(bord):
            lose = True

    if lose == True:
        while lose:
            windowSurface.fill(BLACK)
            lost1 = basicFont.render('You lose.', True, WHITE, None)
            textRectLost1 = lost1.get_rect()
            textRectLost1.centerx = 240
            textRectLost1.centery = 180
            lost2 = basicFont.render('Press q to quit.', True, WHITE, None)
            textRectLost2 = lost2.get_rect()
            textRectLost2.centerx = 240
            textRectLost2.centery = 250
            windowSurface.blit(lost2, textRectLost2)
            windowSurface.blit(lost1, textRectLost1)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == KEYUP:
                    if event.key == ord('q'):
                        pygame.quit()
                        sys.exit()

    windowSurface.fill(BLACK)

    pygame.draw.rect(windowSurface, RED, food)
    pygame.draw.rect(windowSurface, BLUE, head)
    for piece in tail:
        pygame.draw.rect(windowSurface, GREEN, piece)
        
    pygame.draw.rect(windowSurface, WHITE, square[0])
    pygame.draw.rect(windowSurface, WHITE, square[1])
    pygame.draw.rect(windowSurface, WHITE, square[2])
    pygame.draw.rect(windowSurface, WHITE, square[3])    
    
    


    updates += 1
    pygame.display.update()
    mainClock.tick(SPEED)
                


PARTNERS