check for event midway through running while loop? - python

So with pygame you have a while loop that loops continuously, then your event handlers in a for loop, then the code you want to execute continuously.
I need to handle an event after i execute a line of code inside the while loop though beacuse they impact each other, but I also need to handle a different event before the line.
How, inside my main while loop, handle a set of events, execute some code, and then handle another set of events?

Solved.
I set a variable equal to 1 in the user event handler, and then down where i needed to execute the code, i check if the variable was equal to 1, and if it was, i executed my code and set the variable back to 0.
Good stuff.
Here is my code if anyone wants to help me find a better solution ;) (kinda long):
uif = "images/userGray.png"
bif = "images/bg.jpg"
cif = "images/chair3.png"
i = 0
playerX = 1
playerY = 1
pX = 1
pY = 1
bX = 0
bY = 0
moveX = 0
moveY = 0
windowX = 640
windowY = 480
lowerY = 1024
lowerX = 1024
bullets = []
x = 0
y = 0
rotate = False
objects = []
objects.append([256,260,410,511])
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.image.load(bif).convert()
user = pygame.image.load(uif).convert_alpha()
chair = pygame.image.load(cif).convert_alpha()
chair1 = pygame.image.load(cif).convert_alpha()
pygame.time.set_timer(USEREVENT + 1, 100)
def shoot(inLoc, clLoc, weapon):
bulletId = len(bullets)
bullets[bulletId] = [inLoc, clLoc, 200, 3]
moveSpeed = .1
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == USEREVENT + 1:
rotate = True;
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == K_a:
moveX = -1*moveSpeed
elif event.key == K_RIGHT or event.key == K_d:
moveX = moveSpeed
if event.key == K_DOWN or event.key == K_s:
moveY = moveSpeed
elif event.key == K_UP or event.key == K_w:
moveY = -1*moveSpeed
if event.type == KEYUP:
if event.key == K_LEFT or event.key == K_a or event.key == K_RIGHT or event.key == K_d:
moveX = 0
if event.key == K_DOWN or event.key == K_s or event.key == K_UP or event.key == K_w:
moveY = 0
dontMoveX = 0
dontMoveY = 0
for obj in objects:
if playerX + moveX > obj[0]-user.get_width() and playerX + moveX < obj[1] and playerY + moveY > obj[2]-user.get_height() and playerY + moveY < obj[3]:
if playerY + moveY == obj[2]-user.get_height()-1 or playerY + moveY == obj[3]+1:
dontMoveX = 0
else:
dontMoveX = 1
if playerX + moveX > obj[0]-user.get_width() and playerX + moveX < obj[1] and playerY + moveY > obj[2]-user.get_height() and playerY + moveY < obj[3]:
if playerX + moveX == obj[0]-user.get_width()-1 or playerX + moveX == obj[1]+1:
dontMoveY = 0
else:
dontMoveY = 1
if dontMoveX == 0:
playerX += moveX
if (playerX >= 0 and playerX <= windowX/2) or (playerX >= lowerX-(windowX/2) and playerX <= lowerX-user.get_width()):
pX+=moveX
if playerX > windowX/2 and playerX < lowerX-(windowX/2):
bX+=-1*moveX
if dontMoveY == 0:
playerY += moveY
if (playerY >= 0 and playerY <= windowY/2) or (playerY >= lowerY-(windowY/2) and playerY <= lowerY-user.get_width()):
pY+=moveY
if playerY > windowY/2 and playerY < lowerY-(windowY/2):
bY+=-1*moveY
screen.blit(background,(bX,bY))
screen.blit(user,(pX,pY))
pygame.mouse.set_visible(False);
if rotate == True:
if i < 360:
i = i + 18
else:
i = 0
orig_chair_rect = chair.get_rect()
chair1 = pygame.transform.rotate(chair, i);
rot_chair_rect = orig_chair_rect.copy()
rot_chair_rect.center = chair1.get_rect().center
chair1 = chair1.subsurface(rot_chair_rect).copy()
rotate = False
x,y = pygame.mouse.get_pos()
x -= chair.get_width()/2
y -= chair.get_height()/2
screen.blit(chair1,(x,y))
pygame.display.update()

