How to change the snake head direction in pygame? - python

I want it so that when i press my left arrow key (for example) the snake head will move towards the left. I have been using the pygame.display.flip command for that but that would mean if i keep clicking my left key it continually flips left and right.
if event.key == K_LEFT:
block = pygame.transform.flip(block, True, False)
block_x -= 20
(rest of my code if it helps)
import pygame
from pygame.locals import *
def draw_block():
surface.fill((44, 250, 150))
surface.blit(block, (block_x, block_y))
pygame.display.update
def change_direction():
block = pygame.display.flip
pygame.init()
WND_RES = (800, 600)
surface = pygame.display.set_mode(WND_RES)
surface.fill((44, 250, 150))
block_x = 100
block_y = 100
block = pygame.image.load("resources/pogchamp.jpg").convert()
surface.blit(block,(block_x,block_y))
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
pass
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
block_y -= 20
draw_block()
if event.key == K_DOWN:
block_y += 20
draw_block()
if event.key == K_LEFT:
block = pygame.transform.flip(block, True, False)
block_x -= 20
draw_block()
if event.key == K_RIGHT:
block_x += 20
block = pygame.transform.flip(block, True, False)
draw_block()
elif event.type == QUIT:
running = False
pygame.display.update()

Ok, from what I've seen every time you enter the event, you flip your image like that.
if event.key == K_LEFT:
block = pygame.transform.flip(block, True, False)
block_x -= 20
draw_block()
So I added conditions to know when the head must turn right or left
if event.key == K_LEFT:
if flip_left is False and flip_right is True: ## HERE ##
block = pygame.transform.flip(block, True, False)
flip_left, flip_right = True, False ## HERE ##
block_x -= 20
draw_block()
if event.key == K_RIGHT:
if flip_right is False and flip_left == True:## HERE ##
block = pygame.transform.flip(block, True, False)
flip_left, flip_right = False, True ## HERE ##
So here is the rest of your code, I marked the changes with "## HERE ##"
import pygame
from pygame.locals import *
def draw_block():
surface.fill((44, 250, 150))
surface.blit(block, (block_x, block_y))
pygame.display.update
def change_direction():
block = pygame.display.flip
pygame.init()
WND_RES = (1080, 960)
surface = pygame.display.set_mode(WND_RES)
surface.fill((44, 250, 150))
block_x = 100
block_y = 100
block = pygame.image.load("pogchamp.jpg").convert()
surface.blit(block,(block_x,block_y))
pygame.display.update()
running = True
flip_left = False ## HERE ##
flip_right = True ## HERE ## He starts to look to the right
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
pass
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
block_y -= 20
draw_block()
if event.key == K_DOWN:
block_y += 20
draw_block()
if event.key == K_LEFT:
if flip_left is False and flip_right is True: ## HERE ##
'''when you click to look on the left, it checks if it is not
already done and if it is not it exchanges the status'''
block = pygame.transform.flip(block, True, False)
flip_left, flip_right = True, False ## HERE ##
block_x -= 20
draw_block()
if event.key == K_RIGHT:
if flip_right is False and flip_left == True: ## HERE ##
block = pygame.transform.flip(block, True, False)
flip_left, flip_right = False, True ## HERE ##
block_x += 20
draw_block()
elif event.type == QUIT:
running = False
pygame.display.update()

