Reputation: 25
I am creating a space type game for a school competition. Im going to use stars (white dots) moving outwards to give an effect of moving in space. Next I would check to see if a star's x cords are less than the centre or the screen (move the star to the left) and if the x coordinate is larger (Move to the right). However, I can't seem to make more than one instance of the stars class.Here is an image of the kind of thing I want . Help is very appreciated.
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((1200, 800))
caption = pygame.display.set_caption("sapce game")
screen.fill((56, 56, 56))
white = (255, 255, 255)
class Stars:
def __init__(self):
self.x = random.randint(0, 600)
self.y = random.randint(0, 400)
self.pos = (self.x, self.y)
def move(self):
pygame.draw.circle(screen, white, (self.x, self.y), 4)
self.y -= 1
self.x -= 2
screen.fill((56, 56, 56))
pygame.draw.circle(screen, white, (self.x, self.y), 4)
pygame.display.update()
s = Stars()
run = True
while run:
s.move()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
quit()
Upvotes: 2
Views: 262
Reputation: 210968
First of all you have to put scrre.fill
and pygame.display.update()
in the main application loop. Remove this calls from Stars.move
:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
quit()
screen.fill((56, 56, 56))
s.move()
pygame.display.update()
Note, you want to clear the display once, then draw all the stars and finally update the display.
Create a list of stars:
star_list = []
for i in range(10):
star_list.append(Stars())
Move and draw the stars in a loop:
run = True
while run:
# [...]
screen.fill((56, 56, 56))
for s in star_list:
s.move()
pygame.display.update()
Example code:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((1200, 800))
caption = pygame.display.set_caption("sapce game")
screen.fill((56, 56, 56))
white = (255, 255, 255)
class Stars:
def __init__(self):
self.x = random.randint(0, 600)
self.y = random.randint(0, 400)
self.dx, self.dy = 0, 0
while self.dx == 0:
self.dx = random.randint(-2, 2)
while self.dy == 0:
self.dy = random.randint(-2, 2)
self.pos = (self.x, self.y)
def move(self):
self.x += self.dx
self.y += self.dy
if self.x <= 0 or self.x >= 1200:
self.dx = -self.dx
if self.y <= 0 or self.y >= 800:
self.dy = -self.dy
pygame.draw.circle(screen, white, (self.x, self.y), 4)
star_list = []
for i in range(10):
star_list.append(Stars())
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
quit()
screen.fill((56, 56, 56))
for s in star_list:
s.move()
pygame.display.update()
Upvotes: 1