Related

Stop moving when let go key

I am trying to move Left and Right and whenever I let go of the right arrow it keeps moving right and same with the left side of things. I have been messing around with this and cant figure it out.
import pygame
# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800,600))
# Player
PlayerHealth = 100
Playerinven = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
playerImg = pygame.image.load('001-alien.png')
# Player Movment
playerX = 370
playerY = 480
XLlabel = False
XRlabel = False
playerX_change = 0
def player(x, y):
screen.blit(playerImg, (x , y))
# Game Loop
running = True
while running:
# RGB - Red,Green,Blue
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
XLlabel = True
elif event.key == pygame.K_RIGHT:
XRlabel = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
XLlabel = False
if event.key == pygame.K_RIGHT:
XRlabel = False
if XLlabel == True and XRlabel == True:
playerX_change = 0
elif XLlabel == True:
playerX_change = -0.3
elif XRlabel == True:
playerX_change = 0.3
elif XLlabel == False and XRlabel == False:
player_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
player(playerX, playerY)
pygame.display.update()
This is my first time trying to make a game so it is kinda stressing me out XD
Error:
You have written player_change = 0 where there must be playerX_change = 0.
Code:
# Player
PlayerHealth = 100
Playerinven = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
playerImg = pygame.image.load('001-alien.png')
# Player Movment
playerX = 370
playerY = 480
XLlabel = False
XRlabel = False
playerX_change = 0
def player(x, y):
screen.blit(playerImg, (x , y))
# Game Loop
running = True
while running:
# RGB - Red,Green,Blue
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
XLlabel = True
elif event.key == pygame.K_RIGHT:
XRlabel = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
XLlabel = False
if event.key == pygame.K_RIGHT:
XRlabel = False
if XLlabel == True and XRlabel == True:
playerX_change = 0
elif XLlabel == True:
playerX_change = -0.3
elif XRlabel == True:
playerX_change = 0.3
elif XLlabel == False and XRlabel == False:
playerX_change = 0 #just a small error you have written player_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
player(playerX, playerY)
pygame.display.update()
Not sure if this is the cause of your problem but your handling of the keys seems a little "tortured".
For a start, you should generally never use if XLlabel == True, preferring instead the more succinct if XLlabel.
The key handling can then be made something like:
# Initial left/right key state flags.
left_down, right_down = False, False
for event in pygame.event.get():
# Process events, keys up/down sets flags.
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
left_down = True
elif event.key == pygame.K_RIGHT:
right_down = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
left_down = False
elif event.key == pygame.K_RIGHT:
right_down = False
# Event processing done, evaluate key states to get velocity.
velocity = 0
if left_down:
velocity -= 0.3
if right_down:
velocity += 0.3
# Adjust player position by velocity.
...

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

-805306369 (0xCFFFFFFF) error in python what can i do

