Outside of my game loop, I have created a function that creates a list of 200 enemies with random coordinates. These enemies are suppose to start at the top of the screen and then drop down at random speeds. Inside the loop, I use a "for" loop to blit the enemies on screen. It works, but all 200 hundred are spawned and fall at the same time, albeit, at different speeds. So I know I need a timer and herein lies the problem; nothing I do works. Ive tried clock.tick(), pygame.delay(), import time and do the time.time() method. Everything either strobes or the system just crashes. What's causing the problem?
[Code]
import pygame
import sys
import random
import time
pygame.init()
#MAIN GAME
game_screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Beer Goggles")
bg = pygame.image.load("bg.png")
bg_image = pygame.transform.scale(bg, (600, 600))
class Object:
def __init__(self, image_path, width, height, x, y):
self.image_path = image_path
self.width = width
self.height = height
self.x = x
self.y = y
player = pygame.image.load(image_path)
self.player_main = pygame.transform.scale(player, (width,height))
def draw(self, background):
background.blit(self.player_main, (self.x, self.y))
#enemies
def enemy():
enemy_list = []
for e in range(200):
x_cor = random.randint(25, 361)
e = Object("enemy.png", 70, 70, x_cor, 25)
enemy_list.append(e)
return enemy_list
#Main Objects
player1 = Object("crate.png", 70, 70, 25, 500)
list1 = enemy()
#ladies
fat_lady = Object("fat_lady.png", 300, 300, 360, 180)
# Main Loop
direction = 0
game_on = True
while game_on:
clock = pygame.time.Clock()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_on = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
direction = 1
elif event.key == pygame.K_LEFT:
direction = -1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
direction = 0
game_screen.fill((0,0,0))
game_screen.blit(bg_image, (0,0))
#title.draw(game_screen)
player1.draw(game_screen)
fat_lady.draw(game_screen)
#move
if direction > 0:
player1.x = player1.x + 10
elif direction < 0:
player1.x = player1.x - 10
#boundaries
if player1.x <= 25:
player1.x = 25
elif player1.x >= 360:
player1.x = 360
#for enemy in list1:
for enemy in list1:
a = random.randint(1, 30)
enemy.draw(game_screen)
enemy.y += a
#collisions
#scoring
pygame.display.update()
quit()
In the code where you create the enemy list you could add a drop start time. Just like you create a random x co-ordinate you could create a time to start dropping it. Then later when you start changing the y position for them (dropping them), you would not start it dropping until after that time had passed.
By the way You have a method enemy() and later you have a loop iterator enemy which will override hide the method by that name. After that point if you tried to call the method enemy() it would fail and you would access the loop iterator instead. It does not affect your code here because you do not try to access the method after creating the loop iterator variable, but it is not a great idea and could cause problems if you later changed the code and did try to access that method. You should be careful about name choices.
Related
I'm making a game in pygame and I'm having some trouble with object collisions.
import pygame, sys
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
#Environment Variables
gravity = -1
jumpForce = 20
moveSpeed = 10
#Game Objects
playerPos = Vector2(230,230)
playerVelo = Vector2(0,0)
player = pygame.Rect(playerPos.x,playerPos.y, 20, 20)
boxPos = Vector2(350,480)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
def Clamp(var, minClamp, maxClamp):
if minClamp > maxClamp:
raise Exception("minClamp must be less than maxClamp")
if var < minClamp:
var = minClamp
if var > maxClamp:
var = maxClamp
return var
def Draw():
global player,box
screen.fill((255,255,25))
player = pygame.Rect(playerPos.x,playerPos.y, 20, 20)
pygame.draw.rect(screen,(0,100,255),player)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
pygame.draw.rect(screen,(10,200,20),box)
def PlayerVelocity():
global playerPos,playerVelo,player,box,boxPos
if player.colliderect(box):
playerPos = Vector2(boxPos.x,boxPos.y-20)
print("balls")
if playerPos.y < 499:
playerVelo.y += gravity
#if not pygame.Rect(playerPos.x+playerVelo.x,playerPos.y+playerVelo.y,20,20).colliderect(box):
playerPos -= playerVelo
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_SPACE or event.key == pygame.K_UP:
playerVelo.y = jumpForce
print(playerVelo)
keys = pygame.key.get_pressed()
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
playerVelo.x = 1*moveSpeed
elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
playerVelo.x = -1*moveSpeed
else:
playerVelo.x = 0
#Draw things to the screen
Draw()
PlayerVelocity()
playerPos.x = Clamp(playerPos.x, 0, 480)
playerPos.y = Clamp(playerPos.y,0,480)
pygame.display.update()
clock.tick(30)
I've tried looking this up and the other solutions either don't work with the movement system I've implemented or I just plain don't understand them.
It is not enough to change the position of the player when the player hits the obstacle. You need to constrain the player's box (pygame.Rect object) with the obstacle rectangle and update the player's position. Clamp and calculate the position of the player before checking for collision:
def PlayerVelocity():
global playerPos,playerVelo,player,box,boxPos
prev_y = playerPos.y
if playerPos.y < 499:
playerVelo.y += gravity
playerPos -= playerVelo
playerPos.x = Clamp(playerPos.x, 0, 480)
playerPos.y = Clamp(playerPos.y, 0, 480)
player = pygame.Rect(playerPos.x, playerPos.y, 20, 20)
box = pygame.Rect(boxPos.x, boxPos.y, 20,20)
if player.colliderect(box):
if prev_y+20 <= box.top:
player.bottom = box.top
elif player.left < box.left:
player.right = box.left
else:
player.left = box.right
playerPos = Vector2(player.topleft)
print("balls")
import pygame
pygame.init()
red = 255,0,0
blue = 0,0,255
black = 0,0,0
screenWidth = 800
screenHeight = 600
gameDisplay = pygame.display.set_mode((screenWidth,screenHeight)) ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS') ## set my title of the window
clock = pygame.time.Clock()
class player(): ## has all of my attributes for player 1
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.height = height
self.width = width
self.vel = 5
self.left = False
self.right = False
self.up = False
self.down = False
class projectile(): ## projectile attributes
def __init__(self,x,y,radius,colour,facing):
self.x = x
self.y = y
self.radius = radius
self.facing = facing
self.colour = colour
self.vel = 8 * facing # speed of bullet * the direction (-1 or 1)
def draw(self,gameDisplay):
pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius) ## put a 1 after that to make it so the circle is just an outline
def redrawGameWindow():
for bullet in bullets: ## draw bullets
bullet.draw(gameDisplay)
pygame.display.update()
#mainloop
player1 = player(300,410,50,70) # moves the stuff from the class (when variables are user use player1.var)
bullets = []
run = True
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed() ## check if a key has been pressed
## red player movement
if keys[pygame.K_w] and player1.y > player1.vel: ## check if that key has been pressed down (this will check for w) and checks for boundry
player1.y -= player1.vel ## move the shape in a direction
player1.up = True
player1.down = False
if keys[pygame.K_a] and player1.x > player1.vel: ### this is for a
player1.x -= player1.vel
player1.left = True
player1.right = False
if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
player1.y += player1.vel
player1.down = True
player1.up = False
if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel: ## this is for d
player1.x += player1.vel
player1.right = True
player1.left = False
if keys[pygame.K_SPACE]: # shooting with the space bar
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing)) ##just like calling upon a function
## level
gameDisplay.fill((0,255,0)) ### will stop the shape from spreading around and will have a background
pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height)) ## draw player
pygame.display.update()
redrawGameWindow()
pygame.quit()
When I shoot more than 1 bullet fires and I only want 1 bullet to fire at a time (but not only 1 bullet on the screen)
They all fire in a large clump and stick together also so I want them to fire at different times
I have tried using a delay clock.tick but that makes the game extremely laggy
I am relatively new to pygame and don't fully understand it any help would be appreciated thanks !
The general approach to firing bullets is to store the positions of the bullets in a list (bullet_list). When a bullet is fired, add the bullet's starting position ([start_x, start_y]) to the list. The starting position is the position of the object (player or enemy) that fires the bullet. Use a for-loop to iterate through all the bullets in the list. Move position of each individual bullet in the loop. Remove a bullet from the list that leaves the screen (bullet_list.remove(bullet_pos)). For this reason, a copy of the list (bullet_list[:]) must be run through (see How to remove items from a list while iterating?). Use another for-loop to blit the remaining bullets on the screen:
bullet_list = []
while run == True:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_list.append([start_x, start_y])
for bullet_pos in bullet_list[:]:
bullet_pos[0] += move_bullet_x
bullet_pos[1] += move_bullet_y
if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
bullet_list.remove(bullet_pos)
# [...]
for bullet_pos in bullet_list[:]
screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))
# [...]
See also Shoot bullet.
The states which are returned by pygame.key.get_pressed() are, set, as long a key is hold down. That is useful for the movement of a player. The player keeps moving as long a key is hold down.
But it contradicts your intention, when you want to fire a bullet. If you want to fire a bullet when a key is pressed, then can use the KEYDOWN event. The event occurs only once when a key is pressed:
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
# [...]
If you want to implement some kind of rapid fire, then the things get more tricky. If you would use the state of pygame.key.get_pressed() then you would spawn one bullet in every frame. That is far too fast. You have to implement some timeout.
When a bullet is fired, the get the current time by pygame.time.get_ticks(). Define a number of milliseconds for the delay between to bullets. Add the dela to the time and state the time in a variable (next_bullet_threshold). Skip bullets, as long the time is not exceeded:
next_bullet_threshold = 0
run = True
while run == True:
# [...]
current_time = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:
bullet_delay = 500 # 500 milliseconds (0.5 seconds)
next_bullet_threshold = current_time + bullet_delay
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5:
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
Minimal example: repl.it/#Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
next_bullet_time = current_time + bullet_delta_time
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()
I'm trying to make a game where the player can move the main sprite (gran) left right in 3 columns avoiding falling thunderclouds from the sky. Both components work but won't at the same time, so I can either move the player or the thundercloud falls from the top. Please can someone help so both of these events can occur at the same time
Heres my code...
import pygame, sys
import random
import time
from pygame.locals import *
#sets colours for transparency
BLACK = ( 0, 0, 0)
#Sets gran sprite
class Sprite_maker(pygame.sprite.Sprite): # This class represents gran it derives from the "Sprite" class in Pygame
def __init__(self, filename):
super().__init__() # Call the parent class (Sprite) constructor
self.image = pygame.image.load(filename).convert()# Create an image loaded from the disk
self.image.set_colorkey(BLACK)#sets transparrency
self.rect = self.image.get_rect()# Fetchs the object that has the dimensions of the image
#Initilizes pygame game
pygame.init()
pygame.display.set_caption("2nd try")
#sets background
swidth = 360
sheight = 640
sky = pygame.image.load("sky.png")
screen = pygame.display.set_mode([swidth,sheight])
#This is a list of every sprite
all_sprites_list = pygame.sprite.Group()
#Sets thunder list and creates a new thunder cloud and postions it
tcloud_speed = 10
tc_repeat = 0
thunder_list = [0, 120, 240]
for i in range(1):
tx = random.choice(thunder_list)
tcloud = Sprite_maker("thundercloud.png")
tcloud.rect.x = tx
tcloud.rect.y = 0
all_sprites_list.add(tcloud)
#Creates the gran sprite
gran = Sprite_maker("gran.png")
all_sprites_list.add(gran)
gran.rect.x = 120
gran.rect.y = 430
#Movement of gran sprite when left/right pressed
def gran_movement(movex):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and gran.rect.x == 0:
gran.rect.x = 0
elif event.key == pygame.K_RIGHT and gran.rect.x == 240:
gran.rect.x = 240
elif event.key == pygame.K_LEFT:#left key pressed player moves left 1
gran.rect.x -= 120
elif event.key == pygame.K_RIGHT:#right key pressed player moves left 1
gran.rect.x += 120
return movex
#Main program loop
game_start = True
while game_start == True:
for event in pygame.event.get():
tcloud.rect.y += tcloud_speed
if event.type == pygame.QUIT: #If user clicked close
game_start = False #Exits loop
#Clear the screen and sets background
screen.blit(sky, [0, 0])
#Displays all the sprites
all_sprites_list.draw(screen)
pygame.display.flip()
#Moves gran by accessing gran
gran_movement(gran.rect.x)
#Moves cloud down screen
if tc_repeat == 0:
tcloud.rect.y = 0
time.sleep(0.25)
tc_repeat = 1
else:
tcloud.rect.y += tcloud_speed
pygame.quit()
I'd actually create some pygame.sprite.Sprite subclasses and sprite groups, but since you're not familiar with them, I'll just use pygame.Rects and pygame.Surfaces.
So, create a rect for the player and a list of rects for the clouds. The rects are used as the blit positions (images/surfaces get blitted at the rect.topleft coordinates) and also for the collision detection (colliderect).
To move the clouds, you have to iterate over the cloud_list with a for loop and increment the y coordinate of each rect. That will happen once per frame (iteration of the while loop) and the game will run with 30 frames per second (because of clock.tick(30)).
The player movement (in the event loop) will seemingly take place at the same time as the cloud movement.
import random
import pygame
pygame.init()
# Some replacement images/surfaces.
PLAYER_IMG = pygame.Surface((38, 68))
PLAYER_IMG.fill(pygame.Color('dodgerblue1'))
CLOUD_IMG = pygame.Surface((38, 38))
CLOUD_IMG.fill(pygame.Color('gray70'))
def main():
screen = pygame.display.set_mode((360, 640))
clock = pygame.time.Clock()
# You can create a rect with the `pygame.Surface.get_rect` method
# and pass the desired coordinates directly as an argument.
player_rect = PLAYER_IMG.get_rect(topleft=(120, 430))
# Alternatively create pygame.Rect instances in this way.
cloud_rect = pygame.Rect(120, 0, 38, 38)
# The clouds are just pygame.Rects in a list.
cloud_list = [cloud_rect]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
player_rect.x += 120
elif event.key == pygame.K_a:
player_rect.x -= 120
remaining_clouds = []
for cloud_rect in cloud_list:
# Move the cloud downwards.
cloud_rect.y += 5
# Collision detection with the player.
if player_rect.colliderect(cloud_rect):
print('Collision!')
# To remove cloud rects that have left the
# game area, append only the rects above 600 px
# to the remaining_clouds list.
if cloud_rect.top < 600:
remaining_clouds.append(cloud_rect)
else:
# I append a new rect to the list when an old one
# disappears.
new_rect = pygame.Rect(random.choice((0, 120, 240)), 0, 38, 38)
remaining_clouds.append(new_rect)
# Assign the filtered list to the cloud_list variable.
cloud_list = remaining_clouds
screen.fill((30, 30, 30))
# Blit the cloud image at the cloud rects.
for cloud_rect in cloud_list:
screen.blit(CLOUD_IMG, cloud_rect)
screen.blit(PLAYER_IMG, player_rect)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()
I have been working on this pygame application, that is bascially a coin collecting game. It has a very simple idea, where you have a freely moving player (a blue ball in this case, move it by "WASD") and it should collect coins that appear on the screen after a certain amount of time. The code is pretty long, for SO standarts, I will try my best explaining my problem.
from pygame.locals import *
import pygame
import sys
import time
import random
image_resources = "C:/Users/user/Desktop/Pygame App/app_resources/image_resources/"
sound_resources = "C:/Users/user/Desktop/Pygame App/app_resources/sound_resources/"
width,height = 400,400
size = (width,height)
elapsed_seconds = 0
def quit_game():
pygame.quit()
sys.exit("System exit.")
class GetSource:
def background(self,image):
return pygame.image.load(image_resources + image).convert()
def player(self,image):
return pygame.image.load(image_resources + image).convert_alpha()
class Wall(pygame.sprite.Sprite):
def __init__(self,color,x,y,width,height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width,height))
self.image.fill(pygame.color.Color(color))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class Player(pygame.sprite.Sprite):
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_resources + image).convert_alpha()
self.rect = self.image.get_rect()
class Coin(pygame.sprite.Sprite):
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_resources + image).convert_alpha()
self.rect = self.image.get_rect()
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PyGame App")
background = GetSource().background("bg_solid_black_square.jpg")
player = GetSource().player("ball_blue.png")
player_dimension = player.get_width()
x,y = width/2-player_dimension,height/2-player_dimension
movex,movey = 0,0
walls = pygame.sprite.Group()
players = pygame.sprite.Group()
coins = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
wall_1 = Wall("white", 0, 0, width, 5)
wall_2 = Wall("white", 0, 0, 5, height)
wall_3 = Wall("white", 0, height-5, width, 5)
wall_4 = Wall("white", width-5, 0, 5, height)
player = Player("ball_blue.png")
coin = Coin("coin.png")
walls.add(wall_1,wall_2,wall_3,wall_4)
players.add(player)
coins.add(coin)
all_sprites.add(wall_1,wall_2,wall_3,wall_4,player)
while True:
time.sleep(0.01)
elapsed_seconds += 0.01
collide_list_1 = pygame.sprite.spritecollideany(wall_1,players)
collide_list_2 = pygame.sprite.spritecollideany(wall_2,players)
collide_list_3 = pygame.sprite.spritecollideany(wall_3,players)
collide_list_4 = pygame.sprite.spritecollideany(wall_4,players)
for event in pygame.event.get():
if event.type == QUIT:
quit_game()
if event.type == KEYDOWN:
if event.key == K_q:
quit_game()
elif event.key == K_a:
movex = -1
elif event.key == K_d:
movex = 1
elif event.key == K_w:
movey = -1
elif event.key == K_s:
movey = 1
if event.type == KEYUP:
if event.key == K_a or event.key == K_d:
movex = 0
if event.key == K_w or event.key == K_s:
movey = 0
if collide_list_1 != None:
movey = 0
y += 1
if collide_list_2 != None:
movex = 0
x += 1
if collide_list_3 != None:
movey = 0
y -= 1
if collide_list_4 != None:
movex = 0
x -= 1
else:
x += movex
y += movey
player.rect.x = x
player.rect.y = y
coin.rect.x = random.randint(0,width)
coin.rect.y = random.randint(0,height)
screen.blit(background, (0,0))
if elapsed_seconds % 4 == 0:
coins.draw(screen)
coins.update()
all_sprites.draw(screen)
all_sprites.update()
pygame.display.update()
As you can see, I am increasing the "elapsed_seconds" variable every frame by the time a wait, in order the regulate frames per second, then check if it is a multiple of 4. But the thing is, when I monitored the "elapsed_seconds" variable, it never actually becomes 4. It generally goes around at "2,9998999128999" and stuff. I tried;
elapsed_seconds = math.floor(elapsed_seconds)
but that is no good as well. So, how can I render this coin at every set time interval?
EDIT: I want the sprites not to be flashing on the screen, I want them to be staying where they are after the "certin amount of time" is passed. So it should look as if it moved, after that "certain amount of time"! Thanks.
Firstly, pygame.time.get_ticks() will return elapsed milliseconds since your game started. Your method is not accurate as it does not take into account the time spent executing your game loop.
You could just track the elapsed time since you last added a coin. Then:
ticks = pygame.time.get_ticks()
if ticks - last_coin_ticks > 1000: # new coin once per second
last_coin_ticks = ticks
# add a new coin
Im trying to call moveleft method but there is no movement. i pass the distance of the character and this should be updated but its not. Any ideas?
import pygame, sys
from pygame.locals import *
pygame.init()
pygame.font.init()
width,height=(842,595)
window = pygame.display.set_mode((width,height),0,32)
pygame.display.set_caption("game!")
speedX=3
movingX =0
clock= pygame.time.Clock()
man = pygame.image.load("man.png")
target= pygame.image.load("target.png")
x = 100
y = height-300
def name(name=""):
myfont = pygame.font.SysFont(None, 15)
label = myfont.render(name, 1, (255,255,0))
result=window.blit(label, (100, 100))
pygame.display.update()
return name
def moveleft(distanceX):
movingX =0
speedX =0
x=0
while True:
pygame.display.update()
ticks=clock.tick(25)
time_passedSeconds=ticks/1000.0
distanceX = time_passeSeconds*speedX
movingX+=distanceX
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key ==K_LEFT:
x+=distanceX
window.blit(man, (x,y))
return movingX
name("werodo!")
moveleft(5)
pygame.display.update()
You draw the character at (x, y). The only time you change x is here:
elif event.type==KEYDOWN:
if event.key ==K_LEFT:
x+=distanceX
What is distanceX? It changes every iteration of the loop:
distanceX = time_passeSeconds*speedX
Yet you only assign speedX once at the start of the function:
speedX = 0
So, you're always moving by 0. Change speedX to 50 and see what happens.