Bug in pygame when collidereacting - python

I can't collide rect whit rectangles, should I give up or try using x and y positions?
I don't get any errors from it but it closes right after i run it.
can you please suggest me what to do.
import pygame,sys,time,random
pygame.init()
x = 425
y = 750
player_x = x/2-25
player_y = 600
player_speed = 0
timer = 0
score = 0
screen = pygame.display.set_mode((x,y))
clock = pygame.time.Clock()
enemy_x = random.randint(0,425)
enemy_y = -(random.randint(0,500))
enemy2_x = random.randint(0,425)
enemy2_y = -(random.randint(0,500))
police_x = random.randint(0,425)
police_y = random.randint(750,1400)
police2_x = random.randint(0,425)
police2_y = random.randint(750,1400)
enemy_speed = 16
police_speed = 3
font = pygame.font.SysFont("comicsansms",50)
player = pygame.image.load("macchina.png").convert_alpha()
pygame.display.set_caption("NapoliSimulator (schiva le buche e non farti prendere dalla pula)")
def player_a():
global player_x,player_y,player_speed
player_x+=player_speed
player = pygame.image.load("macchina.png").convert_alpha()
screen.blit(player,(player_x,player_y))
def enemy_a():
global enemy_x,enemy_y,enemy_speed,enemy2_x,enemy2_y,enemy3_x,enemy3_y,enemy4_x,enemy4_y,enemy5_x,enemy5_y
enemy_y += enemy_speed
enemy2_y += enemy_speed
enemy = pygame.image.load("crepa.png").convert_alpha()
enemy_2 = pygame.image.load("crepa.png").convert_alpha()
screen.blit(enemy,(enemy_x,enemy_y))
screen.blit(enemy,(enemy2_x,enemy2_y))
def enemy_b():
global police_x,police_y,police_speed,police2_x,police2_y
police_y -= police_speed
police = pygame.image.load("polizia.png").convert_alpha()
screen.blit(police,(police_x,police_y))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_speed -= 5
if event.key == pygame.K_d:
player_speed += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player_speed += 5
if event.key == pygame.K_d:
player_speed -= 5
screen.fill((200,200,200))
player_a()
if enemy_y >= 700:
enemy_y = -(random.randint(500,1200))
enemy_x = random.randint(0,425)
score += 1
if enemy2_y >= 700:
enemy2_y = -(random.randint(0,750))
enemy2_x = random.randint(0,425)
score += 1
if police_y <= 40:
police_y = random.randint(750,1900)
police_x = random.randint(0,425)
score += 1
enemy_a()
if score >= 7:
enemy_b()
if score >= 15:
police_speed += 0.0001
enemy = pygame.image.load("crepa.png").convert_alpha()
enemy_2 = pygame.image.load("crepa.png").convert_alpha()
police = pygame.image.load("polizia.png").convert_alpha()
playerr = player.get_rect()
enemyr = enemy.get_rect()
policer = police.get_rect()
enemyr2 = enemy_2.get_rect()
if enemyr.colliderect(playerr):
pygame.quit()
sys.exit()
if enemyr2.colliderect(playerr):
pygame.quit()
sys.exit()
if crepar.colliderect(policer):
enemy_b()
if player.colliderect(policer):
pygame.quit()
ys.exit()
pygame.display.flip()
clock.tick(60)

pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. The position of the rectangle can be specified by a keyword argument. For example, the top left of the rectangle can be specified with the keyword argument topleft:
playerr = player.get_rect(topleft = (player_x, player_y))
enemyr = enemy.get_rect(topleft = (enemy_x, enemy_y))
policer = police.get_rect(topleft = (police_x, police_y))
enemyr2 = enemy_2.get_rect(topleft = (enemy2_x, enemy2_y))
if enemyr.colliderect(playerr):
pygame.quit()
sys.exit()
if enemyr2.colliderect(playerr):
pygame.quit()
sys.exit()
if player.colliderect(policer):
pygame.quit()
sys.exit()

Related

Is there a way to make the box like go towards the x which the player is going and also being able to change direction if the player jumps over it

