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()
Related
import pygame
import blocks
import random
class World:
def __init__(self):
self.tile_list = []
TILESIZE = 20
minStoneHeight = 1
maxStoneHeight = 8
x = 0
y = 0
height = 10
width = 100
for x in range(width):
minHeight = height - 1
maxHeight = height + 2
height = random.randrange(minHeight, maxHeight)
minStoneSpawnDistance = height - minStoneHeight
maxStoneSpawnDistance = height - maxStoneHeight
totalStoneSpawnDistance = random.randrange(minStoneHeight, maxStoneHeight)
for y in range(height):
if y < totalStoneSpawnDistance:
t = blocks.stoneBlock(x*20, y*20 + 100)
self.tile_list.append(t)
else:
t = blocks.dirtBlock(x*20, y*20 + 100)
self.tile_list.append(t)
if(totalStoneSpawnDistance == height):
t = blocks.stoneBlock(x*20, y*20 + 100)
self.tile_list.append(t)
else:
self.tile_list.append(t)
t = blocks.stoneBlock(x*20, y*20+100)
def draw(self, screen):
for tile in self.tile_list:
tile.draw(screen)
This is the code I use for procedural terrain generation in pygame. I adapted it from a script in C# for Unity. The issue is that pygames grid orgin is in the topleft and unitys is at bottom left. I was wondering how I would get my terrain to not be upside down?
It s a matter of Indentation. You maust move the player in the application loop rather than the event loop:
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
currentPlayerImg = playerImgBack
playerYSpeed = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
playerYSpeed = 0
#<--| INDENTATION
playerX += playerXSpeed
playerY += playerYSpeed
screen.blit(bgImg, (0, 0))
screen.blit(currentPlayerImg, (playerX, playerY))
pygame.display.update()
I want to make it so when my character touches the "v" block the game quits. What I tried was to find all blocks that are "v" and put them in the list. If player colliderect with any in list of "v" game will quit.
I think this should work although it does not seem to be working. Whenever I run it when I touch the "v" block nothing happens.
Here is my code
import pygame
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
WINDOW_SIZE = (600, 400)
pygame.display.set_caption("Game")
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32)
display = pygame.Surface((300, 200))
player_image = pygame.image.load("Jacques clone-1.png (1).png").convert()
player_image.set_colorkey((255,255,255))
location = [50, 50]
#boolean for movement
moving_right = False
moving_left = False
scroll = [0, 0]
Stay_right = True
game_map1 = """
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
xx----------x----------------------------------------
----------vvvv---------------------xxx----------------
---------xooo----------------------------------------
xxxxxxxxxooooxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
""".splitlines()
game_map = [list(lst) for lst in game_map1]
tl = {}
tl["v"] = spike_img = pygame.image.load('dirt.png')
tl["o"] = dirt_img = pygame.image.load('grass.png')
tl["x"] = grass_img = pygame.image.load('grass.png')
player_rect = pygame.Rect(50, 50, 25, 25)
momentum = 0
air_timer = 0
#adding tiles list that are hit for movement
def collision_test(rect, tiles):
hit_list = []
for tile in tiles:
if rect.colliderect(tile):
hit_list.append(tile)
#print(hit_list)
return hit_list
def move(rect, movement, tiles):
collision_types = {'top': False, 'bottom': False, 'right': False, 'left': False}
rect.x += movement[0]
hit_list = collision_test(rect, tiles)
for tile in hit_list:
if movement[0] > 0:
rect.right = tile.left
collision_types['right'] = True
elif movement[0] < 0:
rect.left = tile.right
collision_types['left'] = True
rect.y += movement[1]
hit_list = collision_test(rect, tiles)
for tile in hit_list:
if movement[1] > 0:
rect.bottom = tile.top
collision_types['bottom'] = True
elif movement[1] < 0:
rect.top = tile.bottom
collision_types['top'] = True
return rect, collision_types
run = True
while run:
display.fill((146, 244, 255))
scroll[0] += (player_rect.x - scroll[0] - 130)
tile_rects = []
y = 0
for line_of_symbols in game_map:
x = 0
for symbol in line_of_symbols:
if symbol in tl:
display.blit(tl[symbol], (x * 16 - scroll[0], y * 16 - scroll[1]))
if symbol != "-":
tile_rects.append(pygame.Rect(x * 16, y * 16, 16, 16))
x += 1
y += 1
list_ofspike = []
y2 = 0
for lineofsymbols in game_map:
x2 = 0
for symbols in lineofsymbols:
if symbols == "v":
list_ofspike.append(pygame.Rect(x2 * 16, y2 * 16, 16, 16))
x2 += 1
y2 += 1
for spike in list_ofspike:
if player_rect.colliderect(spike):
pygame.quit()
player_movement = [0, 0]
if moving_right:
player_movement[0] += 2
if moving_left:
player_movement[0] -= 2
player_movement[1] += momentum
momentum += 0.3
if momentum > 3:
momentum = 3
player_rect, collisions = move(player_rect, player_movement, tile_rects)
if collisions['bottom']:
air_timer = 0
momentum = 0
else:
air_timer += 1
if Stay_right:
display.blit(player_image, (player_rect.x - scroll[0], player_rect.y - scroll[1]))
else:
display.blit(pygame.transform.flip(player_image, 1, 0 ),(player_rect.x - scroll[0], player_rect.y - scroll[1]))
for event in pygame.event.get():
if event.type == QUIT:
run = False
if event.type == KEYDOWN:
if event.key == K_RIGHT:
moving_right = True
Stay_right = True
if event.key == K_LEFT:
moving_left = True
Stay_right = False
if event.key == K_SPACE:
if air_timer < 6:
momentum = -5
if event.type == KEYUP:
if event.key == K_RIGHT:
moving_right = False
if event.key == K_LEFT:
moving_left = False
screen.blit(pygame.transform.scale(display, (WINDOW_SIZE)), (0, 0))
pygame.display.update()
clock.tick(60)
pygame.quit()
You do not detect a collision with the spikes, because your collision detection works too perfectly.
When you move the player then you ensure, that the player does not intersect any object, thus the player does not intersect a spike, too.
You have to test if the player touches a spike. Increase the player rectangle by 1 in direction and use the increased rectangle to do the collision test with the spikes:
while run:
# [...]
test_rect = pygame.Rect(player_rect.left-1, player_rect.top-1,
player_rect.width+2, player_rect.height+2)
for spike in list_ofspike:
if test_rect.colliderect(spike):
pygame.quit()
# [...]
So im new at pygame and coding my first project- a side scrolling shooter. The issue im having is with my bullets: when i press the space key, some of the bullets will show up but there are times when nothing happens, and no bullets spawn when i jump. Not quite sure how to go about fixing this issue- any ideas would be greatly appreciated.
Code is as follows:
import pygame
import math, random, sys, pygame.mixer
from pygame.locals import *
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 8192)
pygame.mixer.init()
jump = False
jump_offset = 0
jump_height = 250
k = pygame.key.get_pressed()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
def do_jumping():
global jump_height
global jump
global jump_offset
if jump:
jump_offset += 3
if jump_offset >= jump_height:
jump = False
elif jump_offset > 0 and jump == False:
jump_offset -= 3
#Defining colours
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
#Window Settings
w = 1280
h = 720
half_w = w /2
half_h = h /2
AREA = w*h
#Initialising the window
pygame.init()
display = pygame.display.set_mode((w,h)) #Sets the size of the window
pygame.display.set_caption("Cattleman") #Sets the title of the window
Clock = pygame.time.Clock() #clockspeed for the game ie. 60fps
FPS = 600
#pygame.mouse.set_visible(True) #Allows the mouse to be shown in the game window.
background = pygame.image.load("background.png").convert()
backgroundWidth, backgroundHeight = background.get_rect().size
stageWidth = backgroundWidth*2 #sets the area which the player can move in
stagePosX = 0 #Records position of stage as the player moves
startScrollPosX = half_w
circleRadius = 25
circlePosX = circleRadius
playerPosX = circleRadius
playerPosY = 602
playerVelocityX = 0
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
bullets = []
bulletSprite = pygame.image.load("Bullet1.png").convert_alpha()
bulletSprite = pygame.transform.scale(bulletSprite, (20,10))
#Sounds
#gunSounds = ["pew1.wav", "pew2.wav", "pew3.wav", "pew4.wav"]
#SOUNDS
shot = pygame.mixer.Sound("pew1.wav")
#------------------------MAIN PROGRAM LOOP------------------------#
while True:
events()
do_jumping()
k = pygame.key.get_pressed()
if k[K_RIGHT]:
playerVelocityX = 2 #Moves the player right
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_LEFT]:
playerVelocityX = -2 #Moves the player left
playersprite = pygame.image.load("player_spriteL2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_UP] and jump == False and jump_offset == 0:
jump = True
if not k[K_RIGHT] and not k[K_LEFT]:
playerVelocityX = 0 #If no input detected, the player does not move
if k[K_SPACE]:
for event in pygame.event.get():
bullets.append([circlePosX-100, playerPosY-20])
shot.play()
playerPosX += playerVelocityX
if playerPosX > stageWidth - circleRadius-25: playerPosX = stageWidth - circleRadius-25 #Checks if the player trie to go past the right boundary
if playerPosX < circleRadius+55:playerPosX = circleRadius+55 #Checks if the player tries to go past the left boundary
if playerPosX < startScrollPosX: circlePosX = playerPosX
elif playerPosX > stageWidth - startScrollPosX: circlePosX = playerPosX - stageWidth + w
else:
circlePosX = startScrollPosX
stagePosX += -playerVelocityX
for b in range(len(bullets)):
bullets[b][0] -= 3
for bullet in bullets[:]:
if bullet[0] < 0:
bullets.remove(bullet)
rel_x = stagePosX % backgroundWidth
display.blit(background,(rel_x - backgroundWidth, 0))
if rel_x < w:
display.blit(background, (rel_x, 0))
for bullet in bullets:
display.blit(bulletSprite, pygame.Rect(bullet[0], bullet[1], 0, 0,))
#pygame.draw.circle(display,WHITE, (int(circlePosX),playerPosY - jump_offset), circleRadius, 0)
display.blit(playersprite, (int(circlePosX-80),playerPosY-100 - jump_offset))
pygame.display.update()
Clock.tick(FPS)
display.fill(BLACK)
I have done this in my code that leaves multiple balls similar like bullets :
class Bullet():
def __init__(self, x, y):
# self.image = pygame.image.load("SingleBullet.png")
self.image = pygame.image.load("ball.png")
self.image = pygame.transform.scale(self.image, (25, 25))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.is_alive = True
# --------------------
def update(self):
self.rect.y -= 15
if self.rect.y < 0:
self.is_alive = False
# --------------------
def draw(self, screen):
screen.blit(self.image, self.rect.topleft)
for getting keyboard :
def event_handler(self, event):
if event.type == KEYDOWN:
if event.key == K_LEFT:
self.move_x = -5
elif event.key == K_RIGHT:
self.move_x = 5
elif event.key == K_SPACE:
if len(self.shots) < self.max_shots:
self.shots.append(Bullet(self.rect.centerx, self.rect.top))
if event.type == KEYUP:
if event.key in (K_LEFT, K_RIGHT):
self.move_x = 0
I've written a game where the main character can shoot daggers on mouseclick, and move around with the up, down, left, and right keys. THe character also follows the mouse around. I have added the villains into the screen, however I am unsure of how to make a rect for my daggers. My intention is to use colliderect when the dagger and the villain collide; and recode the villain to disappear, and code it off of the screen and have him reappear. However; before I can do this I need to make a rect for my daggers; which I, for whatever reason cannot find out.
This is the portion of the code in which I define my rects variables and rect:
xPlayer = 200
yPlayer = 275
dxPlayer = 0
dyPlayer = 0
playerPosition = (200,275)
daggers = []
angle = 0
villainStartx = 800
villainStarty = random.randrange(0, 550)
villainSpeed = -10
villainWidth = 100
villainHeight = 100
villainTWOStartx = 800
villainTWOStarty = random.randrange(0, 550)
villainTWOSpeed = -20
villainTWOWidth = 100
villainTWOHeight = 100
villainRect = pygame.Rect(villainStartx, villainStarty, villainWidth, villainHeight)
villainTWORect = pygame.Rect(villainTWOStartx, villainTWOStarty, villainTWOWidth, villainTWOHeight)
player = pygame.Rect(xPlayer, yPlayer, 160, 146)
This is the portion of my code where I draw the daggers to the screen on mouseclick:
filtered_daggers = []
for shot in daggers:
if not outOfBounds(shot[0]):
filtered_daggers.append(shot)
daggers = filtered_daggers
for shot in daggers:
shot[0][0] += shot[1][0]
shot[0][1] += shot[1][1]
screen.blit(cloudSky, (0,0))
screen.blit(playerRotate, playerPositionNew)
for shot in daggers:
x, y = shot[0]
screen.blit(shot[2], shot[0])
And if necessary, below is my entire code:
#Import the necessary modules
import pygame
import sys
import os
import math
import random
#Initialize pygame
pygame.init()
# Set the size for the surface (screen)
screenSize = (900,600)
screen = pygame.display.set_mode((screenSize),0)
# Set the caption for the screen
pygame.display.set_caption("Neverland")
#Define Colours
WHITE = (255,255,255)
BLUE = (0,0,255)
BLACK = (0,0,0)
GRAY = (128, 128, 128)
MAROON = (128, 0, 0)
NAVYBLUE = (0, 0, 128)
OLIVE = (128, 128, 0)
PURPLE = (128, 0, 128)
TEAL = (0,128,128)
PINK = (226,132,164)
MUTEDBLUE = (155,182,203)
PLUM = (221,160,221)
#Clock Setup
clock = pygame.time.Clock()
#Load Images
peterPlayer = pygame.image.load('pixelPirateOne.png')
nightBackground = pygame.image.load ('skyTwo_1.png')
daggerPlayer = pygame.image.load('daggerPlayer.png')
captHook = pygame.image.load('/pixelCaptainHook.png')
cloudSky = pygame.image.load('cloudSky.png')
pirateTwo = pygame.image.load('pixelPirateTwo.png')
#Define All Variables
xPlayer = 200
yPlayer = 275
dxPlayer = 0
dyPlayer = 0
playerPosition = (200,275)
accuracyShot = [0,0]
daggers = []
angle = 0
healthValue=194
villainStartx = 800
villainStarty = random.randrange(0, 550)
villainSpeed = -10
villainWidth = 100
villainHeight = 100
villainTWOStartx = 800
villainTWOStarty = random.randrange(0, 550)
villainTWOSpeed = -20
villainTWOWidth = 100
villainTWOHeight = 100
villainRect = pygame.Rect(villainStartx, villainStarty, villainWidth, villainHeight)
villainTWORect = pygame.Rect(villainTWOStartx, villainTWOStarty, villainTWOWidth, villainTWOHeight)
player = pygame.Rect(xPlayer, yPlayer, 160, 146)
#dagger = pygame.Rect(
def quitGame():
pygame.quit()
sys.exit()
def outOfBounds(shot):
return shot[0] < -40 or shot[0] > 900 or shot[1] < -40 or shot[1] > 600
def villains(x,y):
screen.blit(captHook, (x,y))
def villainsTwo(x,y):
screen.blit(pirateTwo, (x,y))
go = True
while go:
#Quit Game
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitGame()
#Move Player
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer -= 25
elif event.key == pygame.K_RIGHT:
dxPlayer += 25
elif event.key == pygame.K_UP:
dyPlayer -= 25
elif event.key == pygame.K_DOWN:
dyPlayer += 25
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dxPlayer = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dyPlayer = 0
elif event.type == pygame.MOUSEBUTTONDOWN:
mousePosition = pygame.mouse.get_pos()
velx = math.cos(angle)*20
vely = math.sin(angle)*20
daggerImage = pygame.transform.rotate(daggerPlayer, -math.degrees(angle))
width, height = daggerImage.get_size()
daggers.append([[xPlayer,yPlayer],
[velx, vely], daggerImage])
#Update move player
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
#Learned about atan2 from --> https://docs.python.org/2/library/math.html
#Allows To Rotate Player With Mouse
mousePosition = pygame.mouse.get_pos()
rise = mousePosition[1] - player.centery
run = mousePosition[0] - player.centerx
angle = math.atan2(rise, run)
playerRotate = pygame.transform.rotate(peterPlayer, -math.degrees(angle))
playerPositionNew = (xPlayer-playerRotate.get_rect().width/2, yPlayer-playerRotate.get_rect().height/2)
player = playerRotate.get_rect(center=player.center)
#Learned about cos and sin in python from --> https://docs.python.org/2/library/math.html
#Draw daggers to screen
filtered_daggers = []
for shot in daggers:
if not outOfBounds(shot[0]):
filtered_daggers.append(shot)
daggers = filtered_daggers
for shot in daggers:
shot[0][0] += shot[1][0]
shot[0][1] += shot[1][1]
screen.blit(cloudSky, (0,0))
screen.blit(playerRotate, playerPositionNew)
for shot in daggers:
x, y = shot[0]
screen.blit(shot[2], shot[0])
if villainRect.colliderect(dagger):
print(dagger)
pygame.display.update()
clock.tick(30)
#Drawing the villains at random
villains(villainStartx, villainStarty)
villainStartx +=villainSpeed
if villainStartx < -50:
villainStartx = random.randrange(800,900)
villainStarty = random.randrange(0,550)
villainsTwo(villainTWOStartx, villainTWOStarty)
villainTWOStartx +=villainTWOSpeed
if villainTWOStartx < -50:
villainTWOStartx = random.randrange(800,1000)
villainTWOStarty = random.randrange(0,550)
#Redrawing villain after collision- To be finished after defining dagger rect
pygame.display.update()
You can use an image for your dagger, and then get the rect properties from it:
dagger = pygame.image.load("dagger.png")
#you can then blit it on the screen:
screen.blit(dagger, (corrd1, corrd2))
dagger_rect = dagger.get_rect() #get the location of the dagger
if villianRect.colliderect(dagger_rect):
#do something
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()