Python/Pygame Trouble with Game loop/Getting code to run - python

For the past few days I've been working on this code for pong and I've almost got it running. Everything works up to the movement of the objects. The screen just freezes when the pygame window opens. There seems to be something wrong in my main() but I am still fairly new to python/pygame and am lost as to what is wrong.
import pygame, sys
pygame.init()
SCR_WID, SCR_HEI = 640, 480
class Player():
def __init__(self):
self.x, self.y = 16, SCR_HEI/2
self.x1, self.y1 = SCR_WID-16, SCR_HEI/2
self.speed = 3
self.padWid, self.padHei = 8, 64
self.score = 0
self.scoreFont = pygame.font.Font("imagine_font.ttf", 64)
def scoring(self):
scoreBlit = self.scoreFont.render(str(self.score), 1, (0,0,0))
screen.blit(scoreBlit, (32, 16))
if self.score == 10:
print ("player 1 wins!")
exit()
def scoring1(self):
scoreBlit = self.scoreFont.render(str(self.score), 1, (0,0,0))
screen.blit(scoreBlit, (SCR_HEI+92, 16))
if self.score == 10:
print ("Player 2 wins!")
exit()
def movement(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.y -= self.speed
elif keys[pygame.K_s]:
self.y += self.speed
if self.y <= 0:
self.y = 0
elif self.y >= SCR_HEI-64:
self.y = SCR_HEI-64
keys1 = pygame.key.get_pressed()
if keys1[pygame.K_UP]:
self.y1 -= self.speed
elif keys1[pygame.K_DOWN]:
self.y1 += self.speed
if self.y1 <= 0:
self.y1 = 0
elif self.y >= SCR_HEI-64:
self.y1 = SCR_HEI-64
def draw(self):
pygame.draw.rect(screen, (0,0,0), (self.x, self.y, self.padWid, self.padHei))
pygame.draw.rect(screen, (0,0,0), (self.x1, self.y1, self.padWid, self.padHei))
class Ball():
def __init__(self):
self.x, self.y = SCR_WID/2, SCR_HEI/2
self.x1, self.y1 = SCR_WID/2, SCR_HEI/2
self.speed_x = -3
self.speed_y = 3
self.size = 8
def movement(self):
self.x += self.speed_x
self.y += self.speed_y
if self.y <= 0:
self.speed_y *= -1
elif self.y >= SCR_HEI-self.size:
self.speed_y *= -1
if self.x <= 0:
self.__init__()
enemy.score += 1
elif self.x >= SCR_WID-self.size:
self.__init__()
self.speed_x = 3
player.score += 1
for n in range(-self.size, player.padHei):
if self.y == player.y + n:
if self.x <= player.x + player.padWid:
self.speed_x *= -1
break
n += 1
self.x1 += self.speed_x
self.y1 += self.speed_y
if self.y1 <= 0:
self.speed_y *= -1
elif self.y1 >= SCR_HEI-self.size:
self.speed_y *= -1
if self.x1 <= 0:
self.__init__()
enemy.score += 1
elif self.x1 >= SCR_WID-self.size:
self.__init__()
self.speed_x = 3
player.score += 1
for n in range(-self.size, enemy.padHei):
if self.y1 == enemy.y1 + n:
if self.x1 >= enemy.x1 - enemy.padWid:
self.speed_x *= -1
break
n += 1
def draw(self):
pygame.draw.rect(screen, (112,138,144), (self.x, self.y, 8, 8))
SCR_WID, SCR_HEI = 640, 480
screen = pygame.display.set_mode((SCR_WID, SCR_HEI))
player = Player()
ball = Ball()
enemy = Player()
def main():
running = True
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print ("Game exited by user")
exit()
else:
running = False
pygame.font.init()
clock = pygame.time.Clock()
FPS = 60
backgroundimage = pygame.image.load("background.png")
pygame.display.set_caption("Justin's pong")
ball.movement()
player.movement()
enemy.movement()
position = (0,0)
screen.fill((0, 0, 0))
screen.blit(backgroundimage, position)
ball.draw()
player.draw()
player.scoring()
enemy.draw()
enemy.scoring1()
pygame.display.flip()
clock.tick(FPS)
main()

The problem is this code:
running = True
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print ("Game exited by user")
exit()
else:
running = False
You are correctly getting the events, but if there aren't any events (as there aren't in the beginning), you will run forever, checking for events.
I assume you want the rest of your code to run in the while loop as well, so you should indent it.

Related

My collision detection isn't working and way to laggy