import pygame
from sys import exit
import random
pygame.init()
WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My game!")
fps = pygame.time.Clock()
active = True
score = 0
startedplus = False
startedminus = False
test_font = pygame.font.Font("letters.ttf", 50)
text_surface = test_font.render((f"Score: {score}") , False, (64,64,64))
text_rect = text_surface.get_rect(center = (400,50))
#game over
game_over = pygame.image.load("game_over.png").convert()
#Heart
heart = pygame.image.load("heart.png").convert_alpha()
heart = pygame.transform.rotozoom(heart,0,0.6)
#Box
box = pygame.image.load("box.png").convert_alpha()
box = pygame.transform.rotozoom(box,0,0.3)
box_rect = box.get_rect(midbottom = (100,305))
#Background och Ground
background = pygame.image.load("sky.png").convert()
ground = pygame.image.load("ground.png").convert()
#player PNG
player = pygame.image.load("player.png").convert_alpha()
player = pygame.transform.rotozoom(player,0,2.5)
player_rect = player.get_rect(midbottom = (400,325))
#pickaxe PNG
pickaxe = pygame.image.load("pickaxe.png").convert_alpha()
pickaxe = pygame.transform.rotozoom(pickaxe,0,3.5)
pickaxe_rect = pickaxe.get_rect(center = (400,325))
#Gravity
player_gravity = 0
pickaxe_gravity = 0
adding = 0.01
hearts = 4
collided_in_the_last_frame = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if active:
if event.type == pygame.MOUSEBUTTONDOWN:
if player_rect.collidepoint(event.pos) and player_rect.bottom >= 325:
player_gravity = -20
pickaxe_gravity = -20
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
player_rect.x -= 40
pickaxe_rect.x -= 40
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
player_rect.x += 40
pickaxe_rect.x += 40
if (event.key == pygame.K_SPACE or event.key == pygame.K_w or event.key == pygame.K_UP) and player_rect.bottom >= 325:
player_gravity = -20
pickaxe_gravity = -20
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_x:
box_x = random.randint(10, 800)
box_rect = box.get_rect(midbottom = (box_x,305))
hearts = 4
active = True
if active:
collides = player_rect.colliderect(box_rect)
if collides and not collided_in_the_last_frame:
hearts -= 1
collided_in_the_last_frame = collides
screen.blit(background,(0,0))
screen.blit(ground,(0,300))
if player_rect.colliderect(box_rect):
box_x = random.randint(10, 800)
box_rect = box.get_rect(midbottom = (box_x,305))
adding = adding + 0.001
if player_rect.x <= 400:
box_rect.x += (1 + adding)
elif player_rect.x >= 400:
box_rect.x -= (1 + adding)
if hearts == 0:
active = False
elif hearts == 1:
screen.blit(heart, (35,35))
elif hearts == 2:
screen.blit(heart, (35,35))
screen.blit(heart, (65,35))
elif hearts == 3:
screen.blit(heart, (35,35))
screen.blit(heart, (65,35))
screen.blit(heart, (95,35))
else:
screen.blit(heart, (35,35))
screen.blit(heart, (65,35))
screen.blit(heart, (95,35))
screen.blit(heart, (125,35))
screen.blit(box, box_rect)
screen.blit(pickaxe, pickaxe_rect)
screen.blit(player,player_rect)
screen.blit(text_surface, text_rect)
player_gravity += 1
pickaxe_gravity += 1
player_rect.y += player_gravity
pickaxe_rect.y += pickaxe_gravity
if pickaxe_rect.bottom >= 325: pickaxe_rect.bottom = 325
if player_rect.bottom >= 325: player_rect.bottom = 325
if player_rect.x <= -10 and pickaxe_rect.x <= -10:
player_rect.x = -10
pickaxe_rect.x = player_rect.x - 70
mouse_pos = pygame.mouse.get_pos()
if player_rect.collidepoint(mouse_pos):
player_gravity = -20
pickaxe_gravity = -20
player_rect.y += player_gravity
pickaxe_rect.y += pickaxe_gravity
if pickaxe_rect.bottom >= 325: pickaxe_rect.bottom = 325
if player_rect.bottom >= 325: player_rect.bottom = 325
else:
screen.blit(game_over, (0,0))
pygame.display.update()
fps.tick(60)
How can I make the box like follow the player. I want it like when the player is "right" of the box then the box will start going right and when the player is "left" of the box the box will start going left.
I tried many ways but none worked so in the end I was left with this:
adding = adding + 0.001
if player_rect.x <= 400:
box_rect.x += (1 + adding)
elif player_rect.x >= 400:
box_rect.x -= (1 + adding)
And I thought it would work but it didnt.
You have to compare the position of the box with the position of the player. e.g.:
if box_rect.right < player_rect.left:
box_rect.x += 1
elif box_rect.left > player_rect.right:
box_rect.x -= 1
Also not, that pygame.Rect is supposed to represent an area on the screen, therfore a pygame.Rect object can only store integral data.
The coordinates for Rect objects are all integers. [...]
The fractional part of the coordinates is lost when a floating point value is added to a coordinate of a pygame.Rect object. Therefore box_rect.x += (1 + adding) always adds 1 to and box_rect.x -= (1 + adding) always subtracts 2 (as long 0 < a <= 1).
Also see Pygame doesn't let me use float for rect.move, but I need it

