This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Pygame: problems with shooting in Space Invaders
(1 answer)
Closed 1 year ago.
code:
import pygame
import sys
from pygame.locals import *
count = 0
moving = False
def blast1():
blast.y -= bl
def player_animation():
global player_speed
player.x = player_speed
pygame.init()
running = True
clock = pygame.time.Clock()
bl = 1
player_speed = 1
player = pygame.Rect(250, 450, 50, 50)
blast = pygame.Rect(player.x, player.y , 10, 10)
screen = pygame.display.set_mode((500, 500))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
player_animation()
blast1()
screen.fill((255, 255, 255)) #color
pygame.draw.ellipse(screen, [0, 0, 255], player)
pygame.draw.ellipse(screen, [0, 255, 0], blast)
keys=pygame.key.get_pressed()
if keys[K_LEFT] and player.x != -4 :
player_speed -= 5
if keys[K_RIGHT] and player.x != 451:
player_speed += 5
pygame.display.flip()
clock.tick(30)
blast.x = player.x
pygame.quit()
My objective is pretty simple. I want to create a ball that you can move to the right and left. Then I want to create a bullet that is fired from the position of the "player". I'm having some trouble with this, I don't know why but when I declare the position of the bullet blast = pygame.Rect(player.x, player.y , 10, 10) only the y position works. The x position is somehow in the middle of the screen instead of on the player. How can I fix this?
The line
blast = pygame.Rect(player.x, player.y , 10, 10)
assigns a Rect to blast, with the position of the player at this moment. This blast will stay still until you edit its position. You only change the y position here:
blast.y -= bl
But you don't update the x position when you launch the bullet. You could do this like that:
def launch_blast(): # call this function when you create the bullet.
# At this point in the program, just call it at the beginning.
blast.x = player.x + player.width / 2 - blast.width / 2
def blast1():
blast.y -= bl
To launch several bullets, you can use this code:
import pygame
from pygame.locals import *
pygame.init()
class Bullet:
def __init__(self):
self.rect = Rect(player.rect.x - 5 + player.rect.width / 2, player.rect.y , 10, 10)
def move(self):
self.rect.y -= 10 # move up
pygame.draw.ellipse(screen, [0, 255, 0], self.rect) # draw on screen
class Player:
def __init__(self):
self.rect = pygame.Rect(250, 450, 50, 50)
def move(self):
# move
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
self.rect.x -= 5
if keys[K_RIGHT]:
self.rect.x += 5
# don't go out of the screen
self.rect.x = min(max(self.rect.x, 0), 500 - self.rect.width)
# draw on screen
pygame.draw.ellipse(screen, [0, 0, 255], self.rect)
player = Player()
bullets = []
clock = pygame.time.Clock()
screen = pygame.display.set_mode((500, 500))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN and event.key == K_SPACE:
bullets.append(Bullet()) # generate a new bullet when space pressed
screen.fill((255, 255, 255)) # white
for bullet in bullets: # draw each bullet generated
bullet.move()
if bullet.rect.x < bullet.rect.height: # if out of the screen,
bullets.remove(bullet) # then remove it
player.move() # draw the player
pygame.display.flip()
clock.tick(30)
Related
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()
So recently I have been trying to make my first big game but I'm stuck on the shooting phase. Basically, my problem is I want to make it so that I can shoot multiple bullets and move around while doing so, but I can't seem to figure it out.
Code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
playerX = 5
playerY = 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bulletX = playerX
bulletY = playerY
#End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
keyPressed = pygame.key.get_pressed()
#Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
#End of Controls
#Shooting
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
Bullet = pygame.draw.rect(screen, red, (bulletX+35,bulletY + 60,10,25))
bulletY = bulletY + 1
pygame.display.update()
Here is what i meant by classes:
import pygame
import Bullet
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Shooter Game!")
# Variables
playerX = 5
playerY = 5
black = (0, 0, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
clicking = False
bulletX = playerX
bulletY = playerY
bullets = []
newBullet = False
# End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("100x100_logo.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100, 100))
screen.blit(player1, (playerX, playerY))
keyPressed = pygame.key.get_pressed()
# Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
# End of Controls
# Shooting
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
bullets.append(Bullet.Bullet(bulletX + 35, bulletY + 60))
for i in range(len(bullets)):
bullets[i].draw(screen, (255, 0, 0))
bullets[i].move(1)
print(len(bullets))
pygame.display.update()
Thats your main code. There is still a bug where there is no cooldown so multiple bullets are created consecutively when holding the mouse button.
import pygame
class Bullet:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, win, colour):
pygame.draw.rect(win, colour, (self.x, self.y, 10, 25))
def move(self, speed):
self.y += speed
and thats the bullet class to create multiple instances
See How do I stop more than 1 bullet firing at once? and How can i shoot a bullet with space bar?.
You need to manage the bullets in a list:
bullets = []
Add a new bullet to the list when the mouse click is detected. Use pygame.Rect objects to represent the bullets. The events must be handled in the event loop:
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
Move the bullets in a loop. Remove the bullets from the list, when they when they move off the screen. See How to remove items from a list while iterating?:
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
Draw all the bullets in the list in another loop:
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
Complete example:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
playerX, playerY = 5, 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bullets = []
#End Of Variables#
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
keyPressed = pygame.key.get_pressed()
playerX += keyPressed[pygame.K_d] - keyPressed[pygame.K_a]
playerY += keyPressed[pygame.K_s] - keyPressed[pygame.K_w]
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
pygame.display.update()
pygame.quit()
exit()
This question already has answers here:
How does this algorithm make the character jump in pygame?
(1 answer)
How can I do a double jump in pygame?
(1 answer)
jumping too fast?
(1 answer)
Closed 1 year ago.
I'm doing own game with the help Python. I need to make a jumping to my sprite can jump. However, my sprite can't jump. If my program had 1 and more mistakes, my game wouldn't able to work. Please, find mistake to my sprite can jump. Here's my program:
from pygame.locals import *
import pygame
import os
import random
WIDTH = 800
HEIGHT = 600
FPS = 60
usr_y = 400
# Задаем цвета
GREEN = (75, 0, 130)
BLUE = (255, 20, 147)
# Создаем игру и окно
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Mini-games by Latypov Vildan 10'a' Class")
clock = pygame.time.Clock()
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH - 360
self.rect.centery = HEIGHT - 200
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
def print_text(message, x, y, font_color = (0, 0, 0), font_type = 'фыы.ttf', font_size = 30):
font_type = pygame.font.Font(font_type, font_size)
text = font_type.render(message, True, font_color)
screen.blit(text, (x, y))
print_text('Hi', 250, 250)
jump = False
counter = -30
def make():
global usr_y, counter, jump
if counter >= -30:
usr_y-= counter / 2.5
counter -= 1
else:
counter = 30
jump = False
# Цикл игры
running = True
while running:
# Держим цикл на правильной скорости
clock.tick(FPS)
# Ввод процесса (события)
for event in pygame.event.get():
# check for closing window
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
elif event.key == K_SPACE:
jump = True
if jump:
make()
# Обновление
all_sprites.update()
# Рендеринг
screen.fill(BLUE)
all_sprites.draw(screen)
# После отрисовки всего, переворачиваем экран
pygame.display.flip()
pygame.quit()
It is a matter of Indentation. You have to do the jump in the application loop. The state jump is set once when the event occurs. However, the jumping needs to be animated in consecutive frames.
Your event loop is mixed up and you must change the coordinate of the player object instead of usr_y:
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH - 360
self.rect.centery = HEIGHT - 200
self.y = self.rect.y # <--- floating point y coordinate
def update(self):
self.rect.y = round(self.y) # <--- update player rectangle
self.speedx = 0
# [...]
jump = False
counter = 30
def make():
global counter, jump
if counter >= -30:
player.y -= counter / 2.5 # <--- change player.y
counter -= 1
else:
counter = 30
jump = False
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.key == K_SPACE:
jump = True
# INDENTATION
#<----------|
if jump:
make()
# [...]
for some reason when I collide with the enemy it randomly spawns elsewhere which is all fine but when I un-collide the enemy goes back to its original position
here is the full code down below. If you run this code see what happens. Im looking for the red block to spawn in a random other location when the blue box collides with it.
import pygame
import random
# places where enemies can spawn (2 to make it simple at first)
enemy_locations = [100, 200]
pygame.init()
# clock
clock = pygame.time.Clock()
# frames per second
fps = 30
# colors
background_color = (255, 255, 255)
player_color = (0, 0, 255)
enemy_color = (255, 0, 0)
# width and height of screen
width = 1000
height = 800
# screen
screen = pygame.display.set_mode((width, height))
# x, y coordinates player
player_x = 300
player_y = 300
# ememy x, y coordinates
enemy_x = random.choice(enemy_locations)
enemy_y = random.choice(enemy_locations)
# new x, y coordinates for enemy player
new_x = random.choice(enemy_locations)
new_y = random.choice(enemy_locations)
# draw player
def draw():
enemy_rect = pygame.Rect(enemy_x, enemy_y, 25, 25)
player_rect = pygame.Rect(player_x, player_y, 25, 25)
if player_rect.colliderect(enemy_rect):
enemy = pygame.draw.rect(screen, enemy_color, (new_x, new_y, 25, 25))
else:
enemy = pygame.draw.rect(screen, enemy_color, enemy_rect)
player = pygame.draw.rect(screen, player_color, player_rect)
# pygame loop (always include)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# controls for player object
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= 10
if event.key == pygame.K_RIGHT:
player_x += 10
if event.key == pygame.K_UP:
player_y -= 10
if event.key == pygame.K_DOWN:
player_y += 10
draw()
pygame.display.update()
screen.fill(background_color)
clock.tick(fps)
The draw method explicitly states to draw enemy rect either in the initial point or in some ONE random point. The random point is selected only once - during the start of an application. You should set the random point every time there is a collision in a draw method, e.g.
if player_rect.colliderect(enemy_rect):
enemy_x = random.choice(enemy_locations)
enemy_y = random.choice(enemy_locations)
You have to create a new random enemy position when the player collides with the enemy
if player_rect.colliderect(enemy_rect):
enemy_x = random.choice(enemy_locations)
enemy_y = random.choice(enemy_locations)
Use the global statement, to interpreted the variables enemy_x and enemy_y as global. With the statement global it is possible to write to variables in the global namespace within a function:
global enemy_x, enemy_y
Function draw:
def draw():
global enemy_x, enemy_y
enemy_rect = pygame.Rect(enemy_x, enemy_y, 25, 25)
player_rect = pygame.Rect(player_x, player_y, 25, 25)
if player_rect.colliderect(enemy_rect):
enemy_x = random.choice(enemy_locations)
enemy_y = random.choice(enemy_locations)
enemy = pygame.draw.rect(screen, enemy_color, enemy_rect)
player = pygame.draw.rect(screen, player_color, player_rect)
As others have said you either need to add more "locations" to the list or better, use random.randint(), and also enemy's coordinates does not "get random"(or updated in any way) after every collision, but only once when you initialize them.
I added new function get_new_coord() which will return the random number(I use these limits so the enemy won't go off the screen), which gets called once for every coordinate after each collision.
Also I moved player_rect and enemy_rect outside of the loop, and now draw() returns enemy_rect so it can stay updated if collision occurs.
This is a quick fix to your code, you should consider using Classes. And of course if you want to do so, I could help you with transforming the code.
import pygame
import random
# places where enemies can spawn (2 to make it simple at first)
enemy_locations = [100, 200]
pygame.init()
# clock
clock = pygame.time.Clock()
# frames per second
fps = 30
# colors
background_color = (255, 255, 255)
player_color = (0, 0, 255)
enemy_color = (255, 0, 0)
# width and height of screen
width = 1000
height = 800
# screen
screen = pygame.display.set_mode((width, height))
# x, y coordinates player
player_x = 300
player_y = 300
# ememy x, y coordinates
enemy_x = random.choice(enemy_locations)
enemy_y = random.choice(enemy_locations)
# new x, y coordinates for enemy player
new_x = random.choice(enemy_locations)
new_y = random.choice(enemy_locations)
def get_new_coord():
return random.randint(0, 800-25)
# draw player
def draw(player_rect, enemy_rect):
screen.fill(background_color)
if player_rect.colliderect(enemy_rect):
enemy_rect = pygame.Rect(get_new_coord(), get_new_coord(), 25, 25)
enemy = pygame.draw.rect(screen, enemy_color, enemy_rect)
else:
enemy = pygame.draw.rect(screen, enemy_color, enemy_rect)
player = pygame.draw.rect(screen, player_color, player_rect)
pygame.display.update()
return enemy_rect
# pygame loop (always include)
running = True
enemy_rect = pygame.Rect(enemy_x, enemy_y, 25, 25)
player_rect = pygame.Rect(player_x, player_y, 25, 25)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# controls for player object
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_rect.x -= 10
if event.key == pygame.K_RIGHT:
player_rect.x += 10
if event.key == pygame.K_UP:
player_rect.y -= 10
if event.key == pygame.K_DOWN:
player_rect.y += 10
enemy_rect = draw(player_rect, enemy_rect)
clock.tick(fps)
I know that is not really a blank screen, but now I have a problem.
It takes forever to load the game.
Everytime I close the window, it fully loads????
If u need code, ask.
please help
You've to crate an PlayerClass object and you've to add the pygame.sprite.Sprite to a pygame.sprite.Group:
player = PlayerClass('player_1_0.png', [5, 0])
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
In the main loop you've to updat the position of the player (player.move()). Clear the display, draw the sprites and update the display (e.g. by pygame.display.update()):
while running:
# [...]
player.move()
screen.fill([255, 255, 255])
all_sprites.draw(screen)
pygame.display.update()
Working example:
import pygame, sys
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()
class PlayerClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location = [0,0]):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.speed = speed
self.angle = 90
def move(self):
global points, score_text
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0]
if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
points = points + 1
score_text = font.render(str(points), 1, (0, 0, 0))
player = PlayerClass('player_1_0.png', [5, 0])
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
player.move()
screen.fill([127, 127, 127])
all_sprites.draw(screen)
pygame.display.update()
pygame.quit()