pygame looping through a movement with a Class instance - python

I can't figure out how to loop through the jump function without having it in the first 'while True' block. None of the proposed alternatives have worked so far. Currently the only way I get it to work is having to press spacebar for each step of the jump.
import pygame
from pygame import Color
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.vy = 5
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
if self.isJump:
# using 'while' doesn't work either
if self.jumpCount >= -10:
# this doesn't work -> pygame.time.delay(100)
print(self.jumpCount)
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.jumpCount = 10
self.isJump = False
return self.isJump
def move(self):
return
def run():
bird = Bird()
while True:
pygame.time.delay(100)
# only works if I put 'bird.isJump = True, bird.jump()' here, and then it loops continuously
surface.fill(Color("blue"))
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.isJump = True
bird.jump()
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.flip()
run()

You could call the move method every time you run the game loop, along with draw, then call the jump method only once, when space is clicked.
The result will be (with a few other minor changes, such as calling pygame.init, quitting with quit instead of pygame.quit and removing redundant class members):
import pygame
from pygame import Color
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
self.jumpCount = 10
self.isJump = True
def move(self):
if self.isJump:
if self.jumpCount >= -10:
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.isJump = False
def run():
bird = Bird()
while True:
pygame.time.delay(100)
surface.fill(Color("blue"))
bird.move()
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.jump()
if event.type == pygame.QUIT:
quit()
pygame.display.flip()
pygame.init()
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
run()

Related

OOP Pygame platform game: controlling and moving a square on a screen

import pygame
import random
import math
import sys
screenWidth = 1200
screenHeight = 600
class Hero:
def __init__(self, pos):
self.pos = pos
self.width = 30
self.height = 30
self.color = (0, 0, 0)
self.dirX = 0
self.dirY = 0
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.dirX = 1
elif event.key == pygame.K_LEFT:
self.dirX = -1
def draw(self, display):
x = self.pos[0]
y = self.pos[1]
pygame.draw.rect(display, self.color, (x + self.dirX, y + self.dirY, self.width, self.height))
print(self.pos, self.dirX, self.dirY)
def jump(self):
pass
def die(self):
pass
class Enemy:
pass
class Background:
pass
class Obstacles:
pass
class Camera:
pass
def score():
pass
def create(w, h):
display = pygame.display.set_mode((w, h))
display.fill((255, 255, 255))
#create background
#create Obstacles
#create Hero
heroOne = Hero([150, 450])
heroOne.move()
heroOne.draw(display)
#create Enemy
pygame.display.update()
def main():
pygame.init()
clock = pygame.time.Clock()
running = True
while running:
clock.tick(300)
create(screenWidth, screenHeight)
main()
Hi, I am making an OOP Game using Pygame in which a square would be controlled by the user and move along a floor, jump over obstacles and other enemy squares.
The way I want it to work:
When I press K_LEFT, dirX = 1 it will add to the x-coordinate of the pos and hence the x-position of the square will be updated and the square will begin to slide towards the right. When I press dir = -1and square will move to the left.
The way it is working:
No
I think the problem is the pos of the main cube does not seem to update and the dirX updates from 0 to 1 and goes back to 0.
I guess changing the values of the variables under the __init__() function is done as I am doing it or perhaps it is completely wrong.
Is this any way to make my code work the way I am trying to do it or is it completely a wrong way and there is some other way?
I am learning OOP and python, any additional advice or links regarding the best practices, relating to this code, would be highly appreciated.
Thank you.
First of all you've to invoke move in the main application loop:
def main():
pygame.init()
display = pygame.display.set_mode((screenWidth, screenHeight))
clock = pygame.time.Clock()
heroOne = Hero([150, 450])
running = True
while running:
clock.tick(300)
display.fill((255, 255, 255))
heroOne.move()
heroOne.draw(display)
pygame.display.update()
You have to change the position of the player by self.dirX and self.dirY, in every frame:
class Hero:
# [...]
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.dirX = 1
elif event.key == pygame.K_LEFT:
self.dirX = -1
new_x = self.pos[0] + self.dirX
new_y = self.pos[1] + self.dirY
self.pos = [new_x , new_y]
def draw(self, display):
pygame.draw.rect(display, self.color, (*self.pos, self.width, self.height))
If you wan to move the rectangle, just when a key is pressed, then I recommend to use pygame.key.get_pressed rather than the KEYDOWN event:
class Hero:
# [...]
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.pos[0] -= 1
if keys[pygame.K_RIGHT]:
self.pos[0] += 1
if keys[pygame.K_UP]:
self.pos[1] -= 1
if keys[pygame.K_DOWN]:
self.pos[1] += 1
Complete code:
import pygame
import random
import math
import sys
screenWidth = 1200
screenHeight = 600
class Hero:
def __init__(self, pos):
self.pos = pos
self.width = 30
self.height = 30
self.color = (0, 0, 0)
self.dirX = 0
self.dirY = 0
def move(self, events):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.pos[0] -= 1
if keys[pygame.K_RIGHT]:
self.pos[0] += 1
if keys[pygame.K_UP]:
self.pos[1] -= 1
if keys[pygame.K_DOWN]:
self.pos[1] += 1
def draw(self, display):
pygame.draw.rect(display, self.color, (*self.pos, self.width, self.height))
def jump(self):
pass
def die(self):
pass
class Enemy:
pass
class Background:
pass
class Obstacles:
pass
class Camera:
pass
def score():
pass
def main():
pygame.init()
display = pygame.display.set_mode((screenWidth, screenHeight))
clock = pygame.time.Clock()
heroOne = Hero([150, 450])
running = True
while running:
clock.tick(300)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
heroOne.move(events)
display.fill((255, 255, 255))
heroOne.draw(display)
pygame.display.update()
main()
In your create function you are creating new instance of the Hero each time its being called.
Instead, init heroOne in the main, and pass it as an argument so you can use it:
def main():
pygame.init()
heroOne = Hero([150, 450])
clock = pygame.time.Clock()
running = True
while running:
clock.tick(30)
create(screenWidth, screenHeight, heroOne)
Also add increment in the move method:
self.dirX += 1
and:
self.dirX -= 1
Now the object will move by one on each keypress.
And if you want continuous movement you should put some flag, e.g. if it is True +=1 and "False" -=1 and key presses will change the flag state.

