Why is my key movement not working properly? - python

I'm creating a basic game, but I have a problem with keyboard responding in my code. When you click on start, the cube is going all the way the direction of your pressed arrow key, but I want it to move any direction you press with arrow keys and it stops if no keys are pressed. Could someone show me what error do I have in my code and how to do it right?
Here is the code:
import pygame
import time
import sys
import pygame.event as EVENTS
from pygame.locals import *
import random
print("Welcome to the prototype of rpg game -Made by Adam Pospíchal.")
pygame.init()
sirka = 800
vyska = 800
okno = pygame.display.set_mode((sirka,vyska))
pygame.display.set_caption("RPG GAME")
#PARAMETRE OKNA#
#PARAMETRE OKNA#
#PARAMETRE KOCKY HRACA#
#PARAMETRE MENU#
#farby - RGB#
RM = 255
GM = 255
BM = 0
player_r = 0
player_g = 255
player_b = 0
player_height = 20
player_width = 20
smerx = 0
smery = 0
x_pos = 390
y_pos = 390
#farby - RGB#
x = 400
y = 400
#PARAMETRE MENU#
#TEXT#
font = pygame.font.SysFont('Arial', 40)
textsurface_title = font.render('CUBE ADVENTURE', False, (255, 0, 0))
textsurface_Controls = font.render('CONTROLS', False, (255, 0, 0))
textsurface = font.render('START', False, (255, 0, 0))
textsurface2 = font.render('CONTROLS', False, (255, 0, 0))
textsurface3 = font.render('EXIT', False, (255, 0, 0))
#TEXT#
#MAIN MENU#
obdlznik_start = pygame.Rect(300,200,200,100)
obdlznik_controls = pygame.Rect(300,350,200,100)
obdlznik_exit = pygame.Rect(300,500,200,100)
#MAIN MENU
def game():
x_pos = 360
y_pos = 360
smerx = 0
smery = 0
player_r = 0
player_g = 255
player_b = 0
player_height = 20
player_width = 20
sirka = 800
vyska = 800
while True:
for event in pygame.event.get():
if event.type == QUIT:
koniec()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
smerx = 1
if event.key == pygame.K_LEFT:
smerx = -1
if event.key == pygame.K_DOWN:
smery = 1
if event.key == pygame.K_UP:
smery = -1
if event.key == pygame.K_ESCAPE:
koniec()
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
smerx = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
smery = 0
#BORDER
if x_pos + player_width > 800:
x_pos = 800
if x_pos < 0:
x_pos = 0
if y_pos + player_height > 800:
y_pos = 800
if y_pos < 0:
y_pos = 0
#BORDER
#PLAYER CUBE
okno.fill((0,0,0))
x_pos = x_pos + smerx
y_pos = y_pos + smery
obdlznik_player = pygame.Rect(x_pos,y_pos,player_height,player_width)
pygame.draw.rect(okno,(player_r,player_g,player_b),obdlznik_player)
pygame.display.update()
#PLAYER CUBE
#HEALTHBAR
#HEALTHBAR
def koniec(): #EXIT GAME
pygame.quit()
sys.exit()
def menu_controls(): #CONTROLS MENU
while True:
for event in pygame.event.get():
if event.type == QUIT:
koniec()
#FARBY KOCKY KURZORA
RR = 255
GR = 0
BR = 0
#FARBY KOCKY KURZORA
mouse_x,mouse_y = pygame.mouse.get_pos() #POZÍCIA MYŠI
mouse_rect = pygame.Rect(mouse_x-10,mouse_y-10,20,20) #KOCKA MYŠI
obdlznik_spat = pygame.Rect(10,10,40,40)
obdlznik_spat_2 = pygame.Rect(30,25,10,10)
spat_collision = mouse_rect.colliderect(obdlznik_spat)
if spat_collision:
RR = 0
GR = 0
BR = 255
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu_main()
pygame.mouse.set_visible(0) #VIDITEĽNOSŤ MYŠI
okno.fill((0,0,0))
okno.blit(textsurface_Controls,(300,50))#NADPIS
pygame.draw.rect(okno,(RM,GM,BM),obdlznik_spat)
pygame.draw.polygon(okno, (255,0,0), ((15,30), (30,15), (30,45)))
pygame.draw.rect(okno,(255,0,0),obdlznik_spat_2)
pygame.draw.rect(okno,(RR,GR,BR),mouse_rect) #KRESLENIE KOCKY KURZORA MYSI
pygame.display.update() #UPDATE OBRAZOVKY
def menu_main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
koniec()
#FARBY KOCKY KURZORA
RR = 255
GR = 0
BR = 0
#FARBY KOCKY KURZORA
mouse_x,mouse_y = pygame.mouse.get_pos() #POZÍCIA MYŠI
pygame.mouse.set_visible(0) #VIDITEĽNOSŤ MYŠI
mouse_rect = pygame.Rect(mouse_x-10,mouse_y-10,20,20) #KOCKA MYŠI
s_collision = mouse_rect.colliderect(obdlznik_start)
c_collision = mouse_rect.colliderect(obdlznik_controls)
e_collision = mouse_rect.colliderect(obdlznik_exit)
if s_collision:
RR = 0
GR = 255
BR = 0
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
game()
if c_collision:
RR = 0
GR = 0
BR = 255
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu_controls()
if e_collision:
RR = 255
GR = 255
BR = 255
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
koniec()
okno.fill((0,0,0))
okno.blit(textsurface_title,(250,50))#NADPIS
pygame.draw.rect(okno,(RM,GM,BM),obdlznik_start)
okno.blit(textsurface,(350,230))
pygame.draw.rect(okno,(RM,GM,BM),obdlznik_controls)
okno.blit(textsurface2,(315,370))
pygame.draw.rect(okno,(RM,GM,BM),obdlznik_exit)
okno.blit(textsurface3,(360,520))
pygame.draw.rect(okno,(RR,GR,BR),mouse_rect) #KRESLENIE KOCKY KURZORA MYSI
pygame.display.update() #UPDATE OBRAZOVKY
menu_main()
#MAIN MENU#
#HERNY CYKLUS - PRIKAZY V HRE#