pygame.display.update is a function. You need the Parentheses (see Calls) to call a function:
pygame.display.update
pygame.display.update()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling 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 calling either pygame.display.update() or pygame.display.flip()
Add a variable that indicates the direction of the obejct:
direction = (1, 0)
Change the variable in the event loop depending on the key pressed:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
direction = (0, -1)
if event.key == K_DOWN:
direction = (0, 1)
if event.key == K_LEFT:
direction = (-1, 0)
block = block_left
if event.key == K_RIGHT:
direction = (1, 0)
block = block_right
Move the block in the application loop, depending on the direction:
step = 20
block_x += step * direction[0]
block_y += step * direction[1]
Minimal example:
import pygame
from pygame.locals import *
pygame.init()
WND_RES = (800, 600)
surface = pygame.display.set_mode(WND_RES)
block_x, block_y = 100, 100
# block = pygame.image.load("resources/pogchamp.jpg").convert()
block = pygame.image.load(r"C:\source\PyGameExamplesAndAnswers\resource\icon\Bird64.png")
block_right = block
block_left = pygame.transform.flip(block, True, False)
direction = (1, 0)
def draw_block():
surface.blit(block, (block_x, block_y))
clock = pygame.time.Clock()
running = True
while running:
clock.tick(10)
for event in pygame.event.get():
if event.type == KEYDOWN:
pass
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
direction = (0, -1)
if event.key == K_DOWN:
direction = (0, 1)
if event.key == K_LEFT:
block = block_left
direction = (-1, 0)
if event.key == K_RIGHT:
direction = (1, 0)
block = block_right
elif event.type == QUIT:
running = False
step = 20
block_x += step * direction[0]
block_y += step * direction[1]
surface.fill((44, 250, 150))
draw_block()
pygame.display.update()

Related

How to stop a timer in pygame

For my endscreen, I want a line that says "You survived for X seconds" but in that line, the timer continues to run after game over.
I've tried to move the timer code a bit downwards in the main loop (after the if gameover: part.) I also tried if not gameover and time_difference >= 1500: but the timer still runs.
This is my programme loop with timer:
Code is removed for now. Will re-upload in 1 to 2 months.
and endscreen code if necessary:
def gameOverScreen():
ending = 1
global run, gameover
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
For those who need it, with some help, the code now works.
#Start screen Loop
done = False
start_time = pygame.time.get_ticks()
while not done and display_instructions:
if not pygame.mixer.music.get_busy():
pygame.mixer.music.load('bgm.mp3')
pygame.mixer.music.play()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
instruction_page += 1
if instruction_page == 2:
display_instructions = False
# Set the screen background
win.fill(black)
if instruction_page == 1:
text = font.render("Instructions:", True, white)
win.blit(text, [10, 20])
text = font.render("1. Use WASD, or the Arrow Keys to move", True, white)
win.blit(text, [10, 100])
text = font.render("2. Left click to shoot", True, white)
win.blit(text, [10, 150])
text = font.render("3. Collect ammunition", True, white)
win.blit(text, [10, 200])
text = font.render("4. STAY ALIVE", True, white)
win.blit(text, [10, 250])
text = font.render("Kill or be killed", True, red)
win.blit(text, [260, 420])
text = font.render("How long can you survive?", True, red)
win.blit(text, [150, 470])
text = font.render("Click to start", True, white)
win.blit(text, [270, 600])
clock.tick(60)
pygame.display.flip()
def gameOverScreen(end_time):
seconds_survived = (end_time - start_time) // 1000
ending = 1
global run, gameover
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill(black)
timer = pygame.time.get_ticks() - now2
if ending == 1:
win.blit(endscreen.image, endscreen.rect)
time = font.render(str(seconds_survived/1000) ,1,red)
win.blit(time, (410, 600))
endtext = font.render("You survived for seconds", True, red)
win.blit(endtext, [100, 600])
kill = font.render("Kill count: " +str(killcounter), 1, red)
win.blit(kill, (280, 650))
pygame.display.flip()
clock.tick(100)
# Programme loop
run = True
gameover = False
while run:
actual_ticks = pygame.time.get_ticks()
if gameover:
now2 = now = actual_ticks
gameOverScreen(end_time)
continue
timer = actual_ticks - now2
time_difference = actual_ticks - now
if time_difference >= 1500:
newenemy = Enemy(random.randrange(50,780), random.randrange(50,780), 1 ,wall_list)
enemy_list.add(newenemy)
all_sprite_list.add(newenemy)
newenemy2 = Enemy(random.randrange(50,780), random.randrange(50,780), 1 ,wall_list)
enemy_list.add(newenemy2)
all_sprite_list.add(newenemy2)
now = actual_ticks
all_sprite_list.update()
win.fill(white)
win.blit(background.image, background.rect)
for e in enemy_list:
e.move(player)
collide = pygame.sprite.spritecollide(player, enemy_list, False)
if collide:
gameover = True
end_time = pygame.time.get_ticks()
food_collide = pygame.sprite.spritecollide(player,food_list,False)
for food in food_collide:
score += 1
bullets += 10
food_list.remove(food)
newfood = Food()
food_list.add(newfood)
all_sprite_list.add(newfood)
all_sprite_list.remove(food)
food_list.update()
all_sprite_list.update()
pygame.mixer.music.load('reload.mp3')
pygame.mixer.music.play()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.move(-2, 0)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
player.move(2, 0)
elif event.key == pygame.K_UP or event.key == ord('w'):
player.move(0, -2)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
player.move(0, 2)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.move(2, 0)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
player.move(-2, 0)
elif event.key == pygame.K_UP or event.key == ord('w'):
player.move(0, 2)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
player.move(0, -2)
elif event.type == pygame.MOUSEBUTTONDOWN:
aim_pos = event.pos
player_position = player.rect.center
bullet_vec = pygame.math.Vector2(aim_pos[0] - player_position[0], aim_pos[1] - player_position[1]).normalize() * 10
bullet = Bullet()
bullet.rect.center = player.rect.center
bullet.vec = bullet_vec
if bullets > 0:
all_sprite_list.add(bullet)
bullets -= 1
pygame.mixer.music.load('Gunshot.mp3')
pygame.mixer.music.play()
else:
pygame.mixer.music.load('reload.mp3')
pygame.mixer.music.play()
hit = pygame.sprite.spritecollide(bullet, enemy_list, False)
for enemy in hit:
killcounter += 1
enemy_list.remove(enemy)
all_sprite_list.remove(enemy)
enemy_list.update()
all_sprite_list.update()
enemy.move(player)
all_sprite_list.update()
all_sprite_list.draw(win)
time = font.render(str(timer/1000) ,1,black)
win.blit(time, (680, 5))
scoretext = font.render("Bullets: " +str(bullets), 1, black)
win.blit(scoretext, (5, 5))
kill = font.render("Kill count: " +str(killcounter), 1, black)
win.blit(kill, (250, 5))
pygame.display.flip()
clock.tick(100)
pygame.quit()
What I had to do was:
add a start for a new timer
#Start screen Loop
done = False
start_time = pygame.time.get_ticks()
When you determine the game is over, obtain the time taken here
def gameOverScreen():
seconds_survived = (pygame.time.get_ticks() - start_time) // 1000
ending = 1
What you have to do is find the time at the moment of collision (when collide is true) and pass that as an argument to gameOverScreen().
if collide:
gameover = True
end_time = pygame.time.get_ticks()
And gameOverScreen should receive the argument end_time and use it to display the seconds
def gameOverScreen(end_time):
seconds_survived = (end_time - start_time) // 1000
Keep in mind this only works because "if collide" is True only once, if it was True repeatedly then end_time would keep updating in the loop and you would again see the same case of increasing seconds.
Hope this helped someone!

