This question already has answers here:
Why is nothing drawn in PyGame at all?
(2 answers)
Why is my PyGame application not running at all?
(2 answers)
Closed 2 years ago.
I'm making an side scroller arcade game in python where you control a rocket
and have to avoid the asteroids coming from right to left. My problem is that my asteroids do not appear on the screen. Help is very much appreciated.
import pygame as pg
import numpy as np
from pygame.locals import *
from random import *
#Make a first "game" which is actually the menu
res = (1000,800)
screen = pg.display.set_mode(res)
pg.display.set_caption('Rocket game')
black = (0,0,0)
white = (255,255,255)
backgroundmenu = pg.image.load("menuscreen.jpg")
pg.init()
running1 = True
while running1:
pg.event.pump()
keys = pg.key.get_pressed()
if keys[pg.K_1]:
running1 = False
running2 = True
elif keys[pg.K_2]:
running1 = False
running2 = False
for event in pg.event.get():
if event.type == pg.QUIT:
running1 = False
screen.blit(backgroundmenu,(0,0))
pg.display.flip()
pg.quit()
pg.init()
#Setup screen and define colors
res = (1000,800)
screen = pg.display.set_mode(res)
pg.display.set_caption('Rocket game')
#pg.image.load("space.jpg")
black = (0,0,0)
white = (255,255,255)
background1 = pg.image.load("space.jpg").convert()
background2 = pg.image.load("space.jpg").convert()
background3 = pg.image.load("space.jpg").convert()
#screen.blit(background1,(0,0))
x_back = 0
screenwidth = 1000
#Initialize variables and clock
vx = 0
vy = 0
x = 200
y = 600
t0 = 0.001*pg.time.get_ticks()
maxdt = 0.5
#Load rocket and asteroids
rocketgif = pg.image.load("rocket.gif")
rocketimg = pg.transform.scale(rocketgif, (100,100))
asteroidgif = pg.image.load("Asteroid.gif")
asteroidimg = pg.transform.scale(asteroidgif, (75,75))
#Load music
pg.mixer.music.load('gamesound.mp3')
pg.mixer.music.set_endevent(pg.constants.USEREVENT)
pg.mixer.music.play()
#clock = pg.time.Clock()
#Generate random asteroids
Nasteroid = 5
x_ast = 999
dx = 5
i = 0
asteroidpos_y= []
while i<Nasteroid:
y = randint(0,800)
asteroidpos_y.append(y)
i = i + 1
#Start game loop
running2 = True
while running2:
t = 0.001*pg.time.get_ticks()
dt = min(t-t0,maxdt)
i = 0
pg.event.pump()
while i<Nasteroid:
x_ast -= dx
y = y
screen.blit(asteroidimg,(x_ast,asteroidpos_y[i-1]))
i = i + 1
for event in pg.event.get():
if event.type == pg.QUIT: #Quit using red cross button
running2 = False
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
running2 = False #Quit using key combination
elif event.type == pg.KEYDOWN: #Make user control rocket movement
#and stop if key is released.
if event.key == pg.K_LEFT:
vx = -8
elif event.key == pg.K_RIGHT:
vx = 8
elif event.key == pg.K_UP:
vy = -8
elif event.key == pg.K_DOWN:
vy = 8
elif event.type == pg.KEYUP:
if event.key == pg.K_LEFT:
vx = 0
elif event.key == pg.K_RIGHT:
vx = 0
elif event.key == pg.K_UP:
vy = 0
elif event.key == pg.K_DOWN:
vy = 0
elif event.type == pg.constants.USEREVENT:
pg.mixer.music.load("gamesound.mp3")
pg.mixer.music.play()
#Make the screen scroll behind the rocket to make it "move" (3x the same background behind eachother)
screen.blit(background1,(x_back,0))
screen.blit(background2,(x_back - screenwidth,0))
screen.blit(background3,(x_back - (2*screenwidth),0))
x_back = x_back - 1
if x_back == screenwidth:
x_back = 0
#Update the position of the rocket. If the rocket hits the edges the game stops.
x = x + vx
y = y + vy
"""if x <= 0 or x >=100:
running2 = False
if y <= 0 or y >=800:
running2 = False"""
pg.event.pump()
screen.blit(rocketimg,(x,y))
pg.display.flip()
pg.quit()
Related
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)
Closed 7 months ago.
So basically I'm making an escape room game. In the game, you have to interact with a desk and a key would spawn on the map. Then you would interact with the key and pick it up and it would go on top of your head, and you are free to take it anywhere to escape the escape room. Now the problem I'm having, is I'm able to interact with the desk, and the collision works. But the key doesn't spawn.
Here is my code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
#VARIABLES
velocity = 1
yellow = (255,255,0)
clock = pygame.time.Clock()
white = (255,255,255)
blue = (0,0,255)
black = (0,0,0)
brown = (110,38,14)
x = 300
y = 300
#VARIABLES
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
def Room():
global Player
global x
global y
screen.fill(black)
Player = pygame.draw.rect(screen,blue,(x,y,50,50))
wall_1 = pygame.draw.rect(screen,white,(10,50,20,500))
wall_2 = pygame.draw.rect(screen,white,(10,30,580,20))
wall_3 = pygame.draw.rect(screen,white,(570,40,20,520))
wall_4 = pygame.draw.rect(screen,white,(10,540,580,20))
if Player.colliderect(wall_1):
x = x + 70
if Player.colliderect(wall_2):
y = y + 70
if Player.colliderect(wall_3):
x = x - 70
if Player.colliderect(wall_4):
y = y - 70
def Movement():
global velocity
global x
global y
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
x = x - velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
x = x + velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
y = y - velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN or event.key == ord('s'):
y = y + velocity
def Text():
font = pygame.font.Font("freesansbold.ttf",15)
interact = font.render("E To Interact!",True, (255,255,255))
screen.blit(interact,(75,275))
def FirstKey():
global Player
global x
global y
KeyX = 300
KeyY = 400
key = pygame.draw.rect(screen,yellow,(KeyX,KeyY,15,15))
if Player.colliderect(key) == True:
if key[K_e]:
KeyX = x
KeyY = y - 35
def Desk():
global x
global velocity
Desk = pygame.draw.rect(screen,brown,(75,300,20,60))
if Player.colliderect(Desk) == True:
velocity = 0
Text()
keys = pygame.key.get_pressed()
if keys[K_e]:
x = 300
velocity = 1
FirstKey()
else:
None
#Function Calls#
Room()
Movement()
Desk()
#Function Calls#
pygame.display.update()
#FPS#
clock.tick(120)
#FPS#
I would appreciate an answer as well as an explanation on what I'm doing wrong.
P.S. I'm using the latest version of Python(3.10.5) and the Pygame module.
Try to encapsulate things in a class,
instead of calling the functions secuentially, as it happens in the game, split the functions on what they need to do, and call them on every cycle.
So you need to check for input, check for collisions, check inventary, check states, draw the objects, and so on.
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
#VARIABLES
velocity = 1
yellow = (255,255,0)
clock = pygame.time.Clock()
white = (255,255,255)
blue = (0,0,255)
black = (0,0,0)
brown = (110,38,14)
#VARIABLES
class mygame():
x = 300
y = 300
velocity = 1
state = 'idle'
draw_key = False
def draw_objects(self):
screen.fill(black)
self.player = pygame.draw.rect(screen,blue,(self.x,self.y,50,50))
self.wall_1 = pygame.draw.rect(screen,white,(10,50,20,500))
self.wall_2 = pygame.draw.rect(screen,white,(10,30,580,20))
self.wall_3 = pygame.draw.rect(screen,white,(570,40,20,520))
self.wall_4 = pygame.draw.rect(screen,white,(10,540,580,20))
self.desk = pygame.draw.rect(screen,brown,(75,300,20,60))
if self.draw_key:
self.key = pygame.draw.rect(screen,yellow,(200,200,20,20))
def check_collisions(self):
if self.player.colliderect(self.desk) == True:
font = pygame.font.Font("freesansbold.ttf",15)
interact = font.render("E To Interact!",True, (255,255,255))
screen.blit(interact,(75,275))
if self.player.colliderect(self.wall_1) == True:
self.x = 10
if self.player.colliderect(self.wall_2) == True:
self.y = 10
if self.player.colliderect(self.wall_3) == True:
self.x = 570
if self.player.colliderect(self.wall_4) == True:
self.y = 540
def check_buttons(self):
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
self.state = 'interacting'
self.draw_key = False
if event.key == pygame.K_w or event.key == pygame.K_UP:
self.state = 'up'
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
self.state = 'down'
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
self.state = 'left'
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
self.state = 'right'
if event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
if event.type == pygame.KEYUP:
self.state = 'idle'
def move(self):
if self.state == 'up':
self.y -= self.velocity
if self.state == 'down':
self.y += self.velocity
if self.state == 'left':
self.x -= self.velocity
if self.state == 'right':
self.x += self.velocity
if self.state == 'idle':
pass
if self.state == 'interacting':
self.draw_key = True
def play(self):
while True:
self.draw_objects()
self.check_buttons()
self.check_collisions()
self.move()
pygame.display.update()
clock.tick(120)
game = mygame()
game.play()
This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
Hi guys I started learning pygames, i started playing snake and came to an obstacle. I don't know how to make a function for my snake to grow when it eats an apple, I've looked at a lot of snake codes and I'm still not sure how to do it. I dont have idea how to do that, I realy hope you can give mi some advice to improve my game.
your help would do me good, thanks
import pygame
import random
import math
# Init
pygame.init()
# Screen
screen = pygame.display.set_mode((800, 600))
# Caption and Icon
pygame.display.set_caption("Snake Game")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Background
background = pygame.image.load('background.jpg')
# Snake
snakeImg = pygame.image.load('snake.png')
snakeX = 300
snakeY = 300
snakeX_change = 0
snakeY_change = 0
# Apple
appleImg = pygame.image.load('apple.png')
appleX = random.randint(32, 768)
appleY = random.randint(32, 568)
def snake(x, y):
screen.blit(snakeImg, (x, y))
def apple(x, y):
screen.blit(appleImg, (x, y))
# Collision
def isCollision(appleX, appleY, snaketX, snakeY):
distance = distance = math.sqrt(math.pow(appleX - snakeX, 2) + (math.pow(appleY - snakeY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
score = 0
running = True
while running:
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Snake Movment
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snakeX_change = -0.1
snakeY_change = 0
if event.key == pygame.K_UP:
snakeY_change = -0.1
snakeX_change = 0
if event.key == pygame.K_RIGHT:
snakeX_change = 0.1
snakeY_change = 0
if event.key == pygame.K_DOWN:
snakeY_change = 0.1
snakeX_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
snakeX_change = -0.1
if event.key == pygame.K_RIGHT:
snakeX_change = 0.1
if event.key == pygame.K_DOWN:
snakeY_change = 0.1
if event.key == pygame.K_UP:
snakeY_change = -0.1
snakeX += snakeX_change
snakeY += snakeY_change
if snakeX <= 0:
snakeX = 0
elif snakeX >= 770:
snakeX = 770
if snakeY <= 0:
snakeY = 0
elif snakeY >= 570:
snakeY = 570
# Collision
collision = isCollision(appleX, appleY, snakeX, snakeY)
if collision:
score += 1
print(score)
appleX = random.randint(32, 768)
appleY = random.randint(32, 568)
snake(snakeX, snakeY)
apple(appleX, appleY)
pygame.display.flip()
When snake's head collide with the apple, add 1 element inside snake's body, you can interprete snake's body as a list of elements, containing tuples perhaps.
This question already has answers here:
Pygame collision with masks
(1 answer)
How can I rotate my hitbox with my rotating and moving car in pygame?
(1 answer)
python pygame mask collision [closed]
(1 answer)
Pygame mask collision
(1 answer)
Closed 2 years ago.
I am currently developing a 2d pinball game in python using the pygame library, I opted for the mask collision detection, here is a link to a post where it's well explained:
2D Collision detection for Pinball Game
I think I did everything but it's not working as wanted .
Here is my code for the physiscs of the ball:
from math import *
from Constants import *
def Getcolor(ballx,bally,screen,resources):
screen.blit(resources["CollisionMain"], (220, 0))
color=screen.get_at((ballx,bally))
colore=color[1]
return colore
def UpdateBall(ball,color):
ballx=ball[1][0]
bally=ball[1][1]
lastpos = ball[1][0], ball[1][1]
velocity=ball[2]
if -FRICTION_BALL <= velocity <= FRICTION_BALL :
velocity = 0
else:
velocity += FRICTION_BALL if velocity < 0 else -FRICTION_BALL
ball[2] = velocity
ball[1][0] += velocity
vectorx = sin(color / 255 * 2 * pi)
vectory = cos(color / 255 * 2 * pi)
if ballx+Ball_width<screen_width:
ballx=screen_width-Ball_width
if (bally+Ball_len)>screen_lenght:
bally=screen_lenght-Ball_len
#ball[1][1] -= 10
else:
if color == 255:
ball[1][1] += Gravity
else:
ball[1][0],ball[1][1]=lastpos
ball[1][0] += vectorx
ball[1][1] += vectory
def DrawBall(screen,ball,resources):
screen.blit(ball[0],(ball[1][0],ball[1][1]))
and here is my game engine code:
import pygame
import sys
from pygame.locals import *
from Constants import *
from ball import *
def Init():
pygame.init()
screen = pygame.display.set_mode((screen_width,screen_lenght))
pygame.display.set_caption('Supinball')
pygame.key.set_repeat(150,150)
pygame.mixer.init(44100, -16, 2, 1024)
return screen
def LoadResources():
resources= dict()
resources["MainLayer"] = pygame.image.load("resources/images/main_layer.png")
resources["Ball"] = pygame.image.load("resources/images/Ball.png")
resources["CollisionMain"] = pygame.image.load("resources/images/collision_main.png")
resources["CollisionSpec"] = pygame.image.load("resources/images/collision_special.png")
resources["Rflipper"] = pygame.image.load("resources/images/right_flipper.png")
resources["Lflipper"] = pygame.image.load("resources/images/left_flipper.png")
resources["Spring"] = pygame.image.load("resources/images/spring.png")
resources["Music"] = pygame.mixer.Sound("resources/sounds/music.ogg")
resources["Coin"] = pygame.mixer.Sound("resources/sounds/Coin.wav")
resources["Hit"] = pygame.mixer.Sound("resources/sounds/hit.wav")
resources["Tilted"] = pygame.mixer.Sound("resources/sounds/tilted.wav")
resources["GameOver"] = pygame.mixer.Sound("resources/sounds/GameOver.ogg")
resources["Font"] = pygame.font.Font('resources/Vdj.ttf', 30)
return resources
def GameLoop(screen,resources):
gameRunning = True
ball = [resources["Ball"],[300,20],0]
fpsClock = pygame.time.Clock()
while gameRunning:
ev = GetEvent(ball)
gameRunning = ev[GAME_RUNNING]
#resources["Music"].play(-1)
color=Getcolor(int(ball[1][0]), int(ball[1][1]), screen, resources)
print(color)
UpdateBall(ball,color)
#screen.blit(resources["MainLayer"], (0,0))
DrawBall(screen,ball,resources)
pygame.display.update()
fpsClock.tick(FPS)
def GetEvent(ball):
ev = [True,False,False,False,False,False,False,False,False,False]
for event in pygame.event.get():
if event.type == QUIT:
ev[GAME_RUNNING] = False
if event.type == MOUSEBUTTONUP:
mousepos = pygame.mouse.get_pos()
ball[1][0],ball[1][1]=mousepos
if event.type == KEYDOWN:
if event.key == K_DOWN:#compress spring
ev[KEY_DOWN] = True
if event.key == K_UP: #relax spring
ev[KEY_UP] = True
if event.key == K_LSHIFT: #left flipper
ev[KEY_LSHIFT] = True
if event.key == K_RSHIFT: #right flipper
ev[KEY_RSHIFT] = True
if event.type == KEYUP:
if event.key == K_q: #insert coin
ev[KEY_Q] = True
if event.key == K_SPACE: #launch ball
ev[KEY_SPACE] = True
if event.key == K_LEFT:#tilt left
ev[KEY_LEFT] = True
if event.key == K_RIGHT:#tilt right
ev[KEY_RIGHT] = True
if event.key == K_p:#pause
ev[KEY_P] = True
return ev
def DestroyGame():
pygame.quit()
and the constants code:
#screen
screen_lenght = 256
screen_width= 600
#fps
FPS=100
#events
GAME_RUNNING = 0
KEY_Q = 1
KEY_DOWN = 2
KEY_UP = 3
KEY_SPACE = 4
KEY_LSHIFT = 5
KEY_RSHIFT = 6
KEY_RIGHT = 7
KEY_LEFT = 8
KEY_P = 9
#ball physics
FRICTION_BALL=0.5
Gravity=1.9
Ball_width=11
Ball_len=9
But when I run it the ball is not colliding perfectly it's only colliding with the darkest spots and going through the light grey colors
If you look at this picture
the ball shouldn't be able to go through the bumpers but it does—I am sorry if my code is garbage, I am a beginner. :)
Here is a youtube link to a kinda working version of what I want to achieve: https://www.youtube.com/watch?v=SXegewcVx8A
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
image = https://www.dropbox.com/s/nx6yzx8ddhu36m7/car.png?dl=0
when I rotate(press Left or Right Key) while I accelerate(press up key) my car moves in a strange way.
Also there is something wrong with the accelerating
speed doesn't increase the way I expect it to be. I think the speed should be increasing as the time goes on but it doesn't...
can anyone please help me by trying the code?
thank you
here's my code:
import pygame,math
pygame.init()
display_width = 1200
display_height = 800
white = (255,255,255)
black = (0,0,0)
car_image = pygame.image.load('car.png')
role_model = pygame.image.load('role_model.png')
clock = pygame.time.Clock()
FPS = 30
screen = pygame.display.set_mode([display_width,display_height])
car_width = 76
car_height = 154
def rotate(image, rect, angle):
rot_image = pygame.transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center=rect.center)
return rot_image,rot_rect
def carRotationPos(angle):
x=1*math.cos(math.radians(angle-90))
y=1*math.sin(math.radians(angle-90))
return x,y
def gameloop():
running = True
angle = 0
angle_change = 0
changeX = 0
changeY=0
x=0
y=0
change_x=0
change_y=0
speed = 1
speed_change = 1
rect = role_model.get_rect()
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
angle_change = 5
#changeX=0
#changeY=0
if event.key == pygame.K_RIGHT:
angle_change = -5
#changeX=0
#changeY=0
if event.key == pygame.K_UP:
#angle_change =0
changeX=-x
changeY=y
speed_change = speed_change**2 +1
if event.key == pygame.K_DOWN:
#angle_change =0
changeX=x
changeY=-y
speed_change = -(speed_change**2 + 1)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
angle_change = 0
if event.key == pygame.K_RIGHT:
angle_change = 0
if event.key == pygame.K_UP:
changeX=0
changeY=0
speed = 1
speed_change=1
if event.key == pygame.K_DOWN:
changeX=0
changeY=0
speed = 1
speed_change=1
if angle == -360 or angle == 360:
angle = 0
angle+=angle_change
change_x+=changeX
change_y+=changeY
speed+=speed_change
if speed > 20:
speed = 20
screen.fill(white)
x,y=carRotationPos(angle)
x=round(x,5)*speed
y=round(y,5)*speed
rot_image,rot_rect=rotate(car_image,rect,angle)
rot_rect=list(rot_rect)
rot_rect1=rot_rect[0]+display_width/2-car_width/2
rot_rect2=rot_rect[1]+display_height/2-car_height/2
rot_rect1+=change_x
rot_rect2+=change_y
del rot_rect[0]
del rot_rect[1]
rot_rect.insert(0,rot_rect1)
rot_rect.insert(1,rot_rect2)
screen.blit(rot_image,rot_rect)
pygame.display.update()
clock.tick(FPS)
gameloop()
pygame.quit()
When you press UP/DOWN then you set changeX = x , changeY = y and car moves using changeX, changeY.
When you press LEFT/DOWN then you change angle and calculate new x, y but this doesn't change changeX, changeY so car still moves the same direction (using the same changeX, changeY).
EDIT: now it turns correctly when you move forward but still there is problem with backward acceleration. I'm working on it.
I use moving_up/moving_down to update changeX and changeY when car is moving - so it use current angle and x, y to change direction.
EDIT: acceleration problem solve: you have to use speed_change = speed_change**2 + 1 when you go UP and DOWN. You don't need negative value when you go DOWN because x_change = x, y_change = -y will change direction.
New code:
BTW: I add ESC to quit program and BACKSPACE to center car on screen (reset position)
import pygame
import math
# --- constants --- (UPPER_CASE)
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
DISPLAY_WIDTH = 1200
DISPLAY_HEIGHT = 800
FPS = 30
CAR_WIDTH = 76
CAR_HEIGHT = 154
# --- functions --- (lower_case)
def rotate(image, rect, angle):
rot_image = pygame.transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center=rect.center)
return rot_image, rot_rect
def rotate_car_pos(angle):
x = math.cos(math.radians(angle-90))
y = math.sin(math.radians(angle-90))
return x, y
def gameloop():
# start position - screen center - so I don't have to add center later
car_rect = role_model.get_rect(center=screen_rect.center)
# ---
angle = 0
angle_change = 0
x = 0
y = 0
x_change = 0
y_change = 0
speed = 0
speed_change = 0
# ---
pos_x = 0
pos_y = 0
#---
moving_up = False
moving_down = False
#recalculate = True
running = True
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_BACKSPACE:
# reset position [for test only]
pos_x = 0
pos_y = 0
angle = 0
elif event.key == pygame.K_LEFT:
angle_change = 5
elif event.key == pygame.K_RIGHT:
angle_change = -5
elif event.key == pygame.K_UP:
moving_up = True
x_change = -x
y_change = y
speed_change = speed_change**2 + 1
elif event.key == pygame.K_DOWN:
moving_down = True
x_change = x
y_change = -y
speed_change = speed_change**2 + 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
angle_change = 0
elif event.key == pygame.K_RIGHT:
angle_change = 0
elif event.key == pygame.K_UP:
moving_up = False
x_change = 0
y_change = 0
speed = 0
speed_change = 0
elif event.key == pygame.K_DOWN:
moving_down = False
x_change = 0
y_change = 0
speed = 0
speed_change = 0
# --- updates ---
# - pos -
if x_change or y_change:
pos_x += x_change
pos_y += y_change
print('[DEBUG]: pos_x, pos_y: ', pos_x, pos_y)
# - angle -
# rotate olny when moving
#if moving_up or moving_down:
if angle_change:
angle += angle_change
while angle > 360:
angle -= 360
while angle < -360:
angle += 360
print('[DEBUG]: angle: ', angle)
# - speed -
if speed_change:
speed += speed_change
if speed > 20:
speed = 20
print('[DEBUG]: speed: ', speed)
# - others -
x, y = rotate_car_pos(angle)
x = round(x*speed, 5)
y = round(y*speed, 5)
print('[DEBUG]: x, y: ', x, y)
if moving_up:
x_change = -x
y_change = y
elif moving_down:
x_change = x
y_change = -y
#if recalculate:
rot_image, rot_rect = rotate(car_image, car_rect, angle)
rot_rect.centerx += pos_x
rot_rect.centery += pos_y
# --- draws ---
screen.fill(WHITE)
screen.blit(rot_image, rot_rect)
pygame.display.update()
# --- clock ---
clock.tick(FPS)
# --- main ---
pygame.init()
car_image = pygame.image.load('car.png')
role_model = pygame.image.load('car.png')
screen = pygame.display.set_mode( (DISPLAY_WIDTH, DISPLAY_HEIGHT) )
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
gameloop()
pygame.quit()
I am making an side-scroller arcade game where you control a rocket and have to avoid waves of asteroids coming from the right to the left. The problem I have is that the wave only comes one time. My loop to do another wave does not work. Help is very much appreciated. I have added my code below:
#Make a first "game" which is actually the menu
res = (1000,800)
screen = pg.display.set_mode(res)
pg.display.set_caption('Rocket game')
black = (0,0,0)
white = (255,255,255)
backgroundmenu = pg.image.load("menuscreen.jpg")
pg.init()
pg.mixer.music.load('gamesound.mp3')
pg.mixer.music.set_endevent(pg.constants.USEREVENT)
pg.mixer.music.play()
running1 = True
while running1:
pg.event.pump()
keys = pg.key.get_pressed()
if keys[pg.K_1]:
running1 = False
running2 = True
elif keys[pg.K_2]:
running1 = False
running2 = False
for event in pg.event.get():
if event.type == pg.QUIT:
running1 = False
screen.blit(backgroundmenu,(0,0))
pg.display.flip()
pg.quit()
pg.init()
#Setup screen and define colors
res = (1000,800)
screen = pg.display.set_mode(res)
pg.display.set_caption('Rocket game')
#pg.image.load("space.jpg")
black = (0,0,0)
white = (255,255,255)
background1 = pg.image.load("space.jpg").convert()
background2 = pg.image.load("space.jpg").convert()
background3 = pg.image.load("space.jpg").convert()
#screen.blit(background1,(0,0))
x_back = 0
screenwidth = 1000
#Initialize variables and clock
vx = 0
vy = 0
x = 200
y = 600
t0 = 0.001*pg.time.get_ticks()
maxdt = 0.5
#Load rocket and asteroids
rocketgif = pg.image.load("rocket.gif")
rocketimg = pg.transform.scale(rocketgif, (100,100))
asteroidgif = pg.image.load("Asteroid.gif")
asteroidimg = pg.transform.scale(asteroidgif, (75,75))
#Load music
pg.mixer.music.load('gamesound.mp3')
pg.mixer.music.set_endevent(pg.constants.USEREVENT)
pg.mixer.music.play()
#clock = pg.time.Clock()
#Generate random asteroids at right of the screen (x =999) and at a random y position (between 0 and 800)
Nasteroid = 4
x_ast = 999
dx = 5
i = 0
asteroidpos_y= []
while i<Nasteroid:
y = randint(0,800)
asteroidpos_y.append(y)
i = i + 1
#Start game loop
running2 = True
while running2:
t = 0.001*pg.time.get_ticks()
dt = min(t-t0,maxdt)
for event in pg.event.get():
if event.type == pg.QUIT: #Quit using red cross button
running2 = False
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
running2 = False #Quit using key combination
elif event.type == pg.KEYDOWN: #Make user control rocket movement
#and stop if key is released.
if event.key == pg.K_LEFT:
vx = -8
elif event.key == pg.K_RIGHT:
vx = 8
elif event.key == pg.K_UP:
vy = -8
elif event.key == pg.K_DOWN:
vy = 8
elif event.type == pg.KEYUP:
if event.key == pg.K_LEFT:
vx = 0
elif event.key == pg.K_RIGHT:
vx = 0
elif event.key == pg.K_UP:
vy = 0
elif event.key == pg.K_DOWN:
vy = 0
elif event.type == pg.constants.USEREVENT:
pg.mixer.music.load("gamesound.mp3")
pg.mixer.music.play()
#Make the screen scroll behind the rocket to make it "move" (3x the same background behind eachother)
screen.blit(background1,(x_back,0))
screen.blit(background2,(x_back - screenwidth,0))
screen.blit(background3,(x_back - (2*screenwidth),0))
x_back = x_back - 1
if x_back == screenwidth:
x_back = 0
i = 0
pg.event.pump() #Flush event queue
#Update position of the rocket
x = x + vx
y = y + vy
"""if x <= 0 or x >=100:
running2 = False
if y <= 0 or y >=800:
running2 = False"""
#Calculate distance between rocket and asteroid
sx = abs(x - x_ast)
sy = abs(y - asteroidpos_y[i-1])
sxy = sqrt(sx**2 + sy**2)
#Wave of asteroids
while i<Nasteroid:
x_ast -= dx
y = y
screen.blit(asteroidimg,(x_ast,asteroidpos_y[i-1]))
i = i + 1
#Check if rocket is in touching distance of an asteroid. If hit, play explosion sound and exit game
if sx <= 75 and sy <= 75 or sxy <= 75:
pg.mixer.music.load('explosion.mp3')
pg.mixer.music.set_endevent(pg.constants.USEREVENT)
pg.mixer.music.play()
time.sleep(1)
running2 = False
else:
while i<Nasteroid:
y = randint(0,800)
asteroidpos_y.append(y)
i = i + 1
while i<Nasteroid:
x_ast -= dx
y = y
screen.blit(asteroidimg,(x_ast,asteroidpos_y[i-1]))
i = i + 1
pg.event.pump()
screen.blit(rocketimg,(x,y))
pg.display.flip()
pg.quit()
I managed to solve this by using the following code:
import pygame as pg
from random import *
import time
pg.init()
scr = pg.display.set_mode((1000,800))
img2 = pg.image.load("asteroid.gif")
img = pg.transform.scale(img2, (75,75))
imgrect = img.get_rect()
#list with asteroid postitions and speeds
xast = []
yast = []
vx = []
vy = []
t = 0.001*pg.time.get_ticks()
tast = t
t0 = t
dtast = 0.5
running = True
while running:
t = t = 0.001*pg.time.get_ticks()
dt = t - t0
if dt >0.:
t0 = t
for i in range(len(xast)):
xast[i] = xast[i] + vx[i] * dt
yast[i] = yast[i] + vy[i] * dt
#Create new asteroids every dtast seconds
if t - tast >= dtast:
xast.append(999.)
yast.append(float(randint(0,799)))
vx.append(-50)
vy.append(float(randint(-1,1)))
tast = t
#Draw frame
scr.fill((0,0,0))
for i in range(len(xast)):
imgrect.center = (xast[i],yast[i])
scr.blit(img,imgrect)
pg.display.flip()
pg.quit()