The problem is that you are using two event loops inside game(). You must add all the events in the same event loop.
So,
for event in pygame.event.get():
if event.type == QUIT:
koniec()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
smerx = 1
if event.key == pygame.K_LEFT:
smerx = -1
if event.key == pygame.K_DOWN:
smery = 1
if event.key == pygame.K_UP:
smery = -1
if event.key == pygame.K_ESCAPE:
koniec()
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
smerx = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
smery = 0
this ^ will become just
for event in pygame.event.get():
if event.type == QUIT:
koniec()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
smerx = 1
if event.key == pygame.K_LEFT:
smerx = -1
if event.key == pygame.K_DOWN:
smery = 1
if event.key == pygame.K_UP:
smery = -1
if event.key == pygame.K_ESCAPE:
koniec()
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
smerx = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
smery = 0

So basically, I did a mistake in my code by using (2x for) in the game(). Next time when I will use (for), I will check if the commands below it are in the same cycle. Thanks for answer :)

Related

name 'event' is not defined not sure why im getting this

class GameState():
def init(self):
self.state = 'main_game'
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
while not done:
game_state.main_game()
clock.tick(50)
pygame.quit()
This is just the snippit of code i can send the rest if needed the thing i did previously i had it under a game loop but this time im making a class and object so i can make multiple levels in the game
The if event.type == pygame.MOUSEBUTTONDOWN: and if event.type == pygame.KEYDOWN: are both outside of the for loop that defines the "event" variable.
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
Your code have indentation problems. Which makes event.MOUSEBUTTONDOWN and other events outside the loop. You code should have looks like this.

Python Pygame letter Keystrokes not registering? [duplicate]

