Python Forum
My code does not work as expected (pygame)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My code does not work as expected (pygame)
#1
Hello,
I am trying to make a game in pygame and after i optimised my code it stopped working.
It is creating a window but it is black .

Thank you for helping.

Here is my code:
import pygame
import sys
from pygame.constants import K_RIGHT

pygame.init()

screen_width = 800
screen_hight = 600

game_window = pygame.display.set_mode((screen_width, screen_hight))
pygame.display.set_caption("Window")

walkleft = (pygame.image.load("D:\python project\pygametest\idle.png"))
walkright = (pygame.image.load("D:\python project\pygametest\idleflip.png"))
idle = (pygame.image.load("D:\python project\pygametest\eidle.png"))
bg = (pygame.image.load("D:\python project\pygametest\ibg.png"))

clock = pygame.time.Clock()

class player (object):
    def __init__(self, x, y, screen_width, screen_hight):
        self.x=x
        self.y=y
        self.screen_width=screen_width
        self.screen_hight=screen_hight
        self.vel=5
        self.is_jump=False
        self.jumpcount=10
        self.left=False
        self.right=False
        self.walkcount=0

    def draw(self,game_window):
        if self.walkcount +1 >= 27:
            self.walkcount = 0
        
        if self.left:
            game_window.blit(walkleft,(self.x,self.y))
            self.walkcount += 1
        elif self.right:
            self.game_window.blit(walkright,(self.x,self.y))
            self.walkcount += 1
        else:
            game_window.blit(idle, (self.x,self.y))

def redrawwindow():
    global walkcount
    man.draw
    pygame.display.update()
    
#mainloop

man=player(300 ,400,64,64)

game_running = True

while game_running:
    clock.tick(27)
    
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and man.x > man.vel:
            man.x -= man.vel
            man.right = False
            man.left = True
    elif keys[pygame.K_RIGHT] and man.x < man.screen_width - man.vel:
            man.x += man.vel
            man.right = True
            man.left = False
    else:
        man.right = False
        man.left = False
        man.walkcount = 0

    if not (man.is_jump):
        if keys[pygame.K_SPACE]:
            man.is_jump = True
            man.right = False
            man.left = False
            man.walkcount = 0

    else:
        if man.jumpcount >= -10:
            neg = 1
            if man.jumpcount < 0:
                neg = -1
            man.y -=(man.jumpcount ** 2) / 4 * neg
            man.jumpcount -= 1

        else:
            man.is_jump= False
            man.jumpcount = 10

    redrawwindow()





pygame.quit()
sys.exit()
Reply
#2
This "man.draw" does not execute the player.draw() method. To do that you need "man.draw()".

What is this for?
    global walkcount
This is the only place walkcount is used in your code. Is this a leftover from before your optimization?

You should define your classes before you start the game code. You have a lot of code in the main loop that should be in the person class. I rearranged thing a bit and included some comments that you can use or ignore.
import pygame
import sys
from pygame.constants import K_RIGHT

# Try to define global variables at the top of module when possible.  Use uppercase 
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Class names should start with uppercase letter Player, not player
class player (object):
    def __init__(self, x, y, screen_width, screen_hight):
        self.x = x  # Spaces around =
        self.y=y
        self.left=False
        self.right=False
        self.walkcount=0
        self.screen_width=screen_width   # Lots of unused variables here
        self.screen_hight=screen_hight
        self.vel=5
        self.is_jump=False
        self.jumpcount=10
  
    def walk_right(self):
        '''Walk to the right'''
        # Walking code from main loop should be moved to methods in person.  person should
        # know how to walk.  Mainloop should only know if when to ask the person to walk or jump.

    def draw(self, game_window):  # game_window not used.
        if self.walkcount +1 >= 27:   # Seems arbitrary.  What does 27 mean?
            self.walkcount = 0
         
        if self.left:
            game_window.blit(walkleft,(self.x,self.y))
            self.walkcount += 1
        elif self.right:
            self.game_window.blit(walkright,(self.x,self.y))
            self.walkcount += 1
        else:
            game_window.blit(idle, (self.x,self.y))

         # Jumping code should be in here, not main loop
 
def redrawwindow():
    man.draw()  # No game_window not used in method.  Do we need to pass an arg or remove an arg?
    pygame.display.update()

# Put the initialization code together after class and function definitions
pygame.init() 
game_window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Window")
walkleft = (pygame.image.load("D:\python project\pygametest\idle.png"))
walkright = (pygame.image.load("D:\python project\pygametest\idleflip.png"))
idle = (pygame.image.load("D:\python project\pygametest\eidle.png"))
bg = (pygame.image.load("D:\python project\pygametest\ibg.png"))
clock = pygame.time.Clock()
man = player(300, 400, 64, 64)  # Why is the man's screen only 64x64?
 
#mainloop
game_running = True
while game_running:
    clock.tick(27)
     
    pygame.display.update()   # Calling update in redrawwindow.  Do we need it here too?
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False
 
    keys = pygame.key.get_pressed()
 
    if keys[pygame.K_LEFT] and man.x > man.vel:
            man.x -= man.vel   # Shouldn't this kind of code be in person?
            man.right = False
            man.left = True
    elif keys[pygame.K_RIGHT]:  # I would do this
        man.walk_right()  # make a method in person that knows how to walk to the right

    else:
        man.stop_walking()
 
    if not (man.is_jump):
        if keys[pygame.K_SPACE]:
            man.is_jump = True  # This code belongs in person, not here
            man.right = False
            man.left = False
            man.walkcount = 0
 
    else:
        if man.jumpcount >= -10:  # This also belongs in person, not here
            neg = 1
            if man.jumpcount < 0:
                neg = -1
            man.y -=(man.jumpcount ** 2) / 4 * neg
            man.jumpcount -= 1
 
        else:
            man.is_jump= False
            man.jumpcount = 10
 
    redrawwindow()

pygame.quit()
sys.exit()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  my simple code wont work! help! simon12323121 2 2,031 Sep-05-2021, 09:06 AM
Last Post: naughtyCat
  I wrote a code but it does not work out as expected chinitayao226 2 1,871 Sep-23-2020, 09:14 PM
Last Post: SnowwyWolf
  A program for backing up documents (doesnt work(code is inside)) Richard_SS 4 3,421 Jun-05-2019, 03:47 PM
Last Post: heiner55
  I Can't Get This Sorting Function In This LinkedList Code To Work JayJayOi 10 7,931 Jan-11-2018, 01:14 AM
Last Post: JayJayOi
  Need help with getting this voting eligiblity code to work Beastly 1 2,525 Aug-16-2017, 03:46 PM
Last Post: ichabod801
  Why can't this code work. sexualpanda 2 3,423 Feb-06-2017, 04:03 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020