So here's just the base function:
def xCollision(self):
for tile in tiles:
if tile.colliderect(self.rect):
if self.x_vel >= 1:
self.rect.right = tile.left
elif self.x_vel <= -1:
self.rect.left = tile.right
def yCollision(self):
for tile in tiles:
if tile.colliderect(self.rect):
if self.y_vel >= 1:
self.rect.bottom = tile.top
elif self.y_vel <= -1:
self.rect.top = tile.bottom
This is inside the Player class.
Now, when i try this my frames go down to around 4 fps and it also isn't working.
About it not working it has to do something with the self.rect.something = tile.something because when i replace it with print() it prints whatever.
Here is the entire code for reference, And yes i just started out so don't think its gonna be any good ok?
import pygame
import random
import math
import time
# Initialize Pygame
pygame.init()
pygame.mixer.init()
# Set the size of the window
size = (900, 600)
screen = pygame.display.set_mode(size)
# Set the title of the window
pygame.display.set_caption("Classes testing")
clock = pygame.time.Clock()
fps = 60
pygame.mixer.music.load('PewPewProject/Retro Platform.wav')
pygame.mixer.music.set_volume(0.1)
pygame.mixer.music.play(-1)
pop_sound = pygame.mixer.Sound("PewPewProject/vine-boom.wav")
pop_sound.set_volume(0.5)
level = [
['1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'],
['1','E','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','E','0','0','0','1'],
['1','0','0','0','1','1','1','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','1','0','1','0','0','0','0','0','0','0','0','E','0','0','0','0','1'],
['1','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','E','1','1','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','E','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','1','1','0','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','1','1','1','0','E','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','1','S','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1'],
['1','0','0','E','0','0','0','0','0','1','1','1','1','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'],
]
tilex, tiley = [0, 0]
tilex_offset, tiley_offset = [0, 0]
tile_size = 50
tilemap = pygame.image.load('PewPewProject/tilemap.png')
tiles = []
collision_tiles = []
enemy_spawns = []
def Build_Level():
global tiley,tilex
tiley = -1
for rows in level:
tilex = -1
tiley += 1
for tile in rows:
tilex += 1
if tile == '1':
tile_rect = pygame.draw.rect(screen, (100, 100, 100), (tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size))
tiles.append(tile_rect)
elif tile == '0':
pass
elif tile == 'E':
enemy_spawns.append([tilex, tiley])
elif tile == 'S':
pygame.draw.rect(screen, (50, 255, 100), (tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size))
elif tile == 'R':
pygame.draw.rect(screen, (255, 50, 50), (tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size))
else:
print("Wrong Map Input")
def random_except(start, end, exception_start, exception_end):
num = random.randint(start, end)
while num >= exception_start and num <= exception_end:
num = random.randint(start, end)
return num
class Player:
def __init__(self, health, speed, x, y, size, healthboost, collision_tiles):
self.speed = speed
self.x = x
self.y = y
self.y_vel = 0
self.x_vel = 0
self.size = size
self.hitbox = pygame.draw.rect(screen, (230, 100, 100), (self.x, self.y, self.size, self.size))
self.gunsurface = pygame.Surface((90, 25), pygame.SRCALPHA)
self.healthboost = healthboost
self.health = health * healthboost
self.rotated_gunsurface = self.gunsurface
self.gunsurface.fill((150, 150, 150))
self.gunrect = self.gunsurface.get_rect()
self.rect = self.hitbox
self.projectiles = [Projectile(-100, 0, 0)]
self.last_shot_time = 0
self.cooldown = 0.5
self.is_slowed = False
self.alive = True
def xCollision(self):
for tile in tiles:
if tile.colliderect(self.rect):
if self.x_vel >= 1:
self.rect.right = tile.left
elif self.x_vel <= -1:
self.rect.left = tile.right
def yCollision(self):
for tile in tiles:
if tile.colliderect(self.rect):
if self.y_vel >= 1:
self.rect.bottom = tile.top
elif self.y_vel <= -1:
self.rect.top = tile.bottom
def Render(self):
self.rect = pygame.draw.rect(screen, (230, 100, 100), (self.x, self.y, self.size, self.size))
self.Gun()
def Alive(self):
if self.health <= 0:
self.alive = False
def GUI(self):
self.empty_health_bar = pygame.draw.rect(screen, (200, 20, 20), (screen.get_width()/4, 10,466, 25))
self.health_bar = pygame.draw.rect(screen, (20, 200, 20), (screen.get_width()/4, 10, self.health*4.66/self.healthboost, 25))
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 10),(screen.get_width()/4+466, 10), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 35),(screen.get_width()/4+466, 35), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 10), (screen.get_width()/4, 35), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4+466, 10), (screen.get_width()/4+466, 35), 2)
def Gun(self):
cursor_x, cursor_y = pygame.mouse.get_pos()
dx = cursor_x - (self.x + self.size)
dy = cursor_y - (self.y + self.size)
angle = math.atan2(dy, dx)
self.rotated_gunsurface = pygame.transform.rotate(self.gunsurface, math.degrees(angle * -1))
self.gunrect = self.rotated_gunsurface.get_rect(center = (self.x+self.size/2, self.y+self.size/2))
screen.blit(self.rotated_gunsurface, (self.gunrect.x, self.gunrect.y))
def Shoot(self):
if pygame.key.get_pressed()[pygame.K_e]:
current_time = time.time()
if current_time - self.last_shot_time > self.cooldown:
pop_sound.play()
cursor_x, cursor_y = pygame.mouse.get_pos()
dx = cursor_x - (self.x + self.size/2)
dy = cursor_y - (self.y + self.size/2)
angle = math.atan2(dy, dx)
self.projectiles.append(Projectile(self.x+self.size/2, self.y+self.size/2, angle))
self.last_shot_time = current_time
self.cooldown = 0.1
def Movement(self):
global tiley_offset, tilex_offset
keys = pygame.key.get_pressed()
if self.x >= screen.get_width()-100-self.size: # Move to the RIGHT
if keys[pygame.K_d]:
tilex_offset -= self.speed
if keys[pygame.K_a]:
self.x_vel = -self.speed
if not self.y <= 100:
if keys[pygame.K_w]:
self.y_vel = -self.speed
else:
if keys[pygame.K_w]:
tiley_offset += self.speed
if not self.y >= screen.get_height()-100-self.size:
if keys[pygame.K_s]:
self.y_vel = self.speed
else:
if keys[pygame.K_s]:
tiley_offset -= self.speed
elif self.x <= 100: # Move to the LEFT
if keys[pygame.K_a]:
tilex_offset += self.speed
if keys[pygame.K_d]:
self.x_vel = self.speed
if not self.y <= 100:
if keys[pygame.K_w]:
self.y_vel = -self.speed
else:
if keys[pygame.K_w]:
tiley_offset += self.speed
if not self.y >= screen.get_height()-100-self.size:
if keys[pygame.K_s]:
self.y_vel = self.speed
else:
if keys[pygame.K_s]:
tiley_offset -= self.speed
elif self.y >= screen.get_height()-100-self.size: # Move DOWN
if keys[pygame.K_s]:
tiley_offset -= self.speed
if keys[pygame.K_w]:
self.y_vel = -self.speed
if keys[pygame.K_a]:
self.x_vel =- self.speed
if keys[pygame.K_d]:
self.x_vel = self.speed
elif self.y <= 100: # Move UP
if keys[pygame.K_w]:
tiley_offset += self.speed
if keys[pygame.K_s]:
self.y_vel = self.speed
if keys[pygame.K_a]:
self.x_vel = -self.speed
if keys[pygame.K_d]:
self.x_vel = self.speed
else: # Default Movement
if keys[pygame.K_w]:
self.y_vel = -self.speed
if keys[pygame.K_s]:
self.y_vel = self.speed
if keys[pygame.K_a]:
self.x_vel = -self.speed
if keys[pygame.K_d]:
self.x_vel = self.speed
self.x += self.x_vel
self.xCollision()
self.y += self.y_vel
self.yCollision()
self.y_vel = 0
self.x_vel = 0
class Projectile:
def __init__(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
self.speed = 8
self.hitbox = pygame.Rect(self.x, self.y, 5,5)
def Move(self):
self.x += math.cos(self.angle) * self.speed
self.y += math.sin(self.angle) * self.speed
def Render(self):
self.hitbox = pygame.draw.circle(screen, (255, 255, 0), (int(self.x), int(self.y)), 7)
class Enemy:
def __init__(self, health, main_speed, tag, size, player, x, y):
self.health = health
self.main_speed = 3
self.tag = tag
self.size = size
self.player = player
self.speed = 3
self.x = x
self.y = y
self.alive = True
def Destroy(self):
self.alive = False
def Spawning(self):
self.hitbox = pygame.draw.rect(screen, (100, 240, 100), (self.x + tilex_offset, self.y + tiley_offset, self.size, self.size))
def Movement(self):
dx = self.player.x - self.x
dy = self.player.y - self.y
angle = math.atan2(dy - tiley_offset, dx - tilex_offset)
self.x += self.speed * math.cos(angle)
self.y += self.speed * math.sin(angle)
def main():
player = Player(100, 3, screen.get_width()/2-50, screen.get_height()/2-50, 50, 1, tiles)
enemies = []
def Spawn_enemies(num_enemies, player):
for i in range(num_enemies):
x, y = random.choice(enemy_spawns)
enemy = Enemy(1, 1, i, 25, player, x*tile_size, y*tile_size)
enemies.append(enemy)
print(x, y)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Main Loop
screen.fill((100, 100, 200))
# usage
spawn_enemies_chance = random.randint(0, 200)
number_of_enemies = len(enemies)
if spawn_enemies_chance == 1 and number_of_enemies <= 4:
Spawn_enemies(1,player)
Build_Level()
# enemy
for enemy in enemies:
if enemy.alive:
enemy.Movement()
enemy.Spawning()
for projectile in player.projectiles:
if enemy.hitbox.colliderect(projectile.hitbox):
enemy.health -= 1
pop_sound.play()
if enemy.health <= 0:
enemy.alive = False
enemies.remove(enemy)
player.projectiles.remove(projectile)
keys = pygame.key.get_pressed()
if keys[pygame.K_LSHIFT]: # Slow things down by 3 times
player.is_slowed = True
for enemy in enemies:
enemy.speed = enemy.main_speed / 3
for projectile in player.projectiles:
projectile.speed = 2.6
player.speed = 1
player.cooldown = 1.5
spawn_enemies_chance = random.randint(0, 1500)
else:
player.is_slowed = False
for enemy in enemies:
enemy.speed = enemy.main_speed
for projectile in player.projectiles:
projectile.speed = 8
player.speed = 3
player.cooldown = 0.5
spawn_enemies_chance = random.randint(0, 500)
# Get Hurt
for enemy in enemies:
if enemy.hitbox.colliderect(player):
player.health -= 10
enemies.remove(enemy)
# Projectiles
for i, projectile in enumerate(player.projectiles):
projectile.Move()
projectile.Render()
if projectile.x < 0 or projectile.x > screen.get_width() or projectile.y < 0 or projectile.y > screen.get_height():
player.projectiles.pop(i)
# player
player.Alive()
player.Movement()
player.Shoot()
player.Render()
# Renders the UI ontop of everything
player.GUI()
pygame.display.update()
clock.tick(fps)
pygame.quit()
# DO NOT DISTURB!
if __name__ == "__main__":
main()
I honestly don't know why its not working but i think i know why its lagging.
It has to check for collision with every tile every single frame which causes some lag if you have a big map i belive, that's just my thought tho.
The actual problem is not the collision detection, but that Build_Level is called in the application loop. Therefore the tiles and enemy_spawns list contain more and more elements over time and your code gets slower and slower. To solve your problem, separate the function into two functions, build_level and draw_level. Call build_level before the application loop, but draw_level in the application loop:
def build_level():
for tiley, rows in enumerate(level):
for tilex, tile in enumerate(rows):
if tile == '1':
tile_rect = pygame.Rect(tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size)
tiles.append(tile_rect)
elif tile == '0':
pass
elif tile == 'E':
enemy_spawns.append([tilex, tiley])
elif tile == 'S':
pass
elif tile == 'R':
pass
else:
print("Wrong Map Input")
def draw_level():
for tiley, rows in enumerate(level):
for tilex, tile in enumerate(rows):
color = None
if tile == '1':
color = (100, 100, 100)
elif tile == 'S':
color = (50, 255, 100)
elif tile == 'R':
color = (255, 50, 50)
if color:
pygame.draw.rect(screen, color, (tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size))
def main():
# [...]
build_level()
running = True
while running:
# [...]
draw_level()

pygame Layers, pygame.sprite [duplicate]

This question already has answers here:
Pygame sprite disappearing with layeredUpdates at a certain Y coordinate
(2 answers)
pygame.sprite.LayeredUpdates.move_to_front() does not work
(1 answer)
Closed 1 year ago.
I have started making a simple 2D game in python.
Thats my code
import clock
import time
import inspect
import itertools
import threading
import sys
pygame.init()
# defining the game window
gameDisplay = pygame.display.set_mode((1280, 640))
# displaying the game window
pygame.display.set_caption("Game")
background = pygame.image.load("images/background.jpg")
right = [pygame.image.load("images/animate/a1_r.png"), pygame.image.load("images/animate/a2_r.png"),
pygame.image.load("images/animate/a3_r.png"), pygame.image.load("images/animate/a4_r.png")]
standing = pygame.image.load("images/animate/standing.png") # 65x87 px
shaking = pygame.image.load("images/animate/shaking.png")
crouching = pygame.image.load("images/animate/crouching.png")
left = [pygame.image.load("images/animate/a1_l.png"), pygame.image.load("images/animate/a2_l.png"),
pygame.image.load("images/animate/a3_l.png"), pygame.image.load("images/animate/a4_l.png")]
shop_img = pygame.image.load("images/shop.png") # 230x140 px
clock = pygame.time.Clock()
isJump = False
jumpCount = 10
height = 87
width = 65
def border(x):
if x <= 0 and keys[pygame.K_a]:
return False
elif x >= 1225 and keys[pygame.K_d]:
return False
else:
return True
class StickMan(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 7
self.steps = 0
self.left = False
self.right = False
self.crouching = False
self.shaking = False
self.hitbox = (self.x + 20, self.y, 70, 60)
def draw(self):
if self.steps + 1 >= 20:
self.steps = 0
if self.left:
gameDisplay.blit(left[self.steps // 5], (self.x, self.y))
self.steps += 1
elif self.right:
gameDisplay.blit(right[self.steps // 5], (self.x, self.y))
self.steps += 1
elif self.shaking:
gameDisplay.blit(shaking, (self.x, self.y))
elif self.crouching:
gameDisplay.blit(crouching, (self.x, self.y))
else:
gameDisplay.blit(standing, (self.x, self.y))
self.steps = 0
def move(self):
if self.vel > 0:
self.x += self.vel
def current_width(self):
self.width = 65
def current_height(self):
if not keys[pygame.K_s]:
self.height = 87
else:
self.height = 50
class shop(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self):
gameDisplay.blit(shop_img, (self.x, self.y))
Shop = shop( 200, 410, 230, 140)
Player = StickMan( 100, 470, 65, 87)
def draw():
gameDisplay.blit(background, (0, 0))
Player.draw()
Shop.draw()
run = True
# main Loop
while run:
for event in pygame.event.get():
pygame.display.update()
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and border(Player.x):
Player.x -= Player.vel
Player.left = True
Player.right = False
if keys[pygame.K_d] and border(Player.x):
Player.x += Player.vel
Player.left = False
Player.right = True
if not keys[pygame.K_d] and not keys[pygame.K_a]:
Player.left = False
Player.right = False
if keys[pygame.K_s]:
Player.crouching = True
else:
Player.crouching = False
if keys[pygame.K_q]:
Player.shaking = True
else:
Player.shaking = False
if not isJump:
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
Player.y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
pygame.display.flip()
draw()
pygame.display.update()
clock.tick(60)
I've got problem with layers. - My character is running behind the shop. I was trying to fix this by using pygame.sprite (http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite) but after many trials my man still runs behind the shop. Have you got any ideas how can I fix it ?

These hit boxes are crossing over even though they are literally not with if statements

I am trying to get my pieces to collide and and when I jump up into the air the characters should not collide.
Here is a video explaining the problem:
https://drive.google.com/file/d/1a26Vmd6TF4C3dJ0DpnFLTR1d3a_lEfn4/view?usp=sharing
The collision is with the goblin.
Furthermore, we can see that the goblin is colliding even though the boxes aren't touching and when on top of the hitbox.
I have tried to change the condition of the loop for example changed the ">" around to "<" and tried making the jump higher. Both of these did not resolve the problem and I am not an experienced coder.
Here is the main problem:
if (adventurer.hitbox_running[0] > attacker.hitbox[0] and adventurer.hitbox_running[0] < attacker.hitbox[0]+70) or (adventurer.hitbox_running[0]+70 > attacker.hitbox[0] and adventurer.hitbox_running[0]+90 < attacker.hitbox[0]+70):
if (adventurer.hitbox_running[1] > attacker.hitbox[1] and adventurer.hitbox_running[1] < attacker.hitbox[1]+70) or (adventurer.hitbox_running[1]+90 > attacker.hitbox[1] and adventurer.hitbox_running[1]+90 < attacker.hitbox[1]+70):
window.fill((255,255,255))
death()
pygame.display.update()
s(0.1)
print("hit")
Here is the entire code with all of the classes and everything:
from time import sleep as s
import random
import pygame
import time
#Loads and plays the music
pygame.mixer.pre_init(44100,16,2,4096)
pygame.init()
pygame.mixer.music.load("Music.mp3")
pygame.mixer.music.set_volume(0.0)
pygame.mixer.music.play(-1)
score = 0
#sets the dimension of the window and loads in the background
window = pygame.display.set_mode((1000, 500))
pygame.display.set_caption("Practice Game")
background = pygame.image.load('pixel6.png')
#Transforms the background to desired dimensions
background = pygame.transform.scale(background, (1000, 500))
#Loads all the jump animation
jumpv1 = [pygame.image.load('adventurer-jump-00.png'),pygame.image.load('adventurer-jump-01.png'),pygame.image.load('adventurer-jump-02.png'),pygame.image.load('adventurer-jump-03.png'), pygame.image.load('adventurer-smrslt-00.png'),pygame.image.load('adventurer-smrslt-01.png'),pygame.image.load('adventurer-smrslt-02.png'),pygame.image.load('adventurer-smrslt-03.png')]
jumpv2 = [pygame.image.load('adventurer-smrslt-00.png'),pygame.image.load('adventurer-smrslt-01.png'),pygame.image.load('adventurer-smrslt-02.png'),pygame.image.load('adventurer-smrslt-03.png')]
jumpv3 = [pygame.image.load('adventurer-smrslt-00.png'),pygame.image.load('adventurer-smrslt-01.png'),pygame.image.load('adventurer-smrslt-02.png'),pygame.image.load('adventurer-smrslt-03.png')]
jumpv4 = [pygame.image.load('adventurer-smrslt-00.png'),pygame.image.load('adventurer-smrslt-01.png'),pygame.image.load('adventurer-smrslt-02.png'),pygame.image.load('adventurer-smrslt-03.png')]
jump = jumpv1+jumpv2+jumpv3+jumpv4
#running animation
run = [pygame.image.load('adventurer-run-00.png'), pygame.image.load('adventurer-run-01.png'),pygame.image.load('adventurer-run-02.png'),pygame.image.load('adventurer-run-03.png')]
#sliding animation
slide = [pygame.image.load('adventurer-slide-00.png'),pygame.image.load('adventurer-slide-01.png'),pygame.image.load('adventurer-stand-00.png'),pygame.image.load('adventurer-stand-01.png'),pygame.image.load('adventurer-stand-02.png')]
#attacking animation
firstattack = [pygame.image.load('adventurer-attack3-00.png'),pygame.image.load('adventurer-attack3-01.png'),pygame.image.load('adventurer-attack3-02.png'),pygame.image.load('adventurer-attack3-03.png'),pygame.image.load('adventurer-attack3-04.png'),pygame.image.load('adventurer-attack3-05.png')]
secondattack = [pygame.image.load('adventurer-attack2-00.png'),pygame.image.load('adventurer-attack2-01.png'),pygame.image.load('adventurer-attack2-02.png'),pygame.image.load('adventurer-attack2-03.png'),pygame.image.load('adventurer-attack2-04.png'),pygame.image.load('adventurer-attack2-05.png')]
thirdattack = [pygame.image.load('adventurer-attack1-00.png'),pygame.image .load('adventurer-attack1-01.png'),pygame.image.load('adventurer-attack1-02.png'),pygame.image.load('adventurer-attack1-03.png'), pygame.image.load('adventurer-attack1-04.png')]
attack = firstattack+secondattack+ thirdattack
#falling animation
falling = [pygame.image.load('adventurer-fall-00.png'), pygame.image.load('adventurer-fall-01.png')]
score = 0
run_program = True
#resizes all the adventuruer images to specified dimensions
for i in range (20):
jump[i] = pygame.transform.scale(jump[i],(90,90))
for i in range(3):
run[i] = pygame.transform.scale(run[i],(90,90))
for i in range (4):
slide[i] = pygame.transform.scale(slide[i],(90,90))
for i in range (1):
falling[i] = pygame.transform.scale(falling[i],(90,90))
for i in range(16):
attack[i] = pygame.transform.scale(attack[i],(90,90))
background_x = 0
background_2 = background.get_width()
clock = pygame.time.Clock()
ghost_image = pygame.image.load('imgg.png')
def text_objects(text, font):
textSurface = font.render(text, True, (0,0,0))
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((1000/2),(500/2))
window.blit(TextSurf, TextRect)
pygame.display.update()
def death():
message_display('You DIED')
class ghost(object):
ghost_animation = [pygame.image.load('imgg.png'),pygame.image.load('imgg.png')]
def __init__(self, x,y,height):
self.x = x
self.y =y
self.height = height
self.hitbox = (x,y,100,100)
self.count = 0
def draw(self, window):
self.hitbox = (self.x, self.y, 45, 60)
if self.count >=1:
self.count = 0
self.count +=1
window.blit(pygame.transform.scale(self.ghost_animation[self.count], (45,60)), (self.x, self.y))
pygame.draw.rect(window, (255,0,0), self.hitbox, 2)
def hit(self):
print ("hit")
class eye(object):
eye_load = pygame.image.load('obstc2.png')
def __init__(self, x,y,width2, height2):
self.x = x
self.y =y
self.hitbox_enemy = (x,y,200,100)
self.count1 = 0
def draw(self, window):
self.hitbox_enemy = (self.x, self.y, 65, 65)
window.blit(pygame.transform.scale(self.eye_load, (65,65)), (self.x, self.y))
pygame.draw.rect(window, (255,0,0), self.hitbox_enemy, 2)
class player(object):
def __init__(self, x,y):
self.vel = 0.5
self.running = True
self.jumping = True
self.sliding = True
self.attacking = True
self.isJump = False
self. jumps = True
self.fall = True
self.player_x = 40
self.player_y = 378
self.x = 40
self.y = 378
self.width = 378
self.speed = 0.6
self.jumpcount = 10
self.jumpingcount = 0
self.runcount = 0
self.attackcount = 0
self.slidecount = 0
self.fallspeed = 0.3
self.fallingcount = 0
self.hitbox_running = (self.player_x,self.player_y,90,90)
self.hitbox_sliding = (45,self.player_y+47,65,45)
self.hitbox_falling = (self.player_x+30,self.player_y,35,80)
self.hitbox_jumping = (self.player_x+20,self.player_y+20,52,55)
self.hitbox_attacking = (58,405,47,70)
self.hitbox_sword = (108, 405, 20, 50)
def movement(self, window):
pygame.time.delay(20)
if self.runcount >= 3:
self.runcount = 0
if self.running == True:
window.blit(run[self.runcount],(int(self.player_x),int(self.player_y)))
self.runcount +=1
self.hitbox_running = (self.player_x+30,self.player_y+20,48,70)
pygame.draw.rect(window,(255,0,0),self.hitbox_running, 2)
if (keys[pygame.K_DOWN]) or ((keys[pygame.K_DOWN]) and keys[pygame.K_p]):
if self.player_y == 378:
self.running = False
if self.slidecount >= 4:
self.slidecount = 0
if self.sliding:
window.blit(slide[self.slidecount],(int(self.player_x),int(self.player_y)))
self.slidecount +=1
pygame.draw.rect(window,(255,0,0),self.hitbox_sliding, 2)
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_DOWN )and self.player_y < self.width:
self.running = False
self.jumping = False
self.fallspeed += 0.2
if self.fallingcount >= 1:
self.fallingcount = 0
if self.fall:
window.blit(falling[self.fallingcount], (int(self.player_x),int(self.player_y)))
self.hitbox_falling = (self.player_x+30,self.player_y,35,80)
pygame.draw.rect(window,(255,0,0),self.hitbox_falling, 2)
self.fallingcount +=1
if keys[pygame.K_UP] and keys[pygame.K_p] :
self.fallspeed = 0.3
self.running = False
self.jumping = False
self.sliding = False
if self.attackcount >= 16:
self.attackcount = 0
if self.attacking:
window.blit(attack[self.attackcount],(int(self.player_x),int(self.player_y)))
self.attackcount += 1
self.hitbox_attacking = (self.player_x+30,self.player_y+20,38,70)
self.hitbox_sword = (self.player_x+72, self.player_y+20, 20, 50)
pygame.draw.rect(window,(255,0,0),self.hitbox_attacking, 2)
pygame.draw.rect(window,(255,0,0),self.hitbox_sword, 2)
if self.jumpingcount >= 20:
self.jumpingcount = 0
if self.jumping and self.player_y < self.width:
window.blit(jump[self.jumpingcount],(int(self.player_x),int(self.player_y)))
self.hitbox_jumping = (int(self.player_x+20),int(self.player_y+20),52,55)
pygame.draw.rect(window,(255,0,0),self.hitbox_jumping, 2)
self.jumpingcount +=1
self.fallspeed = 0.3
if keys[pygame.K_UP]:
self.fallspeed = 0.3
self.running = False
if self.jumpingcount >= 20:
self.jumpingcount = 0
if self.jumping and self.player_y < self.width:
window.blit(jump[self.jumpingcount],(int(self.player_x),int(self.player_y)))
self.hitbox_jumping = (int(self.player_x+20),int(self.player_y+20),52,55)
pygame.draw.rect(window,(255,0,0),self.hitbox_jumping, 2)
self.jumpingcount +=1
self.fallspeed = 0.3
if keys[pygame.K_p] and not keys[pygame.K_UP]:
self.running = False
self.jumping = False
self.sliding = False
if self.attackcount >= 16:
self.attackcount = 0
if self.attacking:
self.hitbox_attacking = (self.player_x+30,self.player_y+20,38,70)
self.hitbox_sword = (self.player_x+72, self.player_y+20, 20, 50)
window.blit(attack[self.attackcount],(int(self.player_x),int(self.player_y)))
self.attackcount += 1
pygame.draw.rect(window,(255,0,0),self.hitbox_attacking, 2)
pygame.draw.rect(window,(255,0,0),self.hitbox_sword, 2)
if keys[pygame.K_DOWN] and keys[pygame.K_UP]:
self.running = False
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
self.running = True
self.jumping = True
self.fallspeed = 0.3
if event.key == pygame.K_UP:
self.running=True
if event.key == pygame.K_p:
self.running = True
self.jumping = True
self.sliding = True
class enemy(object):
walkright = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'), pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'), pygame.image.load('R7E.png'), pygame.image.load('R8E.png'), pygame.image.load('R9E.png'), pygame.image.load('R10E.png'), pygame.image.load('R11E.png')]
walkleft = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'), pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'), pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png'), pygame.image.load('L10E.png'), pygame.image.load('L11E.png')]
for i in range (10):
walkright[i] = pygame.transform.scale(walkright[i],(70,70))
for i in range(10):
walkleft[i] = pygame.transform.scale(walkleft[i],(70,70))
def __init__(self,enemy_x,enemy_y, end):
self.x = enemy_x
self.y = enemy_y
self.end = end
self.path = [self.x,self.end]
self.walkcount = 0
self.vel = 7
self.hitbox = (self.x,self.y-15,90,90)
def draw_enemy(self,window):
self.move()
if self.walkcount+1 >= 33:
self.walkcount = 0
self.vel+=0.2
#walking right
if self.vel > 0:
window.blit(self.walkleft[self.walkcount//3], (self.x,self.y-15))
self.walkcount += 1
#walking left
if self.vel < 0:
## window.blit(self.walkleft[self.walkcount//3], (self.x,self.y))
self.walkcount -= 1
if self.x < -100:
self.x = 1050
self.hitbox = (self.x+25,self.y-15,41,70)
pygame.draw.rect(window, (255,0,0),self.hitbox,2)
def move(self):
if self.vel > 0:
#see if position + movement space is < the end, then it is able to move
if self.x + self.vel < self.path[1]:
self.x -= self.vel
#past end point and turns 180
else:
self.vel = self.vel*-1
self.walkcount = 0
#see if position is smaller than starting position
else:
if self.x - self.vel > self.path[0]:
#vel is already negative
self.x += self.vel
else:
#Truns 180 agian
self.vel = self.vel* -1
self.walkcount = 0
class wizard(object):
walkleft = [pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_05.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_05.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_05.gif'),pygame.image.load('wizard-fly-forward_04.gif'), pygame.image.load('wizard-fly-forward_04.gif'),pygame.image.load('wizard-fly-forward_05.gif')]
for i in range(16):
walkleft[i] = pygame.transform.scale(walkleft[i],(70,70))
def __init__(self,enemy_x,enemy_y, end):
self.x = enemy_x
self.y = enemy_y
self.end = end
self.path = [self.x,self.end]
self.walkcount = 0
self.vel = 7
self.hitbox = (self.x,self.y-15,90,90)
def draw_enemy(self,window):
self.move()
if self.walkcount >= 16:
self.walkcount = 0
#walking left
if self.vel > 0:
window.blit(self.walkleft[self.walkcount], (self.x,self.y-15))
self.walkcount += 1
self.vel+=0.002
if self.x < -120:
self.x = 1100
self.hitbox = (self.x+25,self.y-15,41,70)
pygame.draw.rect(window, (255,0,0),self.hitbox,2)
def move(self):
if self.vel > 0:
#see if position + movement space is < the end, then it is able to move
if self.x + self.vel < self.path[1]:
self.x -= self.vel
#past end point and turns 180
else:
self.vel = self.vel*-1
self.walkcount = 0
#see if position is smaller than starting position
else:
if self.x - self.vel > self.path[0]:
#vel is already negative
self.x += self.vel
else:
#Truns 180 agian
self.vel = self.vel* -1
self.walkcount = 0
class dragon(object):
walkleft = [pygame.image.load('dragon_1.gif'), pygame.image.load('dragon_2.gif'), pygame.image.load('dragon_3.gif'), pygame.image.load('dragon_4.gif'), pygame.image.load('dragon_5.gif'), pygame.image.load('dragon_6.gif')]
for i in range (6):
walkleft[i] = pygame.transform.scale(walkleft[i],(200,176))
def __init__(self,enemy_x,enemy_y, end):
self.x = enemy_x
self.y = enemy_y
self.end = end
self.path = [self.x,self.end]
self.walkcount = 0
self.vel = 7
self.hitbox = (self.x,self.y-15,90,90)
def draw_enemy(self,window):
self.move()
if self.walkcount >= 6:
self.walkcount = 0
#walking left
if self.vel > 0:
window.blit(self.walkleft[self.walkcount], (self.x,300))
self.walkcount += 1
self.vel+=0.002
if self.x < -120:
self.x = 1100
self.hitbox = (self.x+25,self.y-15,41,70)
pygame.draw.rect(window, (255,0,0),self.hitbox,2)
def move(self):
if self.vel > 0:
#see if position + movement space is < the end, then it is able to move
if self.x + self.vel < self.path[1]:
self.x -= self.vel
#past end point and turns 180
else:
self.vel = self.vel*-1
self.walkcount = 0
#see if position is smaller than starting position
else:
if self.x - self.vel > self.path[0]:
#vel is already negative
self.x += self.vel
else:
#Truns 180 agian
self.vel = self.vel* -1
self.walkcount = 0
ghost_list = []
eye_list = []
def keepdrawing():
window.blit(background, (background_x,0))
window.blit(background, (background_2,0))
for draw_ghost in ghost_list:
draw_ghost.draw(window)
for draw_eye in eye_list:
draw_eye.draw(window)
adventurer.movement(window)
attacker.draw_enemy(window)
wizard.draw_enemy(window)
dragon.draw_enemy(window)
score_text = score_font.render("score: " + str(score), 1, (0,0,0))
window.blit(score_text,(470,10))
pygame.display.update()
score_font = pygame.font.SysFont("Arial",30,True)
attacker = enemy(950,407,951)
adventurer = player(40,387)
wizard = wizard(905,407,951)
dragon = dragon(905,407, 951)
vel_background = 2
pygame.time.set_timer(pygame.USEREVENT+1,random.randint(1000, 2000))
pygame.time.set_timer(pygame.USEREVENT+2,random.randint(2000, 3000))
while run:
while run_program:
clock.tick(60)
background_x -= vel_background
background_2 -= vel_background
if background_x < background.get_width() * -1:
background_x = background.get_width()
if background_2 < background.get_width() * -1:
background_2 = background.get_width()
keys = pygame.key.get_pressed()
if (adventurer.hitbox_running[0] > attacker.hitbox[0] and adventurer.hitbox_running[0] < attacker.hitbox[0]+70) or (adventurer.hitbox_running[0]+70 > attacker.hitbox[0] and adventurer.hitbox_running[0]+90 < attacker.hitbox[0]+70):
if (adventurer.hitbox_running[1] > attacker.hitbox[1] and adventurer.hitbox_running[1] < attacker.hitbox[1]+70) or (adventurer.hitbox_running[1]+90 > attacker.hitbox[1] and adventurer.hitbox_running[1]+90 < attacker.hitbox[1]+70):
window.fill((255,255,255))
death()
pygame.display.update()
s(0.1)
print("hit")
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
exit()
if event.type == pygame.USEREVENT+1:
vel_background+=0.2
if event.type == pygame.USEREVENT+2:
r = random.randint(0,1)
if r==0:
new_eye = eye(1050, 390, 64,64)
eye_list.append(new_eye)
if r==1:
new_ghost = ghost(1050,390,64)
ghost_list.append(new_ghost)
if not(adventurer.isJump):
if keys[pygame.K_UP]:
adventurer.isJump =True
else:
if adventurer.jumpcount >= -10:
neg=1
if adventurer.player_y > adventurer.width:
adventurer.player_y = adventurer.width
if adventurer.jumpcount <0:
neg = -1
## s(0.01)
adventurer.player_y -= (adventurer.jumpcount**2)*adventurer.fallspeed*neg*2
## s(0.01)
adventurer.jumpcount -=1
if adventurer.player_y > adventurer.width:
adventurer.player_y=adventurer.width
else:
adventurer.isJump = False
adventurer.jumpcount = 10
if adventurer.player_y > adventurer.width:
player_y = adventurer.width
adventurer.fallspeed = 0.05
keepdrawing()
The expected results should be that the output should not be shit if the hit boxes are not in contact.
The major issue is that you've different "hitboxis, which have different meanings at different states of the game, but you use adventurer.hitbox_running for the collison test event if adventurer is .running or .falling.
The best solution would be the set one .hitbox attribute, which always contains the proper location of adventurer in the method player.movement.
But it is also possible the choose the proper hit box:
if adventurer.running:
hitbox = adventurer.hitbox_running
elif adventurer.jumping:
hitbox = adventurer.hitbox_jumping
elif adventurer.falling:
hitbox = adventurer.hitbox_falling
Further I recommend to use pygame.Rect objects and .colliderect() for the collision test:
rect_adventurer = pygame.Rect(*hitbox)
rect_attacker = pygame.Rect(*attacker.hitbox)
if rect_adventurer.colliderect(rect_attacker):
window.fill((255,255,255))
death()
pygame.display.update()
s(0.1)
print("hit")

adding a def main to the end of my pong game code

I'm trying to add a def main to the end of my pong game to make it easier to read, but i've ran into problems trying to do that. When I add the def main, I just get a black screen, but without it I get the whole game.
import pygame
SCR_WID, SCR_HEI = 640, 480
class Player():
def __init__(self):
self.x, self.y = 16, SCR_HEI/2
self.speed = 3
self.padWid, self.padHei = 8, 64
self.score = 0
self.scoreFont = pygame.font.Font("imagine_font.ttf", 64)
def scoring(self):
scoreBlit = self.scoreFont.render(str(self.score), 1, (255, 255, 255))
screen.blit(scoreBlit, (32, 16))
if self.score == 10:
print ("player 1 wins!")
exit()
def movement(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.y -= self.speed
elif keys[pygame.K_s]:
self.y += self.speed
if self.y <= 0:
self.y = 0
elif self.y >= SCR_HEI-64:
self.y = SCR_HEI-64
def draw(self):
pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.padWid, self.padHei))
class Enemy(Player):
def __init__(self):
self.x, self.y = SCR_WID-16, SCR_HEI/2
self.speed = 3
self.padWid, self.padHei = 8, 64
self.score = 0
self.scoreFont = pygame.font.Font("imagine_font.ttf", 64)
def scoring(self):
scoreBlit = self.scoreFont.render(str(self.score), 1, (255, 255, 255))
screen.blit(scoreBlit, (SCR_HEI+92, 16))
if self.score == 10:
print ("Player 2 wins!")
exit()
def movement(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.y -= self.speed
elif keys[pygame.K_DOWN]:
self.y += self.speed
if self.y <= 0:
self.y = 0
elif self.y >= SCR_HEI-64:
self.y = SCR_HEI-64
def draw(self):
pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.padWid, self.padHei))
class Ball():
def __init__(self):
self.x, self.y = SCR_WID/2, SCR_HEI/2
self.speed_x = -3
self.speed_y = 3
self.size = 8
def movement(self):
self.x += self.speed_x
self.y += self.speed_y
#wall col
if self.y <= 0:
self.speed_y *= -1
elif self.y >= SCR_HEI-self.size:
self.speed_y *= -1
if self.x <= 0:
self.__init__()
enemy.score += 1
elif self.x >= SCR_WID-self.size:
self.__init__()
self.speed_x = 3
player.score += 1
##wall col
#paddle col
#player
for n in range(-self.size, player.padHei):
if self.y == player.y + n:
if self.x <= player.x + player.padWid:
self.speed_x *= -1
break
n += 1
#enemy
for n in range(-self.size, enemy.padHei):
if self.y == enemy.y + n:
if self.x >= enemy.x - enemy.padWid:
self.speed_x *= -1
break
n += 1
##paddle col
def draw(self):
pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, 8, 8))
SCR_WID, SCR_HEI = 640, 480
screen = pygame.display.set_mode((SCR_WID, SCR_HEI))
pygame.display.set_caption("Pong")
pygame.font.init()
clock = pygame.time.Clock()
FPS = 60
def main():
ball = Ball()
player = Player()
enemy = Enemy()
while True:
#process
for event in pygame.event.get():
if event.type == pygame.QUIT:
print ("Game exited by user")
exit()
##process
#logic
ball.movement()
player.movement()
enemy.movement()
##logic
#draw
screen.fill((0, 0, 0))
ball.draw()
player.draw()
player.scoring()
enemy.draw()
enemy.scoring()
##draw
#_______
pygame.display.flip()
clock.tick(FPS)
main()
The call for main() on the end should be
if __name__ == "__main__":
main()
So that you can run your code and get the function to run. Also your indentation seems a little off. Is your code structured correctly with regard to spaces?
As already answered, you should insert the following statement at the end of the script:
if __name__ == "__main__":
main()
This answer will give you more info about the meaning of that statement.
What does if __name__ == "__main__": do?
In short, it tells the interpreter what it has to do with the function main():
1) Run it automatically if the file has been executed as stand alone script.
2) Don't run if the file has been imported as module from another script.
In your case, the wanted behaviour is the number one.