This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
How can I make a sprite move when key is held down
(6 answers)
Closed 2 years ago.
My problem is that whenever I use a letter for a keystroke it does not work. The code worked when I changed the keystrokes to arrow keys but didn't work if I tried to use WASD. I have tried replacing the variables and many other things but it still does not work.
Here is my code that works:
import pygame
import os
pygame.init()
width = 1200
height = 800
FPS = 60
# Player 1
playerImg1 = pygame.image.load('spaceship1.png')
playerX1 = 200
playerY1 = 370
playerX_change1 = 0
playerY_change1 = 0
def player1(x1, y1):
window.blit(playerImg1, (x1, y1))
# Player 2
playerImg2 = pygame.image.load('spaceship2.png')
playerX2 = 800
playerY2 = 370
playerX_change2 = 0
playerY_change2 = 0
def player2(x2, y2):
window.blit(playerImg2, (x2, y2))
# gameLoop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Keystrokes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT: #left
playerX_change1 = -5
if event.key == pygame.K_RIGHT: #right
playerX_change1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_RIGHT:
playerX_change1 = 0
playerX1 += playerX_change1
if playerX1 <= 0:
playerX1 = 0
elif playerX1 >= 400:
playerX1 = 400
window.blit(bg,(0,0))
player1(playerX1, playerY1)
player2(playerX2, playerY2)
pygame.display.update()
Here is the code that doesn't work:
import pygame
import os
pygame.init()
width = 1200
height = 800
FPS = 60
# Creating and naming the screen
window = pygame.display.set_mode((width, height))
name = pygame.display.set_caption("Duel")
# Player 1
playerImg1 = pygame.image.load('spaceship1.png')
playerX1 = 200
playerY1 = 370
playerX_change1 = 0
playerY_change1 = 0
def player1(x1, y1):
window.blit(playerImg1, (x1, y1))
# Player 2
playerImg2 = pygame.image.load('spaceship2.png')
playerX2 = 800
playerY2 = 370
playerX_change2 = 0
playerY_change2 = 0
def player2(x2, y2):
window.blit(playerImg2, (x2, y2))
# gameLoop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Keystrokes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a: #left
playerX_change1 = -5
if event.key == pygame.K_d: #right
playerX_change1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerX_change1 = 0
playerX1 += playerX_change1
if playerX1 <= 0:
playerX1 = 0
elif playerX1 >= 400:
playerX1 = 400
window.blit(bg,(0,0))
player1(playerX1, playerY1)
player2(playerX2, playerY2)
pygame.display.update()
```
It's a matter of Indentation. You have to handle the events in the event loop rather than the application loop.
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
# Keystrokes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a: #left
playerX_change1 = -5
if event.key == pygame.K_d: #right
playerX_change1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_a:
playerX_change1 = 0

How to make enemies fall at random on pygame?

I want enemies to randomly fall from the sky on my game and I do not know how to do this.
I was using this youtube video: Falling Objects in Pygame.
import pygame, random
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
##
x += x_change
y += y_change
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
So the code that was supposed to make the image fall was this
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
Move the following code:
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
To here so it can be within the game loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10

Player movement

I wrote this simple code that draws and then lets you move a rectangle, but even after I change the coordinates of the rectangle by calling the move_player_x_ function, it doesn't move at all. I don't understand why. I came here looking for clarification and a detailed solution to my problem.
Here's the code:
import pygame
white = (255, 255, 255)
black = (0, 0, 0)
class Game():
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
def __init__(self):
pass
def fill_screen(self, color):
self.color = color
self.screen.fill(self.color)
def update_method(self):
pygame.display.update()
game = Game()
class Player(pygame.sprite.Sprite):
lead_x = game.width/2
lead_y = game.height/2
lead_x_change = 0
lead_y_change = 0
velocity = 0.2
block_size = 10
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def move_player_x_left(self):
self.lead_x_change += -self.velocity
def move_player_x_right(self):
self.lead_x_change += self.velocity
def move_player_y_up(self):
self.lead_y_change += -self.velocity
def move_player_y_down(self):
self.lead_y_change += self.velocity
def draw_player(self):
pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def key_up_x_stop(self):
self.lead_x = 0
def key_up_y_stop(self):
self.lead_y = 0
def constant_x_movement(self):
self.lead_x += self.lead_x_change
def constant_y_movement(self):
self.lead_y += self.lead_y_change
player = Player()
exitGame = False
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.move_player_y_up()
if event.key == pygame.K_s:
player.move_player_y_down()
if event.key == pygame.K_a:
player.move_player_x_left()
if event.key == pygame.K_d:
player.move_player_x_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player.key_up_y_stop()
if event.key == pygame.K_a or event.key == pygame.K_d:
player.key_up_x_stop()
player.constant_x_movement()
player.constant_y_movement()
player.draw_player()
game.update_method()
pygame.quit()
quit()
The code in the event loop is not indented correctly. Here's a corrected version:
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.move_player_y_up()
if event.key == pygame.K_s:
player.move_player_y_down()
if event.key == pygame.K_a:
player.move_player_x_left()
if event.key == pygame.K_d:
player.move_player_x_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
player.key_up_y_stop()
if event.key == pygame.K_a or event.key == pygame.K_d:
player.key_up_x_stop()
Also, in the ...stop methods, you have to set lead_x_change and lead_y_change to 0 not lead_x and lead_y.
def key_up_x_stop(self):
self.lead_x_change = 0
def key_up_y_stop(self):
self.lead_y_change = 0
I edited your code, i added a function in the player object move_player with local booleans bUp,bDown,bLeft,bRight. If python had enumerations, it would be so much better. Any how, on event KEY DOWN and KEY UP, they toggle these booleans in the player. after the input is calculated and these booleans are toggled/set, it called move_player() in player object that checks its booleans and sets a while loop while one is true and adds velocity in the respected location and redraws player.
Here the source i got for you...
import pygame
white = (255, 255, 255)
black = (0, 0, 0)
class Game():
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
def __init__(self):
pass
def fill_screen(self, color):
self.color = color
self.screen.fill(self.color)
def update_method(self):
pygame.display.update()
class Player(pygame.sprite.Sprite):
lead_x = 800/2
lead_y = 600/2
velocity = 0.002
block_size = 10
bUp = false
bDown = false
bLeft = false
bRight = false
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def draw_player(self):
pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])
def move_player(self):
while bLeft:
self.lead_x += -self.velocity
self.draw_player()
while bRight:
self.lead_x += self.velocity
self.draw_player()
while bUp:
self.lead_y += -self.velocity
self.draw_player()
while bDown:
self.lead_y += self.velocity
self.draw_player()
game = Game()
player = Player()
exitGame = False
while not exitGame:
game.fill_screen(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.bUp = true
if event.key == pygame.K_s:
player.bDown = true
if event.key == pygame.K_d:
player.bRight = true
if event.key == pygame.K_a:
player.bLeft = true
elif event.type == pygame.KEYUP:
if event.key == pygame.K_w:
player.bUp = false
if event.key == pygame.K_s:
player.bDown = false
if event.key == pygame.K_d:
player.bRight = false
if event.key == pygame.K_a:
player.bLeft = false
player.move_player()
game.update_method()
pygame.quit()
quit()

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