While doing some test in python, one of the sprites in a Player class randomly started duplicating itself.. I can't figure it out.. (I realize it's probally something really simple)
Here's the code:
import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
health = 10
keys = {"w":False, "a":False, "s":False, "d":False, " ":False}
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, direction, distance):
if direction == "UP":
self.position[1] -= distance
elif direction == "DOWN":
self.position[1] += distance
elif direction == "RIGHT":
self.position[0] += distance
elif direction == "LEFT":
self.position[0] -= distance
class Enemy:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [15, 110]
def draw(self, screen):
screen.blit(self.texture, tuple([int(e) for e in self.position]))
def move(self, distance):
if player.direction == "UP":
self.position[1] -= distance
elif player.direction == "DOWN":
self.position[0] -= distance
elif player.direction == "RIGHT":
self.position[1] += distance
elif player.direction == "LEFT":
self.position[1] += distance
done = False
black = (0, 0, 0)
player = Thing("2.png")
enemy = Enemy("1.png")
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_w:
keys["w"] = True
if event.key == K_a:
keys["a"] = True
if event.key == K_s:
keys["s"] = True
if event.key == K_d:
keys["d"] = True
if event.key == K_SPACE:
keys[" "] = True
if event.type == KEYUP:
if event.key == K_w:
keys["w"] = False
if event.key == K_a:
keys["a"] = False
if event.key == K_s:
keys["s"] = False
if event.key == K_d:
keys["d"] = False
if event.key == K_SPACE:
keys[" "] = False
#Consistent movement
if keys["w"]:
player.move("UP", 2)
if keys["a"]:
player.move("LEFT", 2)
if keys["s"]:
player.move("DOWN", 2)
if keys["d"]:
player.move("RIGHT", 2)
#if keys[" "]:
#Shoot..
#Walls - Player
if player.position[1] <= -2:
player.position[1] += 2
if player.position[1] >= 433:
player.position[1] -= 2
if player.position[0] <= -2:
player.position[0] += 2
if player.position[0] >= 690:
player.position[0] -= 2
#Walls - Enemy
if enemy.position[1] <= -2:
enemy.position[1] += 2
if enemy.position[1] >= 433:
enemy.position[1] -= 2
if enemy.position[0] <= -2:
enemy.position[0] += 2
if enemy.position[0] >= 690:
enemy.position[0] -= 2
#Text
label = myfont.render("Health: " + str(health), 50, (255, 255, 255))
screen.blit(label, (5, 5))
player.draw(screen)
pygame.display.flip()
pygame.quit()
Turns out my original answer was close - your problem is that you're simply drawing the image - you never fill the screen even though you've declared black = (0, 0, 0). You need to put screen.fill(black) before you start drawing everything else.
For the record, here is what a Minimal, Complete, and Verifiable example looks like:
import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font.SysFont("mirc", 25)
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
class Thing:
def __init__(self, picture):
self.texture = pygame.image.load(picture).convert()
self.position = [360, 240]
def draw(self, screen):
screen.blit(self.texture, self.position)
done = False
black = (0, 0, 0)
player = Thing(os.path.expanduser("~/Downloads/disapproval.png"))
x_direction = 1
y_direction = 0
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if player.position[0] < 400:
x_direction = 1
y_direction = 0
elif player.position[0] >= 400 and player.position[1] > 100:
x_direction = 0
y_direction = -1
else:
x_direction = 0
y_direction = 0
player.position[0] += x_direction
player.position[1] += y_direction
# Uncomment this line, and you'll fix your problem
#screen.fill(black)
player.draw(screen)
pygame.display.flip()
pygame.quit()
disapproval.png
Related
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
I'm trying to make a quick animation where if a key is held down the character will keep moving, however my code doesn't seem to be doing that. I press the key and moves once but doesn't move any further. Any help to fix this. Any other suggestions are appreciated and keep in mind this isn't near final product form.
import pygame
import os
import sys
from pygame.locals import *
pygame.init()
WIN = pygame.display.set_mode(display)
pygame.display.set_caption('The Game')
width = 500
height = 500
display = (width, height)
WHITE = (255, 255, 255)
left = [
pygame.image.load(os.path.join('assets', 'main', 'left_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'left_walk2.png'))
]
right = [
pygame.image.load(os.path.join('assets', 'main', 'right_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'right_walk2.png'))
]
up = [
pygame.image.load(os.path.join('assets', 'main', 'up_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'up_walk2.png'))
]
down = [
pygame.image.load(os.path.join('assets', 'main', 'down_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'down_walk2.png'))
]
standing_left = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_right = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_up = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_down = (os.path.join('assets', 'main', 'down_walk2.png'))
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.health = 100
self.inv = []
self.left = False
self.right = False
self.up = False
self.down = False
self.walking_count = 0
self.facing = 'down'
def draw_player(self, win):
if self.walking_count == 3:
self.walking_count = 1
if self.left:
WIN.blit(left[self.walking_count // 2], (self.x, self.y))
elif self.right:
WIN.blit(right[self.walking_count // 2], (self.x, self.y))
player = Player(100, 100)
FPS = 40
fpsClock = pygame.time.Clock()
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP and player.y <= 0:
player.up = True
elif event.key == K_DOWN:
player.down = True
elif event.key == K_LEFT:
player.left = True
elif event.key == K_RIGHT:
player.right = True
elif event.type == KEYUP:
if event.key == K_UP:
player.up = False
if event.key == K_DOWN:
player.down = False
if event.key == K_LEFT:
player.left = False
if event.key == K_RIGHT:
player.right = False
if player.left:
player.x -= 5
player.walking_count += 1
if player.right:
player.x += 5
player.walking_count += 1
if player.up:
player.y -= 5
player.walking_count += 1
if player.down:
player.y += 5
player.walking_count += 1
pygame.display.update()
It is a matter of Indentation. You've to apply the movement in the application loop rather than the event loop:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP and player.y <= 0:
player.up = True
elif event.key == K_DOWN:
player.down = True
elif event.key == K_LEFT:
player.left = True
elif event.key == K_RIGHT:
player.right = True
elif event.type == KEYUP:
if event.key == K_UP:
player.up = False
if event.key == K_DOWN:
player.down = False
if event.key == K_LEFT:
player.left = False
if event.key == K_RIGHT:
player.right = False
#<--| INDENTATION
if player.left:
player.x -= 5
if player.right:
player.x += 5
if player.up:
player.y -= 5
if player.down:
player.y += 5
pygame.display.update()
Alternatively you can use pygame.key.get_pressed() rather than the KEYDOWN and KEYUP event:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
player.left, player.right, player.up, player.down = False, False, False, False
if keys[K_LEFT]:
player.x -= 5
player.left = True
if keys[K_RIGHT]:
player.x += 5
player.right = True
if keys[K_UP]:
player.y -= 5
player.up = True
if keys[K_DOWN]:
player.y += 5
player.down = True
pygame.display.update()
To control the animation speed, add an attribute self.animation_frames = 10. This attributes controls how many frames each image of the animation is shown. Compute the image index dependent on the attribute.
walking_count has to be incremented in Player.draw_player rather than the application loop.
To ensure that the correct "standing" image is displayed, you have to add an attribute self.standing. Set the attribute dependent on the current direction in draw_player. If the player is not moving, the display the current standing image:
class Player:
def __init__(self, x, y):
# [...]
self.animation_frames = 10
self.standing = standing_left
def draw_player(self, win):
# get image list
if self.left:
image_list = left
self.standing = standing_left
else self.right:
image_list = right
self.standing = standing_right
else:
image_list = [self.standing]
# increment walk count and get image list
image_index = self.walking_count // self.animation_frames
if image_index >= len(image_list):
image_index = 0
self.walking_count = 0
self.walking_count += 1
WIN.blit(image_list[image_index], (self.x, self.y))
I recently started programming in pygame and I've been wondering why doesn't my isCollision function work. You don't really have to run the code, because you will need to download the pictures to make it execute. If you can, just tell my why the isCollision function doesn't work. In the mainloop where there is a for i in range(num_of_obstacles) loop there is the if iscollision statement. If you want to see what the program does, here are all the essential files:
Btw don't rewrite the entire code pls.]2[]3
Don't mind the comments cause theyre in polish.
Here is my code:
import pygame
import math
import random
#inicjowanie pygame (to trzeba zawsze dać)
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Kosmiczna Przygoda')
playericon = pygame.image.load('rocket.png')
player2icon = pygame.image.load('rocket.png')
backgroundImg = pygame.image.load('1083.jpg')
num_of_obstacles = 10
obstacleImg = []
obsX = [random.randint(0, 400) for i in range(num_of_obstacles // 2)]
obs2X = [random.randint(400, 800) for i in range(num_of_obstacles // 2)]
for i in obs2X:
obsX.append(i)
obsY = []
for i in range(num_of_obstacles):
obstacleImg.append(pygame.image.load('rectangle.png'))
for i in range(num_of_obstacles):
obsY.append(random.randint(50, 300))
# pierwsze koordynaty
PlayerX, PlayerY = 200, 480
Player2X, Player2Y = 500, 480
PlayerY_change, PlayerX_change = 1, 1
Player2Y_change, Player2X_change = 1, 1
def player(x,y,x2,y2):
screen.blit(playericon, (x, y))
screen.blit(player2icon, (x2, y2))
winFont = pygame.font.Font('freesansbold.ttf', 64)
won1, won2 = False, False
def player1Wins():
win_text = winFont.render('PLAYER 1 WON!',True,(255,255,255))
screen.blit(win_text,(30,30))
def player2Wins():
win_text = winFont.render('PLAYER 2 WON!',True,(255,255,255))
screen.blit(win_text,(150,30))
# wzór matematyczny na odległość koordynatów dwóch punktów (sprawdzabnie czy się dotykają)
def isCollision(obsX,obsY,pX,pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
if distance >= 27:
return True
else:
return False
running = True
won = False
while running:
# tło (blit to rysowanie)
screen.blit(backgroundImg, (0, 0))
# event to wydarzenie zarejestrowane przez program
# jeżeli klikne krzyzyk w prawym gornym rogu to program sie zamknie
# jeżeli nacisne np strzalke w prawo to rakieta przesuwa się na ukos w prawo
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
PlayerX_change = -1
if event.key == pygame.K_d:
PlayerX_change = 1
if event.key == pygame.K_LEFT:
Player2X_change = -1
if event.key == pygame.K_RIGHT:
Player2X_change = 1
if event.key == pygame.K_w:
PlayerY_change = 2
if event.key == pygame.K_UP:
Player2Y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
PlayerY2_change = 0.75
if event.key == pygame.K_w:
PlayerY_change = 0.75
for enemy in range(num_of_obstacles):
if won:
screen.blit(obstacleImg[enemy], (2000, 2000))
else:
#if isCollision(obsX[enemy], obsY[enemy],PlayerX,PlayerY):
#player2Wins()
screen.blit(obstacleImg[enemy], (obsX[enemy], obsY[enemy]))
# Granice Ekranu
if PlayerX <= 0:
PlayerX = 0
elif PlayerX >= 736:
PlayerX = 736
if PlayerY <= 0:
won, won1 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if Player2X <= 0:
Player2X = 0
elif Player2X >= 736:
Player2X = 736
if Player2Y <= 0:
won, won2 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if won1:
player1Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
if won2:
player2Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
# Zmiana kordynatów rakiety
PlayerX += PlayerX_change
PlayerY -= PlayerY_change
Player2X += Player2X_change
Player2Y -= Player2Y_change
player(PlayerX, PlayerY, Player2X, Player2Y)
pygame.display.update()
Should you be checking if the distance is <= 27 rather than >= 27?
def isCollision(obsX, obsY, pX, pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
return distance <= 27
i am currentely making my final project for my exam and i'm making a platform game. Actually i'm made the collisions and it works. But the actual problem is that if i jump on a platform and i keep my player static for 1 second the player disappears which is weird. Could you help me to solve this issue? I have a hint that this issue is related to the velocity (calles vitesse_x and vitesse_y).
import pygame
from pygame.locals import *
pygame.init()
fenetre = pygame.display.set_mode((1024,768))
pygame.display.set_caption("Portal Escape")
class Perso(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50,50))
self.rect = self.image.get_rect(bottomleft=(0,740))
self.image.fill((255, 0, 0))
self.doit_monter = False
self.vitesse_x = 0
self.vitesse_y = 0
def update(self):
self.rect.x += self.vitesse_x
self.rect.y += self.vitesse_y
touche = pygame.key.get_pressed()
if touche[pygame.K_RIGHT] and self.rect.x < 920:
self.vitesse_x += 1
if touche[pygame.K_LEFT] and self.rect.x > 0:
self.vitesse_x -= 1
collision = pygame.sprite.spritecollide(self, blocs, False)
for bloc in collision:
if self.vitesse_y >= 0:
self.rect.bottom = bloc.rect.top
elif self.vitesse_y < 0:
self.rect.top = bloc.rect.bottom
perso = Perso()
class Bloc(pygame.sprite.Sprite): #pour creer un obstacle et éléments du jeu
def __init__(self, x, y, w, h):
super().__init__()
self.image = pygame.Surface((w,h))
self.image.fill((0, 255, 0))
self.rect = self.image.get_rect(topleft=(x, y))
all_sprites = pygame.sprite.Group()
blocs = pygame.sprite.Group()
all_sprites.add(perso)
b1 = Bloc(200,500,250,50)
b2 = Bloc(500,600,200,50)
b3 = Bloc(0,740,1024,30)
blocs.add(b1,b2,b3)
all_sprites.add(b1,b2,b3)
new_y = 0
continuer = True
while continuer:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type == QUIT:
continuer = False
if event.type == KEYDOWN:
if event.key == pygame.K_SPACE:
perso.doit_monter = True
new_y = perso.rect.y - 100
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and perso.vitesse_x < 0:
perso.vitesse_x = 0
perso.vitesse_y = 0
if event.key == pygame.K_RIGHT and perso.vitesse_x > 0:
perso.vitesse_x = 0
perso.vitesse_y = 0
if event.key == pygame.K_SPACE and perso.vitesse_y < 0:
perso.vitesse_y = 0
if perso.doit_monter == True:
if perso.rect.y > new_y and perso.rect.y > 0:
perso.vitesse_y -= 5
else:
perso.doit_monter = False
else:
perso.vitesse_y += 1
all_sprites.update()
fenetre.fill((0,0,0))
all_sprites.draw(fenetre)
pygame.display.flip()
pygame.quit()
Ok simple, problem, simple solution. You have to reset the y velocity if you are on the ground.
In Perso.update:
for bloc in collision:
if self.vitesse_y >= 0:
self.vitesse_y = 0 # reset velocity, so it isn't increasing forever
self.rect.bottom = bloc.rect.top
elif self.vitesse_y < 0:
self.rect.top = bloc.rect.bottom
If you don't do that, the velocity will increase, till it is high enough to jump throug the floor in one go without colliding with stopping box
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.