How to add a boundary on areas inside the screen in pygame

I've been trying to create a game screen but I can't seem to add a boundary around the houses on the screen so that the player doesn't walk over them. Below is my code
import pygame
import sys
from pygame import mixer
pygame.init()
playerImg = pygame.image.load('player.png')
WalkFront = [pygame.image.load('B1.png'), pygame.image.load('B2.png'),pygame.image.load('B3.png'),
pygame.image.load('B4.png')]
WalkBack = [pygame.image.load('F1.png'), pygame.image.load('F2.png'), pygame.image.load('F3.png'),
pygame.image.load('F4.png')]
WalkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
pygame.image.load('R4.png')]
WalkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
pygame.image.load('L4.png')]
walkcount = 0
clock = pygame.time.Clock()
scr = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Pokemon: Red')
logo = pygame.image.load('logo.png')
pygame.display.set_icon(logo)
background = pygame.image.load('BG.png')
pallet = pygame.image.load('pallet town.png')
mixer.music.load('Start menu.mp3')
mixer.music.play(100, 0, 0)
playerX = 200
playerY = 200
up = False
down = False
left = False
right = False
def redrawgamewindow():
global walkcount
scr.fill((0, 0, 0))
scr.blit(pallet, (60, 0))
if walkcount + 1 >= 29:
walkcount = 0
if up:
scr.blit(WalkFront[walkcount // 7], (playerX, playerY))
walkcount += 1
elif down:
scr.blit(WalkBack[walkcount // 7], (playerX, playerY))
walkcount += 1
elif left:
scr.blit(WalkLeft[walkcount // 7], (playerX, playerY))
walkcount += 1
elif right:
scr.blit(WalkRight[walkcount // 7], (playerX, playerY))
walkcount += 1
else:
player(playerX, playerY)
pygame.display.update()
def player(x, y):
scr.blit(playerImg, (x, y))
def start_menu():
while True:
scr.fill((255, 255, 255))
scr.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
game()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
pygame.display.update()
def game():
global playerX
global playerY
clock.tick(12)
mixer.music.pause()
mixer.music.load('pallet_music.mp3')
mixer.music.play(100)
playerX_change = 0
playerY_change = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
global up
global down
global left
global right
up = True
down = False
playerY_change = -0.8
elif event.key == pygame.K_DOWN:
up = False
down = True
playerY_change = 0.8
else:
up = False
down = False
walkcount = 0
if event.key == pygame.K_LEFT:
playerX_change = -1
left = True
right = False
elif event.key == pygame.K_RIGHT:
playerX_change = 1
right = True
left = False
else:
left = False
right = False
walkcount = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
up = False
down = False
left = False
right = False
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
up = False
down = False
left = False
right = False
playerX += playerX_change
playerY += playerY_change
if playerX <= 90:
playerX = 90
elif playerX >= 670:
playerX = 670
if playerY <= 40:
playerY = 40
elif playerY >= 540:
playerY = 540
redrawgamewindow()
start_menu()
the background image has an area on it with a house in the top left. See the background image below so you can get a better idea. what I want is for the player to not be able to walk on the house so he gets blocked at the edge.
I recommend to define a rectangular area for the house. Use pygame.Rect. You have to find the values for hx, hy, hw and hh:
house_rect = pygame.Rect(hx, hy, hw, hh)
Create a rectangle for the player after the position of the player is changed. The size of the rectangle can be get from the pygame.Surface object which represents the player by get_rect(). The position has to be set by an keyword argument (topleft = (playerX, playerY)).
Use pygame.Rect.colliderect to evaluate if the player collides with the house and restrict the position of the player to the area outside the house:
playerX += playerX_change
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
if player_rect.colliderect(house_rect):
if playerX_change > 0:
player_rect.right = house_rect.left
elif playerX_change < 0:
player_rect.left = house_rect.right
playerX = player_rect.x
playerY += playerY_change
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
if player_rect.colliderect(house_rect):
if playerY_change < 0:
player_rect.top = house_rect.bottom
elif playerY_change > 0:
player_rect.bottom = house_rect.top
playerY = player_rect.y
I guess you have to patiently make the boundaries with x and y like this:
if x > boundaryX and y > boundaryY:
xOfThePlayer -= moving
It is an example you have to change this according to your needs.

Pointer not moving up or down despite using earlier and already working code

been trying for a while to find the problem with the following code. I'm trying to have the pointer move up and down like the title of the question states but it just won't move. Any and all help is welcome.
Code for Pause Screen event processing:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_w:
self.pointer.moveUp()
print("Up we go")
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
self.pointer.moveDown()
print("Down we go")
if event.key == pygame.K_RETURN:
self.selection = int(pointer.Pointer.getPosition(self.pointer))
print(str(pointer.Pointer.getPosition(self.pointer)))
return True
return False
Code for displaying which shows the pointer in the same place.
self.active_sprite_list.draw(screen)
font = pygame.font.SysFont("serif", 25)
text = []
center_x = []
center_y = []
for counter in range(1,5):
text.append(font.render(self.options[counter-1], True, constants.WHITE))
center_x.append(150)
center_y.append((counter * 120) - (text[counter-1].get_height() // 2) + (self.pointer.image.get_height() // 2))
screen.blit(text[counter-1], [center_x[counter-1],center_y[counter-1]])
pygame.display.flip()
And for reference the same code in the Menu which has the pointer moving up and down:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_w:
self.pointer.moveUp()
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
self.pointer.moveDown()
if event.key == pygame.K_RETURN:
self.selection = int(pointer.Pointer.getPosition(self.pointer))
#print(str(self.selection))
return True
###Some code later###
screen.fill(constants.BLACK)
font = pygame.font.SysFont("serif", 25)
for counter in range(1,5):
text = font.render(self.options[counter-1], True, constants.WHITE)
center_x = 150
center_y = (counter * 120) - (text.get_height() // 2) + (self.pointer.image.get_height() // 2)
screen.blit(text, [center_x, center_y])
self.active_sprite_list.draw(screen)
pygame.display.flip()
And before you suggest, the screen for the pause has been declared before here:
while notPaused == False:
#print("Received")
notPaused = pause.processEvents()
print(str(notPaused))
if firstTime == True:
self.pauseScreen.fill(constants.ABLACK)
pause.displayFrame(self.pauseScreen)
self.pauseScreen.set_alpha(128)
screen.blit(self.pauseScreen, [0,0])
firstTime = False
pause.displayFrame(self.pauseScreen)
clock.tick(60)
As per requested, here is the MoveUp and MoveDown functions in the Pointer Class:
def moveUp(self):
if self.rect.y <= 120:
self.rect.y = 480
else:
self.rect.y -= 120
def moveDown(self):
if self.rect.y >= 480:
self.rect.y = 120
else:
self.rect.y += 120
And as suggested, the modular/self-contained code that can be run on its own as long as you have some kind of image in a Resources Folder next to the saved code file.
import pygame, sys
"""
Global constants
"""
# Colors
ABLACK = ( 0, 0, 0, 125)
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
YELLOW = ( 255, 255, 0)
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Pointer(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Resources/Pointer.png")
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 120
def moveUp(self):
if self.rect.y <= 120:
self.rect.y = 480
else:
self.rect.y -= 120
print("Within pointer object moving up from ",self.rect.x,self.rect.y)
def moveDown(self):
if self.rect.y >= 480:
self.rect.y = 120
else:
self.rect.y += 120
print("Within pointer object moving up from ",self.rect.x,self.rect.y)
def getPosition(self):
self.position = self.rect.y / 120
return self.position
class Pause(object):
def __init__(self,screen):
self.selection = 4
self.options = ["Resume Game","Review Controls","Back to Menu","Quit"]
self.active_sprite_list = pygame.sprite.Group()
self.pointer = Pointer()
self.active_sprite_list.add(self.pointer)
def processEvents(self):
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_w:
self.pointer.moveUp()
print("Up we go")
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
self.pointer.moveDown()
print("Down we go")
if event.key == pygame.K_RETURN:
self.selection = int(Pointer.getPosition(self.pointer))
print(str(Pointer.getPosition(self.pointer)))
return False
return True
def displayFrame(self,screen):
self.active_sprite_list.draw(screen)
for pointer in self.active_sprite_list:
print("The y value of this pointer is:" + str(pointer.rect.y))
font = pygame.font.SysFont("serif", 25)
text = []
center_x = []
center_y = []
for counter in range(1,5):
text.append(font.render(self.options[counter-1], True, WHITE))
center_x.append(150)
center_y.append((counter * 120) - (text[counter-1].get_height() // 2) + (self.pointer.image.get_height() // 2))
for pointer in self.active_sprite_list:
print("The y value of this pointer is:" + str(pointer.rect.y))
screen.blit(text[counter-1], [center_x[counter-1],center_y[counter-1]])
for pointer in self.active_sprite_list:
print("The y value of this pointer is:" + str(pointer.rect.y))
pygame.display.flip()
pygame.init()
pygame.display.set_caption("Pause Error Finder")
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
Paused = True
clock = pygame.time.Clock()
pauseScreen = pygame.Surface(size,pygame.SRCALPHA,32)
pauseScreen.fill(ABLACK)
pause = Pause(screen)
pauseScreen.set_alpha(128)
Paused = pause.processEvents()
print(str(notPaused))
pause.displayFrame(pauseScreen)
screen.blit(pauseScreen, [0,0])
while Paused:
notPaused = pause.processEvents()
print(str(Paused))
pause.displayFrame(pauseScreen)
#screen.blit(pauseScreen, [0,0])
clock.tick(60)
Your issue is in the main game loop, first off, you had the blitting of Pause Screen to Screen commented out. readding that in gave the pointer seeming to multiply and go all over the place (getting closer!).
The reason it does that is you did not update your pauseScreen in each pass of the loop. Your displayFrame will add your pointer to the proper location, but the one from last frame, and 2 frames ago, and... are still there. by moving the lines
pauseScreen.fill(ABLACK)
pauseScreen.set_alpha(128)
And placing them within your game loop, the pause screen is reset ever frame and only the latest pointer is displayed. Here is the updated game loop:
pygame.init()
pygame.display.set_caption("Pause Error Finder")
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
notPaused = False
clock = pygame.time.Clock()
pauseScreen = pygame.Surface(size,pygame.SRCALPHA,32)
pause = Pause(screen)
notPaused = pause.processEvents()
print(str(notPaused))
pause.displayFrame(pauseScreen)
screen.blit(pauseScreen, [0,0])
while not notPaused:
notPaused = pause.processEvents()
print(str(notPaused))
pauseScreen.fill(ABLACK)
pauseScreen.set_alpha(128)
pause.displayFrame(pauseScreen)
screen.blit(pauseScreen, [0,0])
clock.tick(60)

Having Trouble with Python Classes

So I am making a simple "Dodge the Meteor Game" with Python 27 and Pygame. So everything ran smoothly, until I wanted to make classes, so I could make multiple meteors without retyping the same code. After I did this, when I run it, it stops responding with no error message. Here is my code:
import pygame
from pygame.locals import *
import sys
import random
pygame.init()
width,height = 800,600
gameDisplay = pygame.display.set_mode((width,height))
pygame.display.set_caption("Fifteen Minute Game ")
gameStart = False
bg = pygame.image.load("C:\Users\DEREK\Desktop\Python\\space.jpg")
bg = pygame.transform.scale(bg,(900,600))
x = 300
y = 300
move_x = 0
move_y = 0
playerspeed = 3
pellet_x = random.randint(0,800)
pellet_y = random.randint(0,550)
player = pygame.draw.rect( gameDisplay, (255,255,255), (x,y,30,30) )
pellet = pygame.draw.rect( gameDisplay, (255,255,255), (pellet_x,pellet_y,15,15) )
count = 0
#Functions
def pelletxy():
global pellet_x, pellet_y
pellet_x = random.randint(0,770)
pellet_y = random.randint(0,570)
def collision(rect1,rect2):
global player, count, pellet
if rect1.colliderect(rect2):
if rect2 == pellet:
pelletxy()
count +=1
class Meteor():
def __init__(self):
self.meteor_x = random.randint(0,800)
self.meteor_y = 0
self.meteorfall = 3
self.meteor = pygame.draw.rect( gameDisplay, (255,255,255), (self.meteor_x,self.meteor_y,35,35) )
def collision(self,rect1,rect2):
if rect1.colliderect(rect2):
if rect2 == self.meteor:
print "Good Game"
print "MUA HAHAHAHA"
print ""
print "Your score:" + str(count)
pygame.quit()
sys.exit()
def meteorxy(self):
self.meteor_x = random.randint(0,800)
self.meteor_y = 0
def render(self):
self.meteor_y += self.meteorfall
self.meteor
if meteor_y > 600:
meteorxy()
m1 = Meteor()
#Game Loop
while gameStart:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Keyboard Movement
if event.type == pygame.KEYDOWN:
if event.key == K_UP:
move_y -= playerspeed
if event.key == K_DOWN:
move_y += playerspeed
if event.key == K_LEFT:
move_x -= playerspeed
if event.key == K_RIGHT:
move_x += playerspeed
if event.type == pygame.KEYUP:
if event.key == K_UP:
move_y = 0
if event.key == K_DOWN:
move_y = 0
if event.key == K_LEFT:
move_x = 0
if event.key == K_RIGHT:
move_x = 0
#Calculate new position
x = x + move_x
y = y + move_y
#Stop Movement on boundaries
if x > 830:
x = -30
elif x < -30:
x = 830
elif y < -30:
y = 630
elif y > 630:
y = -30
#Check Different Collision Scenarios
collision(player, pellet)
m1.collision(player, m1.meteor)
#Draw the things onto the screen
gameDisplay.blit(bg,(0,0))
player = pygame.draw.rect( gameDisplay, (255,255,255), (x,y,30,30) )
pellet_outline = pygame.draw.rect( gameDisplay, (255,255,255), ((pellet_x - 1), (pellet_y - 1), 17,17))
pellet = pygame.draw.rect( gameDisplay, (0,0,255), (pellet_x,pellet_y,15,15) )
m1.render
pygame.display.update()
I don't know what I'm doing wrong, but I know it is with the classes. Thanks in advance
Hobby Programmer, Derek
Well, it's probably because gameStart is always False. So you're never getting into the game loop.
You should get to know debugging. You can use pdb or any IDE like Eclipse. The important thing is that it can help you understand what code is being running.
if event.key == K_RIGHT:
move_x = 0
#Calculate new position
x = x + move_x
y = y + move_y
See how the indentation changes? In Python, indentation is very important. Because all of your code after the line 'move_x = 0' is not indented adequately, it is not part of your while loop; therefore, it does not get executed in the loop. Fix your indentation.

Pygame Screen Collision Troubles, Player Moves Off Screen

I've looked around alot for code to implement screen collision but I can't find any that I know how to adapt to my own code, so I just need some help figuring out how to make my player not go through the screen.
import pygame
import random
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('proto')
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
divider = pygame.image.load('divider.png')
spikeImg = pygame.image.load('spikey.png')
player = pygame.image.load('player.png')
bg = pygame.image.load('Backgroundlvl1.png')
attack = ['player.png', 'playerattack.png']
dead = False
images = ['player.png', 'playerwalk.png']
cat = pygame.image.load('catenemy.png')
playerX = 158
playerY = 400
walk1 = ['playerwalkright.png', 'faceright.png']
attack1 = ['playerattack1.png', 'faceright.png']
divider = pygame.image.load('divider.png')
YBuffer = 600 - 16
counter = 0
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
############################
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
player = pygame.image.load(images[counter])
counter = (counter + 1) % len(images)
playerX = playerX + -5
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
player = pygame.image.load(walk1[counter])
counter = (counter + 9) % len(walk1)
playerX = playerX + 5
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
player = pygame.image.load(images[counter])
counter = (counter + 1) % len(images)
playerY = playerY + -25
if event.type == pygame.KEYUP and event.key == pygame.K_UP:
player = pygame.image.load(images[counter])
counter = (counter + 1) % len(images)
playerY = playerY + 25
if event.type == pygame.KEYDOWN and event.key == pygame.K_z:
player = pygame.image.load(attack[counter])
counter = (counter + 1) % len(attack)
if event.type == pygame.KEYDOWN and event.key == pygame.K_x:
player = pygame.image.load(attack1[counter])
counter = (counter + 1) % len(attack1)
##
gameDisplay.fill(black)
gameDisplay.blit(bg, (0,0))
gameDisplay.blit(player, (playerX, playerY))
gameDisplay.blit(cat, (636, 450))
pygame.display.flip()
clock.tick(60)
pygame.quit()
quit()
if playerX > display_width:
playerX = display_width
elif playerX < 0:
playerX = 0
This will prevent the player from going off the screen on the left and right.

Categories