my snake go backwards when the horizontal and vertical

i'm making a game but when i hit the horizontal and vertical keys at the same time or pressed fast enough, my snake go backwards, which will make a game over screen happen if it's longer then 2 blocks.
I tried making a long if statement. And cleaned up the code.
import pygame
import os
import sys
pygame.mixer.pre_init()
pygame.mixer.init(44100, 16, 2, 262144)
pygame.init()
from pygame.locals import*
import cv2
import time
import random
import pickle
import shutil
dw = 1280
dh = 720
at = 40
bs = 20
screen = pygame.display.set_mode((dw, dh))
clock = pygame.time.Clock()
def pause():
paused = True
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
paused = False
elif event.key == pygame.K_SPACE:
menu(1)
screen.fill(white)
mts("Paused", black, -100, 100)
mts("Press esc to go back to the game or press space to go back to the menu", black, 25, 45)
pygame.display.update()
clock.tick(60)
#define the apple to spawn in a random place
def randAppleGen():
randAppleX = random.randrange(0, dw-at, bs)
randAppleY = random.randrange(0, dh-at, bs)
return randAppleX,randAppleY
def snake(bs, sl):
for XnY in sl:
pygame.draw.rect(screen, Dgreen, [XnY[0],XnY[1],bs,bs])
def gameLoop():
global at
global bs
hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )
gameExit = False
gameOver = False
gameHack = False
Speed = 20
lead_x = dw/2
lead_y = dh/2
lead_x_change = 0
lead_y_change = 0
pygame.mixer.music.load(os.path.join(os.getcwd(), 'Sounds', 'music1.ogg'))
pygame.mixer.music.play(-1)
slist = []
sl = 0
if sl > 2304:
gameHack = True
randAppleX,randAppleY = randAppleGen()
while not gameExit:
while gameOver == True:
screen.fill(white)
mts("Game over", red, -50,100)
mts("Press enter to play again or press space to go back to the menu", black, 50,50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = False
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
gameLoop()
if event.key == pygame.K_SPACE:
gameExit = False
gameOver = False
menu(1)
while gameHack == True:
pygame.mixer.music.stop()
screen.fill(white)
mts("Hacked", red, -50,100)
mts("You hacked or exploit the game, press enter to quit the game", black, 50,50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = False
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
pygame.quit()
sys.exit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and lead_x_change != bs:
lead_x_change = -bs
lead_y_change = 0
elif event.key == pygame.K_RIGHT and lead_x_change != -bs:
lead_x_change = bs
lead_y_change = 0
elif event.key == pygame.K_UP and lead_y_change != bs:
lead_y_change = -bs
lead_x_change = 0
elif event.key == pygame.K_DOWN and lead_y_change != -bs:
lead_y_change = bs
lead_x_change = 0
elif event.key == pygame.K_ESCAPE:
pause()
elif event.key == pygame.K_s and Speed >= 10 and Speed < 60:
Speed += 10
clock.tick(Speed)
elif event.key == pygame.K_d and Speed <= 60 and Speed > 10:
Speed -= 10
clock.tick(Speed)
if not pygame.Rect(0, 0, dw, dh).contains(lead_x, lead_y, bs, bs):
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
screen.fill(white)
#draw the apple
apple = pygame.draw.rect(screen, red, [randAppleX,randAppleY,at,at])
sh = []
sh.append(lead_x)
sh.append(lead_y)
slist.append(sh)
snake(bs, slist)
if len(slist) > sl:
del slist[0]
for eachSegment in slist[:-1]:
if eachSegment == sh:
gameOver = True
score(sl)
highscore(hs)
if sl > hs:
hs += 1
os.remove( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN') )
pickle.dump( sl, open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "wb" ) )
hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )
pygame.display.update()
#make the apple spawn
if lead_x > randAppleX and lead_x < randAppleX + at or lead_x + bs > randAppleX and lead_x + bs < randAppleX + at:
if lead_y > randAppleY and lead_y < randAppleY + at:
randAppleX,randAppleY = randAppleGen()
sl += 1
elif lead_y + bs > randAppleY and lead_y + bs < randAppleY + at:
randAppleX,randAppleY = randAppleGen()
sl += 1
clock.tick(Speed)
pygame.quit()
quit()
I expected it to not go backwards, even though there's a code for it. I still go backwards. How do you fix it?
The issue occurs, because the events are handled in a loop:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# [...]
Lets assume the snake moves to the left and lead_x_change == -bs respectively lead_y_change == 0. If (e.g.) pygame.K_UP is pressed and the following condition is fulfilled:
elif event.key == pygame.K_UP and lead_y_change != bs:
This causes that the movement state changes to lead_x_change = 0 and lead_y_change = -bs.
If the pygame.K_RIGHT was pressed a bit later, but fast enough to be handled in the same frame of the main loop, then it is handled in the event loop, one pass later. This causes that the following condition is fulfilled, too:
elif event.key == pygame.K_RIGHT and lead_x_change != -bs:
Now the movement state changes to lead_x_change = bs and lead_y_change = 0. It seems, that the snake turned by 180 degrees. Indeed it change the direction from left to upward and from upwards to right in one frame (in one pass of the main loop, but 2 passes of the event loop).
Fortunately the issue can be solved with ease. Just copy the values of lead_x_change and lead_y_change before the event loop and use the copies to evaluate the movement conditions in the event loop.
Note the conditions have to check against the state of lead_x_change and lead_y_change, which they had have at the begin of the frame:
prev_x, prev_y = lead_x_change, lead_y_change
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and prev_x != bs:
lead_x_change, lead_y_change = -bs, 0
elif event.key == pygame.K_RIGHT and prev_x != -bs:
lead_x_change, lead_y_change = bs, 0
elif event.key == pygame.K_UP and prev_y != bs:
lead_x_change, lead_y_change = 0, -bs
elif event.key == pygame.K_DOWN and prev_y != -bs:
lead_x_change, lead_y_change = 0, bs
# [...]

Moving an image in pygame?

So, I'm making my first game in pygame, and have done OK up to this point. I just can't move the image. Can I please get some help?
mc_x = 20
mc_y = 20
spider_x = 690
spider_y = 500
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
mc_x -= 5
elif event.key == pygame.K_RIGHT:
mc_x += 5
elif event.key == pygame.K_UP:
mc_y += 5
elif event.key == pygame.K_DOWN:
mc_y -= 5
screen.blit(background,(0,0))#fixed
screen.blit(spider_small,(spider_x,spider_y))#FIXED
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
Based on your code:
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
should be inside the loop so that it would update/refresh your game for every keystroke.
You forgot to update the screen. Set the update function inside the main game loop. This is going to work fine!
Here's my sample code
import pygame
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
canvas = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Example')
gameExit = False
lead_x, lead_y = 300, 300
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x -= 10
elif event.key == pygame.K_RIGHT:
lead_x += 10
elif event.key == pygame.K_DOWN:
lead_y += 10
elif event.key == pygame.K_UP:
lead_y -= 10
canvas.fill(WHITE)
pygame.draw.rect(canvas, RED, [lead_x, lead_y, 30, 30])
pygame.display.update()
pygame.quit()
quit()

How do I move an object in one direction with a single keypress until the direction is changed?

When I start the program and press the first key the program freezes. Can anyone tell me why this doesn't work and give me a possible solution to my problem?
if event.key == pygame.K_UP:
key = False
while key == False:
schlange.move(0, -50)
if event.key == pygame.K_DOWN:
key = True
while key == True:
schlange.move(0, 50)
if event.key == pygame.K_LEFT:
key = False
while key == False:
schlange.move(-50, 0)
if event.key == pygame.K_RIGHT:
key = True
while key == True:
schlange.move(50, 0)
def move(self, x_change, y_change):
self.screen.fill(BLACK)
self.x_change = x_change
self.y_change = y_change
self.startx += x_change
self.starty += y_change
self.rectsize = (self.startx, self.starty)
pygame.draw.rect(self.screen, self.color, [self.startx, self.starty, self.width, self.height])
Thanks in advance!
The formatting in your code is off - but regardless - the code in each of the sections that look like:
key = False
while key == False:
schlange.move(0, -50)
Will never complete. That while loop will ALWAYS evaluate to True, because key == False is always true, and never changes. So the loop will never end.
it could be something like this
speed = (0, 0)
While True:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
speed = (0, -50)
elif event.key == pygame.K_DOWN:
speed = (0, 50)
if event.key == pygame.K_LEFT:
speed = (-50, 0)
if event.key == pygame.K_RIGHT:
speed = (50, 0)
# --- all updates (without draws) ---
schlange.move(speed[0], speed[1])
# --- all draws (without updates) ---
# ...

Pygame: game displays nothing, despite 'while' loop

Im working on a simple game( a semi copy of the 'Dodger' game), and the game runs, yet displays nothing. I have a while loop running, so why is nothing showing up? Is it a problem with spacing, the images themselves, or am i just overlooking something?
import pygame,sys,random, os
from pygame.locals import *
pygame.init()
#This One Works!!!!!!!
WINDOWHEIGHT = 1136
WINDOWWIDTH = 640
FPS = 40
TEXTCOLOR = (255,255,255)
BACKGROUNDCOLOR = (0,0,0)
PLAYERMOVEMENT = 6
HARVEYMOVEMENT = 5
TJMOVEMENT = 7
LASERMOVEMENT = 10
ADDNEWBADDIERATE = 8
COLOR = 0
TJSIZE = 65
HARVEYSIZE = 65
#Check the sizes for these
def terminate():
if pygame.event() == QUIT:
pygame.quit()
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitBaddies(playerRect,TjVirus,HarVirus):
for b in TjVirus and HarVirus:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text,font,surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
mainClock = pygame.time.Clock()
WindowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.mouse.set_visible(False)
pygame.display.set_caption('Virus')
#Player Images
# Check the name of the .png file
TjImage = pygame.image.load('Virus_TJ_edited-1.png')
TjRect = TjImage.get_rect()
#chanhe this part from the baddies variable in the 'baddies' area
playerImage = pygame.image.load('Tank_RED.png')
playerRect = playerImage.get_rect()
LaserImage = pygame.image.load('laser.png')
LaserRect = LaserImage.get_rect()
pygame.display.update()
startGame()
while True:
TjVirus = []#the red one / make a new one for the blue one
HarVirus = []#The BLue one / Need to create a new dictionary for this one
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = laser = False
baddieAddCounter = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == K_SPACE:
lasers = True
if event.type == KEYUP:
if evnet.type == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == K_SPACE:
LaserImage.add(LaserRect)
if event.key == ord('j'):
COLOR = 2
if event.key == ord('k'):
if COLOR == 2:
COLOR = 1
playerImage = pygame.image.load('Tank_RED.png')
if COLOR == 1:
COLOR = 2
playerImage = pygame.image.load('Tank_BLUE.png')
if event.type == MOUSEMOTION:
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
#Dict for TJ(RED) VIRUS
baddieSize = (TJSIZE)
NewTjVirus = {'rect':pygame.Rect(random.rantint(0,WINDOWWIDTH - TJSIZE),0 - TJSIZE,TJSIZE,TJSIZE),
'speed':(TJMOVEMENT),
'surface':pygame.transform.scale(TJImage,(TJSIZE,TJSIZE)),
}
TjVirus.append(NewTjVirus)
#Dict for Harvey(BLUE) virus
baddieSize = (HARVEYSIZE)
NewHarveyVirus = {'rect':pygame.Rect(random.randint(0,WINDOWWIDTH - HARVEYSIZE),0 - HARVEYSIZE,HARVEYSIZE,HARVEYSIZE),
'speed':(HARVEYMOVEMENT),
'surface':pygame.transform.scale(HARVEYSIZE,(HARVEYSIZE,HARVEYSIZE))
}
HarVirus.append(NewHarveyVirus)
#Player Movement
if moveLeft and playerRect.left >0:
playerRect.move_ip(-1*PLAYERMOVEMENT,0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVEMENT,0)
if moveUp and playerRect.top >0:
playerRect.move_ip(0,-1*PLAYERMOVEMENT)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0,PLAYERMOVEMENT)
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
#Need to change for each individual virus
for b in HarVirus and TjVirus:
b['rect'].move_ip(0,b['speed'])
for b in HarVirus and TjVirus:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
windowSurface.fill(pygame.image.load('Background_Proto copy.png'))
for b in HarVirus and TjVirus:
windowSurface.blit(b['surface'],b['rect'])
pygame.display.update()
if playerHasHitBaddies(playerRect,HarVirus,TjVirus):
break
for b in TjVirus and HarVirus[:]:
if b['rect'].top < WINDOWHEIGHT:
HarVirus.remove(b)
TjVirus.remove(b)
mainClock.tick(FPS)
Usally I use pygame.display.flip() not pygame.display.update()
You call your startGame() in your script, which looks like this:
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
The game is stuck in that while loop until you press a key.
That's your current problem, but there are other errors as well, like
def terminate():
if pygame.event() == QUIT:
pygame.quit()
pygame.event() is not callable. Maybe you wanted to pass an event as argument here?
And also
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
, instead of .

Categories

Resources