I'm quite new to python and have recently started game dev with pygame. I wanted to know why my game just freezes and the exitcode -805306369 (0xCFFFFFFF) appears. Do i have errors in my programm? It looks like this:
import pygame
import random
import math
pygame.init()
window = pygame.display.set_mode((1000, 600))
caption = pygame.display.set_caption(
'Test your reaction speed. Shoot the target game!') # sets a caption for the window
run = True
PlayerImg = pygame.image.load('F:\PythonPortable\oscn.png')
PlayerX = 370
PlayerY = 420
PlayerX_change = 0
PlayerY_change = 0
def player():
window.blit(PlayerImg, (PlayerX, PlayerY))
aim_sight = pygame.image.load('F:\PythonPortable\ktarget.png')
aim_sightX = 460
aim_sightY = 300
aim_sight_changeX = 0
aim_sight_changeY = 0
def aim_sight_function(x, y):
window.blit(aim_sight, (x, y))
targetedImg = pygame.image.load('F:\PythonPortable\ktargetedperson.png')
targetedX = random.randint(0, 872)
targetedY = random.randint(0, 200)
def random_target():
window.blit(targetedImg, (targetedX, targetedY))
def iscollision(targetedX, targetedY, aim_sightX, aim_sightY):
distance = math.sqrt((math.pow(targetedX - aim_sightX, 2)) + (math.pow(targetedY - aim_sightY, 2)))
if distance < 70:
return True
else:
return False
while run:
window.fill((255, 255, 255))
random_target()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
aim_sight_changeX = 2
PlayerX_change = 2
elif event.key == pygame.K_UP:
aim_sight_changeY = -2
PlayerY_change = -2
elif event.key == pygame.K_DOWN:
aim_sight_changeY = 2
PlayerY_change = 2
score = 0
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
aim_sight_changeX = 0
PlayerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
aim_sight_changeY = 0
PlayerY_change = 0
aim_sightX += aim_sight_changeX
if aim_sightX <= 46.5:
aim_sight_changeX = 0
elif aim_sightX >= 936:
aim_sight_changeX = 0
aim_sightY += aim_sight_changeY
if aim_sightY <= 0:
aim_sight_changeY = 0
elif aim_sightY >= 400:
aim_sight_changeY = 0
PlayerX += PlayerX_change
if PlayerX <= -50:
PlayerX_change = 0
elif PlayerX >= 850:
PlayerX_change = 0
player()
aim_sight_function(aim_sightX, aim_sightY)
pygame.display.update()
I think there is a mistake in this area as my program runs well without it.
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
I've checked other questions but they are mostly for java and other languages.
You have an application loop. You do not need an additional loop to control the game. The loop that increments the score is an infinite loop. Change the loop to a selection (change while to if).
Furthermore, the score has to be initialized before the application loop:
score = 0
while run:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
# [...]
elif event.key == pygame.K_SPACE:
if score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision:
print("HIT")
score = score + 1

List index is out of range and I do not understand why?