Pygame sprite won't show up

I started creating a new game in pygame. first I made the game window and background. I made to backgrounds(bg and fg). I was going to leave fg as it was and make the second backgound, bg, as a scrolling background when my character sprite moves. After that, I pasted in code from a previous pygame project that was just a simple sprite character that could walk and jump in front of a background. When I pasted it in, the window came up and only displayed my backgrounds and did not show my sprite character at all. It also did not throw any errors. what's happening? Is my sprite just hidden?
import pygame
from random import randint, choice
from pygame.locals import *
pygame.init()
#(pasted code start)-----------------------------------------------------------------------------
walkRight = [pygame.image.load('/Users/luke.redwine/Documents/Python/PyGame/Examples/Ben-Game/ben characters main/R %s.png' % frame) for frame in range(1, 9)]
walkLeft = [pygame.image.load('/Users/luke.redwine/Documents/Python/PyGame/Examples/Ben-Game/ben characters main/L %s.png' % frame) for frame in range(14, 21)]
#(pasted code end)-----------------------------------------------------------------------------
bg = pygame.image.load('/Users/luke.redwine/Documents/Python/PyGame/Llama game/Llama imaging/backgrounds concepts/Mountains/PPP_BG1.png')
fg = pygame.image.load('/Users/luke.redwine/Documents/Python/PyGame/Llama game/Llama imaging/backgrounds concepts/Mountains/PPP_fg1.png')
screen = pygame.display.set_mode((276, 216), HWSURFACE|DOUBLEBUF|RESIZABLE)
#(pasted code start)---------------------------------------------------------------------------
class player(object):
def __init__(self,x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.velocity = 15
self.isJump = False
self.jumpCount = 7
self.right = False
self.left = False
self.walkCount = 0
self.screen = screen
def draw(self, screen):
if self.walkCount + 1 >= 8:
self.walkCount = 0
if self.left:
self.screen.blit(walkLeft[self.walkCount//1], (self.x, self.y))
self.walkCount += 1
elif self.right:
self.screen.blit(walkRight[self.walkCount//1], (self.x, self.y))
self.walkCount += 1
else:
self.screen.blit(char, (self.x, self.y))
#(pasted code end)-----------------------------------------------------------------------------
pygame.display.set_caption("Game")
screen.blit(pygame.transform.scale(bg,(276, 216)),(0,0))
screen.blit(pygame.transform.scale(fg,(276, 216)),(0,0))
pygame.display.flip()
#while loop for screen resize, fulscreen:
while True:
pygame.event.pump()
event=pygame.event.wait()
if event.type==QUIT:
pygame.quit()
elif event.type==VIDEORESIZE:
screen=pygame.display.set_mode(event.dict['size'],HWSURFACE|DOUBLEBUF|RESIZABLE)
screen.blit(pygame.transform.scale(bg,event.dict['size']),(0,0))
screen.blit(pygame.transform.scale(fg,event.dict['size']),(0,0))
pygame.display.flip()
#(pasted code start)---------------------------------------------------------------------------
#drawing in sprite character
def redrawGamescreen():
ben.screen.blit(bg,(0,0))
ben.screen.blit(fg,(0,0))
ben.draw(ben.screen)
pygame.display.update()
ben = player(50, 279, 64, 64)
run = True
#main loop and character control
while run:
clock.tick(8)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and ben.x > ben.velocity:
ben.x -= ben.velocity
ben.left = True
ben.right = False
elif keys[pygame.K_RIGHT] and ben.x < 735 - ben.width - ben.velocity:
ben.x += ben.velocity
ben.right = True
ben.left = False
else:
ben.right = False
ben.left = False
ben.walkCount = 0
if not(ben.isJump):
if keys[pygame.K_SPACE]:
ben.isJump = True
ben.right = False
ben.left = False
else:
if ben.jumpCount >= -7:
neg = 1
if ben.jumpCount < 0:
neg = -1
ben.y -= (ben.jumpCount ** 2) * 0.5 * neg
ben.jumpCount -= 1
else:
ben.isJump = False
ben.jumpCount = 7
ben.velocity = 15
redrawGamescreen()
#(pasted code end)-----------------------------------------------------------------------------
pygame.quit()
I can't test it but if you better organize code then you should see that you run two while loop. In first loop you display only background. And you never ends first loop so it never run second loop which draws sprite on background. You should remove first loop.

How to make an object "jump" in pygame

I was trying to create something along the lines of mario, this is far from perfect I know. Anyways, while trying to make the "jumping" method I ran into an issue - The jumping doesn't work the way I intended it to work. Whenether I click the space bar my red square moves up and down randomly, I have to press the spacebar and hold it to complete a jump and even then its not perfect. Sometimes when I hold the space bar for too long the red square will continue to jump again. Is there any way to solve this issue? I'd be very thankful for any help, thanks.
import pygame, time, math, random, sys
from pygame.locals import *
background = pygame.image.load("assets/MarioBackground.png")
def events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
W, H = 640, 400
HW, HH = W / 2, H / 2
AREA = W * H
FPS = 60
bg_x = 0
isJump = False
jumpCount = 10
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((W,H))
pygame.display.set_caption("Mario")
class Mario():
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
pygame.draw.rect(screen, (255,0,0), (self.x, self.y, 40, 40))
def move(self):
global bg_x
if pressed_keys[K_RIGHT] and bg_x > -920:
if self.x > 490:
bg_x -= 5
else:
self.x += 5
if pressed_keys[K_LEFT] and self.x > 5:
self.x -= 5
def jump(self):
global jumpCount, isJump
if pressed_keys[K_SPACE]:
if jumpCount >= -10:
isJump = True
print(jumpCount)
neg = 1
if jumpCount < 0:
neg = -1
self.y -= (jumpCount ** 2) * 0.1 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
mario = Mario(50, 270)
while True:
clock.tick(FPS)
events()
pressed_keys = pygame.key.get_pressed()
screen.blit(background, (bg_x,0))
mario.move()
mario.draw()
mario.jump()
pygame.display.update()
Just check if isJump is true and then execute the jumping code in the jump method. I also recommend adding the isJump and jumpCount as attributes to Mario, so that you don't have to modify global variables.
To prevent the continuous jumping while Space is pressed, you have to handle the key press in the event queue. Then the jump action is triggered only once per key press not while the key is being held down.
import pygame, time, math, random, sys
from pygame.locals import *
background = pygame.Surface((640, 400))
background.fill((30, 90, 120))
W, H = 640, 400
HW, HH = W / 2, H / 2
AREA = W * H
FPS = 60
bg_x = 0
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((W,H))
class Mario():
def __init__(self, x, y):
self.x = x
self.y = y
# isJump and jumpCount should be attributes of Mario.
self.isJump = False
self.jumpCount = 10
def draw(self):
pygame.draw.rect(screen, (255,0,0), (self.x, self.y, 40, 40))
def move(self):
global bg_x
if pressed_keys[K_RIGHT] and bg_x > -920:
if self.x > 490:
bg_x -= 5
else:
self.x += 5
if pressed_keys[K_LEFT] and self.x > 5:
self.x -= 5
def jump(self):
# Check if mario is jumping and then execute the
# jumping code.
if self.isJump:
if self.jumpCount >= -10:
neg = 1
if self.jumpCount < 0:
neg = -1
self.y -= self.jumpCount**2 * 0.1 * neg
self.jumpCount -= 1
else:
self.isJump = False
self.jumpCount = 10
mario = Mario(50, 270)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# Start to jump by setting isJump to True.
mario.isJump = True
clock.tick(FPS)
pressed_keys = pygame.key.get_pressed()
screen.blit(background, (bg_x,0))
mario.move()
mario.draw()
mario.jump()
pygame.display.update()
You can fix it by implementing the following rules:
you can only begin a jump when you touch the floor
you start a jump by pressing the space bar (set a variable) and stop it, when you touch the floor
you start a jump on keydown (pygame.KEYDOWN) not if pressed.
Some code snippets:
Begin jump
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and self.y == 0:
isJump = True
End jump
if self.y == 0:
isJump = False
With this rules you can only jump, when you're on the floor. You don't need to hold the space bar and you won't jump a second time if you hold the space bar to long

Pygame, been having trouble with making a Menu screen

I have been have a lot of trouble with my summative project where you have to make a game in python using pygame. I am currently stuck with trying to make a menu screen for my game, the problem is I can't get my buttons to show up and after that how to change to my game map once they click start. I have been getting the type error "TypeError: button() takes from 6 to 7 positional arguments but 9 were given" if any of you could help that would mean a lot. thanks.
#army man man
import pygame
from pygame import *
from tkinter import *
import time
import random
win = pygame.display.set_mode((1280,720))
pygame.display.set_caption("Armymanman")
walkright = [pygame.image.load('walk1.png'),pygame.image.load('walk2.png'),pygame.image.load('walk3.png'),pygame.image.load('walk4.png'),pygame.image.load('walk5.png'),pygame.image.load('walk6.png'),pygame.image.load('walk7.png'),pygame.image.load('walk8.png'),pygame.image.load('walk9.png')]
walkleft = [pygame.image.load('walk1L.png'),pygame.image.load('walk2L.png'),pygame.image.load('walk3L.png'),pygame.image.load('walk4L.png'),pygame.image.load('walk5L.png'),pygame.image.load('walk6L.png'),pygame.image.load('walk7L.png'),pygame.image.load('walk8L.png'),pygame.image.load('walk9L.png')]
backg = pygame.image.load('pythonbg.png')
#resize char image
char = pygame.image.load('stand.png')
char = pygame.transform.scale(char,(64,64))
x=0
y=720
w=1280
h=720
black=(0,0,0)
red=(255,0,0)
blue=(0,0,255)
green=(0,255,0)
white=(255,255,255)
clock = pygame.time.Clock()
#plays music does not work?
#def playmusic():
pygame.init()
pygame.mixer.pre_init(22050, -16, 2, 2048) # setup mixer
pygame.mixer.init()
pygame.mixer.music.load('bgmusic.ogg')
pygame.mixer.music.play(-1)
#playmusic()
##song=pygame.mixer.sound('bgmusic.ogg')
##
##song.play()
class player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.move = 5
self.isjump = False
## self.isjump=0
self.jumpcount = 10
self.left = False
self.right = False
self.walkcount = 0
def draw(self,win):
if self.walkcount + 1 >=27:
self.walkcount = 0
if self.left:
win.blit(walkleft[self.walkcount//3], (self.x,self.y))
self.walkcount += 1
elif self.right:
win.blit(walkright[self.walkcount//3], (self.x,self.y))
self.walkcount += 1
else:
win.blit(char, (self.x,self.y))
def redrawwindow():
win.blit(backg, (0,0))
man.draw(win)
pygame.display.update()
startsc=pygame.image.load('armymanbg.jpg')
startsc=pygame.transform.scale(startsc,[1280,720])
win.blit(startsc,(0,0))
pygame.display.flip()
DIS=1
def button(x,y,w,h,ic,ac,action=None):
mouse=pygame.mouse.get_pos()
click= pygame.mouse.get_pressed()
if x+w>mouse[0] > x and y+h > mouse[1] > y:
global DIS
global intro
pygame.draw.rect(win,ac,(x,y,w,h))
if click[0] == 1 and action!= None:
if action=="START":
pygame.display.update()
time.sleep(0.5)
run= False
DIS=2
elif action=="EXIT":
pygame.quit()
quit()
elif action=="Menu":
DIS=1
else:
return True
else:
pygame.draw.rect(window, ic, (x,y,w,h))
text = pygame.font.SysFont('freesonsbold.ttf',25)
win.blit(text.render("BECOME THE ARMYMANMAN!", True,(black)), (x+(w/3.1), y+(h/2.5)))
win.blit(text.render("Start",True,(black)), (x+(w/3.1), y+(h/2.5)))
win.blit(text.render("Exit",True,(black)), (x+(w/3.1), y+(h/2.5)))
#MAIN LOOP
man = player(0, 656, 64, 64)
run = True
while run:
clock.tick(27)
if DIS==1:
for event in pygame.event.get():
if event.type==pygame.QUIT:
quit()
win.fill((0,0,0))
button("START",400, 500, 150, 75,green,blue,"START")
button("EXIT", 400,650,150,75,green,red,"EXIT" )
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if (event.type==pygame.KEYDOWN and event.key == K_RIGHT)and man.x < 1280 - man.width - man.move:
man.x += man.move
man.right = True
man.left = False
elif (event.type==pygame.KEYDOWN and event.key == K_LEFT)and man.x > man.move:
man.x -= man.move
man.left = True
man.right = False
else:
man.right= False
man.left = False
man.walkcount = 0
if (event.type==pygame.KEYDOWN and event.key == K_SPACE):
man.isjump = True
man.right = False
man.left = False
man.walkcount = 0
else:
if(man.isjump==True):
if man.jumpcount >= -10:
neg = 1
if man.jumpcount < 0:
neg = -1
man.y -= (man.jumpcount ** 2) *0.5 * neg
man.jumpcount -= 1
else:
man.isjump = False
man.jumpcount = 10
redrawwindow()
print(man.y)
pygame.quit
For starters, you really shouldn't do from pygame import *, as it will pollute your namespace with lots of stuff you don't want, from pygame.locals import * is more normal. The TypeError you mention is due to you giving button() too many parameters. You can see that it takes six or seven parameters when you define it (def button(x,y,w,h,ic,ac,action=None):). When you call it you try to pass too many (button("START",400, 500, 150, 75,green,blue,"START")). I think the initial "START" parameter is the excess. Here are some other things I've noticed:
if(man.isjump==True): can be replaced with if man.isjump:. There seem to be lots of similar excess brackets. You do not need them around comparisons unless it's something like if x and (a or b), where it makes a difference. You also do not need them around most function parameters. This button-drawing lines with (black) are an example of this.
The final pygame.quit is unnecessary and will not work anyway (if you needed it, which you don't, it would be pygame.quit().
All of your buttons are drawn in the same place; try changing the draw coordinates to be different
Your whitespace is strange. As a general rule, do not have trailing whitespace at the end of lines or a gap of more than two blank lines.
In this line (pygame.draw.rect(window, ic, (x,y,w,h))), you draw to window instead of win, which breaks it.
The whole section of code after the huge whitespace glob (excluding pygame.quit, which should be removed) needs to be indented.
if (event.type==pygame.KEYDOWN and event.key == K_RIGHT) can be replaced with if pygame.key.get_pressed()[K_RIGHT] and similar for left. These, along with redrawwindow() should be outside of the for event in pygame.event.get(): loop.

How to move a rectangle in python using pygame in this code?

I want to move a rectangle with the arrow keys, so far I only can draw the rectangle but I don't get the keyhandler to work.
I'm a newbie in python and pygame.
This is my main.py:
import pygame
import time
import random
from Player import *
# Initialize Pygame
pygame.init()
game_over = False
# Color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (192, 192, 192)
# Setting up the window
surfaceWidth = 800
surfaceHeight = 500
surface = pygame.display.set_mode((surfaceWidth, surfaceHeight))
pygame.display.set_caption("Rectangle Runner")
clock = pygame.time.Clock()
#Player(surface, surface_height, surface_width, size, jump_height, color)
player = Player(surface, surfaceHeight, surfaceWidth, 50, 200, BLACK)
# Game Loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if game_over == True:
pygame.quit()
quit()
surface.fill(GRAY)
#Player.draw()
player.keyHandling()
player.checkBoundaries()
player.draw()
#Obstacle.draw()
pygame.display.update()
clock.tick(60)
# This code shall be unreachable
pygame.quit()
quit()
This is the Player.py:
import pygame
class Player:
def __init__(self, surface, surface_height, surface_width, size, jump_height, color):
self.surface = surface
self.surface_height = surface_height
self.surface_width = surface_width
self.size = size
self.jump_height = jump_height
self.color = color
self.x = (0 + (self.surface_width/10))
self.y = self.surface_height - self.size
self.x_move = 0
self.y_move = 0
self.rect = pygame.draw.rect(self.surface, self.color, [self.x, self.y, self.size, self.size])
def keyHandling(self):
# Draw the player
#pygame.draw.rect(self.surface, self.color,
#[self.x, self.y, self.size, self.size])
# KeyListener
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.y_move = -10
#self.y += self.y_move
#self.rect.move_ip(0, -10)
if event.key == pygame.K_LEFT:
self.x_move = -5
#self.x += self.x_move
#self.rect.move_ip(-5, 0)
if event.key == pygame.K_RIGHT:
self.x_move = 5
#self.x += self.x_move
#self.rect.move_ip(5, 0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
self.y_move = 0
#self.y += self.y_move
#self.rect.move_ip(0, 10)
if event.key == pygame.K_LEFT:
self.x_move = 0
if event.key == pygame.K_RIGHT:
self.x_move = 0
self.x += self.x_move
self.y += self.y_move
def checkBoundaries(self):
# Checking for Boundaries
#if self.y <= self.jump_height:
# self.y_move = -10
if self.y > self.surface_height - self.size:
self.y_move = 0
if self.y <= self.jump_height + self.size:
self.y_move = -10
def draw(self):
pygame.draw.rect(self.surface, self.color, [self.x, self.y, self.size, self.size])
#pygame.draw.rect(self.surface, self.color,[self.x, self.y, self.size, self.size])
I need help. I'm thinking thru this the whole day.
Thanks in advance :D
The problem in your code is that pygame.event.get() is a generator. Each item that is obtained from it can ONLY be obtained once. Hence, each time the clock ticks, you are grabbing everything within the events generator and they are all destroyed. Next, when the Player object iterates over pygame.event.get, it does nothing, as the generator was already made empty. See this about generators.
What you need to do is catch the KEYDOWN event in the main.py module and then pass key information onto the Player object.
Replace the main loop in main.py with the following:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
player.keyDown(event.key)
if game_over == True:
pygame.quit()
quit()
surface.fill(GRAY)
player.checkBoundaries()
player.draw()
pygame.display.update()
clock.tick(60)
Remove the keyHandling method from Player.py and replace with the following method:
def keyDown(self, key):
if key == pygame.K_w:
self.y -= 10
elif key == pygame.K_a:
self.x -= 10
elif key == pygame.K_d:
self.x += 10
This now removes the issue with the generator.
Full code

Categories