This question already has answers here:
Shooting a bullet in pygame in the direction of mouse
(2 answers)
How to create bullets in pygame? [duplicate]
(2 answers)
How do I stop more than 1 bullet firing at once?
(1 answer)
Moving forward after angle change. Pygame
(1 answer)
How can you rotate the sprite and shoot the bullets towards the mouse position?
(1 answer)
Closed 2 years ago.
What I am trying to do is make so that the bullets that spawn when I click move up towards the top of the screen. I am new to programming, so when I tried to look for help elsewhere I found nothing that I could understand. below is my code so far
#!/usr/bin/env python3
#from sys import exit
import sys, pygame, pygame.mixer
from pygame.locals import *
import pygame
from pygame.locals import *
from sys import exit
bkgrnd_img = "cory_in_the_house.png" #change name and picture
mouse_image_filename = "Good_Cory.png"
projectile_thing = "good_bullet"
pygame.init()
screen = pygame.display.set_mode((800,650), 0, 32)
background = pygame.ima`enter code
here`ge.load(bkgrnd_img).convert()
pygame.display.set_caption("i dont think ur ready")
mouse_cursor =
pygame.image.load(mouse_image_filename).convert_alpha()
clock = pygame.time.Clock()
speed = 250
screen.blit(background, (0,0))
while True:
for event in pygame.event.get(): #goes through stored
pygame events(?)
if event.type == pygame.QUIT: #checks if user presses x button
exit()
if (cory_health == 0):
break
x, y = pygame.mouse.get_pos()
x -= mouse_cursor.get_width()/2
y -= mouse_cursor.get_height()/2
screen.blit(mouse_cursor, (x, y))
if(event.type == pygame.MOUSEBUTTONDOWN):
print("The mouse was clicked")
x, y = pygame.mouse.get_pos()
x -= mouse_cursor.get_width()/2
y -= mouse_cursor.get_height()/2
screen.blit(mouse_cursor, (x, y))
screen.blit(pygame.image.load('good_bullet.jpg'), (x, y))
pygame.display.update()
Thanks in advance
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
My plan was to make circles spawn at regular intervals and go towards my mouse at a certain speed. I got the first part of this working. Although, when a new sprite is spawned, the previous one stops moving and so on as if they were not getting updated anymore. I am trying to make them all move simultaneously towards my mouse instead of just the new one.
I am fairly new, so feel free to add any other input on flaws you see.
Here is the part of code relevant to this:
# Enemy
class Enemy (pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.x = 0
self.y = 0
self.speed = 2
self.change_x = 0
self.change_y = 0
self.update()
def update(self):
dx, dy = (pygame.mouse.get_pos()[0]+8) - self.x, (pygame.mouse.get_pos()[1]+8) - self.y
dist = math.hypot(dx, dy)
dx, dy = dx / dist, dy / dist
self.change_x += dx * self.speed
self.change_y += dy * self.speed
def make_enemies():
enemy = Enemy()
enemy.change_x = random.randrange(0, 800)
enemy.change_y = random.randrange(0, 600)
enemy.speed = 2
return enemy
enemy_list = []
spawn = make_enemies()
enemy_list.append(spawn)
add_enemy = pygame.USEREVENT + 1
pygame.time.set_timer(add_enemy, 1000)
# Game loop
done = False
while not done:
# RGB - RED, GREEN, BLUE (0-255)
screen.fill(BACKGROUND)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == add_enemy:
spawn = make_enemies()
enemy_list.append(spawn)
for enemy in enemy_list:
enemy.x = enemy.change_x
enemy.y = enemy.change_y
pygame.draw.circle (screen, WHITE, [enemy.change_x, enemy.change_y], BALL_SIZE)
enemy.update()
clock.tick(100)
pygame.display.update()
You are calling enemy.update() outside of your for loop. So, only the last enemy in the list is updating. Moving it inside your for loop should take care of it.
for enemy in enemy_list:
enemy.x = enemy.change_x
enemy.y = enemy.change_y
pygame.draw.circle (screen, WHITE, [enemy.change_x,
enemy.change_y], BALL_SIZE)
enemy.update()
so I am making a game where this character(a circle) has to pop balloons falling from the sky to get points. But I am having trouble making my character move in the first place.
Code:
import pygame
from pygame.locals import *
pygame.init()
#Variables
white = (255, 255, 255)
blue = (70,130,180)
black = (0,0,0)
x = 400
y = 450
#screen stuff
screenwidth = 800
screenheight = 600
screen = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption("Balloon Game!")
#end of screen stuff
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
# Draw Character
character = pygame.draw.circle(screen, (blue), (x, y), 50, 50)
#End of Drawing Character
# Making Arrow Keys
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
character.x -= 1
if keyPressed[pygame.K_RIGHT]:
character.x += 1
pygame.display.update()
I would appreciate it if someone could tell me why it wasn't
working with a fixed code. Thanks!
pygame.draw.circle returns the bounding rectangle (pygame.Rect object) of the circle. However the center of the circle is always (x, y). Therefore you need to change x instead of character.x:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
x -= 1
if keyPressed[pygame.K_RIGHT]:
x += 1
This code can even be simplified:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
x += (keyPressed[pygame.K_RIGHT] - keyPressed[pygame.K_LEFT])
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
I am currently programming a pygame game where you move a spaceship around the screen. Currently, I have got to the part where I made the spaceship and tried to make it move. However, when I try to move the spaceship around, the spaceship doesn't move!
Here is my current code:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 500))
screen.fill((255, 255, 255))
class Spaceship(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
self.image = pygame.transform.scale(self.image, (175, 175))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.rect.center = (self.x, self.y)
spaceship = Spaceship(screen, 400, 400)
screen.blit(spaceship.image, spaceship.rect)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y += 5
elif key[pygame.K_s]:
spaceship.y -= 5
spaceship.update()
pygame.display.update()
What is wrong with my current code?
You have to draw the Sprties in the application loop:
clock = pygame.time.Clock()
running = True
while running:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y -= 5
elif key[pygame.K_s]:
spaceship.y += 5
# update the position of the object
spaceship.update()
# clear the display
screen.fill((255, 255, 255))
# draw the object
screen.blit(spaceship.image, spaceship.rect)
# update the display
pygame.display.update()
# limit frames per second
clock.tick(60)
The typical PyGame application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage
Furthermore I suggest to use a pygame.sprite.Group:
pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The former delegates the to the update mehtod of the contained pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update():
Calls the update() method on all Sprites in the Group [...]
The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]
spaceship = Spaceship(screen, 400, 400)
all_sprites = pygame.sprite.Group()
all_sprites.add(spaceship)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 5
elif key[pygame.K_d]:
spaceship.x += 5
elif key[pygame.K_w]:
spaceship.y += 5
elif key[pygame.K_s]:
spaceship.y -= 5
all_sprites.update()
screen.fill((255, 255, 255))
all_sprites.draw(screen)
pygame.display.update()
a youtube video told me to put what I've already put.
https://www.youtube.com/watch?v=bVx2nhB0t1o&feature=youtu.be
My window opens, but just stays at a black screen. When I close the window, then I get the error message:
Traceback (most recent call last):
File "./invaders.py", line 23, in <module>
keys = pygame.key.get_pressed()
pygame.error: video system not initialized
I don't really understand why this is happening and any help would be much appreciated.
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Space Invaders")
x = 50
y = 50
width = 30
height = 30
vel = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
win.fill(0)
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
Your code is mixed-up. Generally PyGame applications have a "main loop" which handles the event loop, processes any user input, and then re-draws the screen.
Your code has all of these elements, but a whole block of code is not inside the main loop, it's only executed after the window has been closed. You need to be careful of the placement and indentation.
This code below is basically your exact code, re-arranged with some tweaks.
import pygame
BLACK = ( 0, 0, 0 ) # colours
RED = (255, 0, 0 )
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Space Invaders")
x = 50
y = 50
width = 30
height = 30
vel = 5
clock = pygame.time.Clock()
run = True
# Main loop
while run:
#pygame.time.delay(100) # <-- don't use delays like this
# handle the PyGame event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# handle user movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
# repaint the window
win.fill( BLACK )
pygame.draw.rect( win, RED, ( x, y, width, height ) )
pygame.display.update()
clock.tick( 10 ) # limit the FPS here
# main loop has ended, quit
pygame.quit()
Now the window painting, and user-input handling is now moved inside the scope of the main loop.
Also it's best not to add fixed time delays into PyGame code. Adjust the frame rate using a PyGame clock.
When I run this code it shows a blank black window and it says x is not defined.
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,500))
screen.fill((255,255,255))
#basic stuff
pygame.draw.line(screen,(0,0,0),(500,0),(500,500))
pygame.draw.rect(screen, (0,255,0), (20,50,460,420))
#pygame.draw.line(screen, (0,0,0), (500,0),(500,500))
#pygame.draw.line(screen, (0,0,0), (500,500),(0,500))
#draw
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x = int(pos[0]//20)
y = int(pos[1]//20)
j = int(x*20+20)
l = int(y*20+20)
print(x+1,' ',y+1)
if x > 2 and y > 3 and x < 24 and y < 24:
pygame.quit()
its not the color. it dose not draw any lines tough i gave the command
myfont = pygame.font.SysFont("monospace", 20)
label = myfont.render("Allameh helli 3 stock exchange group",1,0,0,0))
screen.blit(label, (30, 10))
What are my error(s) here that prevent me from making the screen white and raising that error?
You need to add this line in your while loop but not in your for loop :
screen.fill([255, 255, 255])
and this line of code outside and after the while loop:
pygame.quit()
You have not defined x nor y yet. You will need to redefine those variables, including pos to prevent the error. The error is that your if statement:
if x > 2 and y > 3 and x < 24 and y < 24:
pygame.quit()
was not in line with the one above it. The program then could not see what x or y was, raising the error. Your while loop is fine by the way. I hope this helps you!