I've been getting the error :
line 102, in <module>
shot[2] += shoty
IndexError: list index out of range
In my code where I am trying to code a dagger to be thrown, and deleted if it is out of bounds. I understand what the list error means however; I am unsure of how it is affecting my code and any help would be greatly appreciated!
This is the part of my code which is relevant to the problem:
daggers = []
daggerPlayer = pygame.image.load(daggerImage.png)
for shot in daggers:
index = 0
shotx = math.cos(shot[0])*10
shoty = math.sin(shot[0])*10
shot[1] += shotx
shot[2] += shoty
if (shot[1] < -64) or (shot[1] > 900) or (shot[2] < -64) or (shot[2]> 600):
daggers.pop(index)
index +=1
for shoot in daggers:
daggerOne = pygame.transform.rotate(daggerPlayer, 360 - shoot[0]*57.29)
screen.blit(daggerOne, (shoot[1], shoot[2]))
EDIT: Here is the entirety of my code
#Load Images
peterPlayer = pygame.image.load('pixelPirateOne.png)'
nightBackground = pygame.image.load ('NightSky.png')
daggerPlayer = pygame.image.load('daggerImage.png')
#Settting Variables for Moving Character
xPlayer = 200
yPlayer = 275
dxPlayer = 0
dyPlayer = 0
playerPosition = (200,275)
accuracyShot = [0,0]
daggers = []
def quitGame():
pygame.quit()
sys.exit()
go = True
while go:
#Blit The Background
screen.blit(nightBackground, (0,0))
#Learned about atan2 from --> https://docs.python.org/2/library/math.html
#Allows To Rotate Player With Mouse
mousePosition = pygame.mouse.get_pos()
angle = math.atan2(mousePosition[1]-(yPlayer+32),mousePosition[0]-(xPlayer+26))
playerRotate = pygame.transform.rotate(peterPlayer, 360-angle*57.29)
playerPositionNew = (xPlayer-playerRotate.get_rect().width/2, yPlayer-playerRotate.get_rect().height/2)
screen.blit(playerRotate, playerPositionNew)
pygame.display.update()
#Quit Game
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitGame()
#Move Player- Note: Make this portion fluid; it's choppy as of now
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer -= 15
elif event.key == pygame.K_RIGHT:
dxPlayer += 15
elif event.key == pygame.K_UP:
dyPlayer -= 15
elif event.key == pygame.K_DOWN:
dyPlayer += 15
if 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
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
mousePosition = pygame.mouse.get_pos()
accuracyShot[1] += 1
daggers.append([math.atan2(mousePosition[1]-(playerPositionNew[1]+32), mousePosition[0]-(playerPositionNew[0]+26)), playerPositionNew[1]+32])
#Learned about cos and sin in python from --> https://docs.python.org/2/library/math.html
#Learned about .pop from --> https://docs.python.org/2/tutorial/datastructures.html
for shot in daggers:
index = 0
shotx = math.cos(shot[0])*10
shoty = math.sin(shot[0])*10
shot[1] += shotx
shot[2] += shoty
if (shot[1] < -64) or (shot[1] > 900) or (shot[2] < -64) or (shot[2]> 600):
daggers.pop(index)
index +=1
for shoot in daggers:
daggerOne = pygame.transform.rotate(daggerPlayer, 360 - shoot[0]*57.29)
screen.blit(daggerOne, (shoot[1], shoot[2]))
The list you append to daggers has only two elements, but by calling shot[2] you are trying to access the third, that's why you get that error. The two elements should be shot[0] and shot[1]. I believe you make the same mistake in screen.blit(daggerOne, (shoot[1], shoot[2])) as well.

Pygame The collision for my game works, but only for the last placed image

import pygame, random, time
class Game(object):
def main(self, screen):
bg = pygame.image.load('data/bg.png')
house1 = pygame.image.load('data/house1.png')
playerIdle = pygame.image.load('data/playerIdle.png')
playerRight = pygame.image.load('data/playerRight.png')
playerLeft = pygame.image.load('data/playerLeft.png')
playerUp = pygame.image.load('data/playerUp.png')
playerX = 0
playerY = 50
clock = pygame.time.Clock()
spriteList = []
gameIsRunning = False
house1Selected = False
houseInWorld = False
while 1:
clock.tick(30)
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
#delete all sprites on the game(only able to do this in god mode)
if event.type == pygame.KEYDOWN and event.key == pygame.K_d and gameIsRunning == False:
spriteList = []
#press 6 to select the house1 image to be placed
if event.type == pygame.KEYDOWN and event.key == pygame.K_6 and gameIsRunning == False:
house1Selected = True
#spawning the image"house1" at the position of the mouse by pressing space
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and gameIsRunning == False and house1Selected == True:
spriteList.append((house1, mouse))
house1XY = mouse
houseInWorld = True
#run mode where you cannot build and you move(where I want collision)
if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
gameIsRunning = True
#god mode where you can build and place the house1 image
if event.type == pygame.KEYDOWN and event.key == pygame.K_g:
gameIsRunning = False
#this is run mode where you can move around and where I want collision
if(gameIsRunning == True):
#player Movements
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
if playerY <= 0:
playerY = 0
if playerY >= 0:
screen.blit(playerUp, (playerX, playerY))
playerY = playerY - 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
PLAYERDOWNLIMIT = 700 - playerIdle.get_height()
if(playerY >= PLAYERDOWNLIMIT):
playerY = PLAYERDOWNLIMIT
if(playerY <= PLAYERDOWNLIMIT):
screen.blit(playerIdle, (playerX, playerY))
playerY = playerY + 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
if playerX <= 0:
playerX = 0
if playerX >= 0:
screen.blit(playerLeft, (playerX, playerY))
playerX = playerX - 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
PLAYERRIGHTLIMIT = 1200 - playerIdle.get_width()
if(playerX >= PLAYERRIGHTLIMIT):
playerX = PLAYERRIGHTLIMIT
if(playerX <= PLAYERRIGHTLIMIT):
screen.blit(playerRight, (playerX, playerY))
playerX = playerX + 2
#collision
if(house1InWorld == True):
house1Rect = pygame.Rect(house1XY[0], house1XY[1], 64, 64)
if playerRect.colliderect(house1Rect) and playerX <= house1XY[0]:
playerX = playerX - 2
if playerRect.colliderect(house1Rect) and playerX >= house1XY[0]:
playerX = playerX + 2
if playerRect.colliderect(house1Rect) and playerY <= house1XY[1]:
playerY = playerY - 2
if playerRect.colliderect(house1Rect) and playerY >= house1XY[1]:
playerY = playerY + 2
#this is godmode where you can move around fast n preview where you place images but I don't want collision here
if(gameIsRunning == False):
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
if playerY <= 0:
playerY = 0
if playerY >= 0:
screen.blit(playerUp, (playerX, playerY))
playerY = playerY - 8
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
PLAYERDOWNLIMIT = 700 - playerIdle.get_height()
if(playerY >= PLAYERDOWNLIMIT):
playerY = PLAYERDOWNLIMIT
if(playerY <= PLAYERDOWNLIMIT):
screen.blit(playerIdle, (playerX, playerY))
playerY = playerY + 8
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
if playerX <= 0:
playerX = 0
if playerX >= 0:
screen.blit(playerLeft, (playerX, playerY))
playerX = playerX - 8
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
PLAYERRIGHTLIMIT = 1200 - playerIdle.get_width()
if(playerX >= PLAYERRIGHTLIMIT):
playerX = PLAYERRIGHTLIMIT
if(playerX <= PLAYERRIGHTLIMIT):
screen.blit(playerRight, (playerX, playerY))
playerX = playerX + 8
screen.fill((200, 200, 200))
screen.blit(bg, (0, 0))
#what block are you placing(displays preview)
if(gameIsRunning == False and house1Selected == True):
screen.blit(house1, (mouse))
if(gameIsRunning == True):
playerXSTR = str(playerX)
playerYSTR = str(playerY)
playerXYSTR = ("(" + playerXSTR + ", " + playerYSTR + ")")
font = pygame.font.SysFont("monospace", 15)
playercord = font.render(playerXYSTR, 1, (255,255,255))
screen.blit(playercord, (0, 0))
runMode = font.render("Run Mode(Cannot build)", 1, (255,255,255))
screen.blit(runMode, (0, 20))
if(gameIsRunning == False):
playerXSTR = str(playerX)
playerYSTR = str(playerY)
playerXYSTR = ("(" + playerXSTR + ", " + playerYSTR + ")")
font = pygame.font.SysFont("monospace", 15)
playercord = font.render(playerXYSTR, 1, (255,255,255))
screen.blit(playercord, (0, 0))
godMode = font.render("God Mode(Can build)", 1, (255,255,255))
screen.blit(godMode, (0, 20))
for (img, pos) in spriteList:
screen.blit(img, pos)
screen.blit(playerIdle, (playerX, playerY))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((1200, 700))
pygame.display.set_caption('Sandbox')
Game().main(screen)
In my game, you start in "god mode", where you can place objects. When you finish placing objects and go into "run mode", however, the game is in realtime and there's collision and other physical effects.
So the collision I have in my game right now works only part of the time.
When you press space, you spawn the 'house1' image at the location of the mouse and it sets the house1's XY coordinates, and sets house1InWorld = True (which affects collision).
Collision is goes into effect when the house1 image is spawned, because of the house1inWorld attribute. So if you press r (to go into run mode), the collision works for one house1 instance. But when you spawn 2 instances of house1 (at different locations), the collision only works for the recently placed house1.
How should I change my code so that collision works no matter how many house1's you spawn?
You only store the position of the last placed house and check the collision against that.
You should create a list of house positions, and loop though them to check for collision.
Something like this:
houses1XY = []
houses1XY.append(mouse)
#and later
for house1XY in houses1XY:
house1Rect = pygame.Rect(house1XY[0], house1XY[1], 64, 64)
Since you moved the houses to a list, you no longer need the houseInWorld. You already have the information about in the list. You can check if the list is not empty -> so there is a house placed already by evaluating the list. It returns true if it is not empty.
if houses1XY:
#enable realtime etc.

Categories

Resources