Pygame, keep jumping and glitching through the "ground"

My character won't jump properly, he keeps glitching through the ground. If i hold key up, my character won't stop going higher. Do you have some ideas for how I could fix it?
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1200, 800))
screen.fill((0,0,0))
pygame.display.set_caption('Jump and Run')
BLACK = (0,0,0)
WHITE = (250, 250,250)
RED = (250, 0, 0)
BLUE = (0,0,250)
direction = 'right'
way = 0
jump_high = 0
class Hero():
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load('hero.bmp')
self.groundcontact = True
self.vy = 0
alive = True
def check_pos(self):
if self.y >= 400:
self.groundcontact = True
elif self.y <= 400:
self.groundcontact = False
def load_picture(self,surface):
surface.blit(self.image,(self.x, self.y))
def check_input(self):
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
self.x += 10
elif key[pygame.K_LEFT]:
self.x -= 10
elif key[pygame.K_UP]:
self.y -= 50
if not self.groundcontact:
self.vy += 1 #max(min(2,200), -200)
#self.y += self.vy
print "not self.groundcontact"
else:
self.vy = 0
#self.y += self.vy
self.y += self.vy
class Monster():
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load('monster.bmp')
self.collision = False
self.alive = True
def load_picture(self,surface):
surface.blit(self.image,(self.x, self.y))
def walk(self):
global direction
global way
if direction == "right":
self.x += 4
way += 1
if way == 100:
direction = "left"
elif direction == "left":
self.x -= 4
way -= 1
if way == 0:
direction = "right"
monster2 = Monster( 200, 333)
monster1 = Monster(400, 450)
hero = Hero(0, 400)
clock = pygame.time.Clock()
pygame.draw.rect(screen, WHITE,(0,500, 1200, 50))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
hero.check_pos()
monster1.walk()
monster2.walk()
hero.check_input()
screen.fill(BLACK)
hero.load_picture(screen)
monster1.load_picture(screen)
monster2.load_picture(screen)
pygame.draw.rect(screen, WHITE,(0,500, 1200, 50))
pygame.display.update()
clock.tick(40)
Regarding my comment above, changing the Hero class to somthing like this:
JUMP_POWER = 10
class Hero():
...
def check_input(self):
key = pygame.key.get_pressed()
...
elif key[pygame.K_UP]:
if self.groundcontact:
self.vy -= JUMP_SPEED

Categories