import pygame, sys
import random
pygame.init() #Initialization (must be)
pygame.display.set_caption("my game")
# # FPS
clock = pygame.time.Clock()
#Set screen size
screen_width = 1150
screen_height = 648
screen = pygame.display.set_mode((screen_width, screen_height))
# Loading Background Images
background = pygame.image.load ("D:/python coding/no title").png")
# Calling up characters
character = pygame.image.load("D:/python coding/character).png")
pygame.transform.scale(charactor, (40, 40))
charactor_x = 650
charactor_y = 450
enemy1 = pygame.image.load ("D:/python coding/enemy1.png")
pygame.transform.scale(enemy1, (100, 100))
enemy1_x = 100
enemy1_y = 450
# Coordinates to move
to_x = 0
to_y = 0
# Travel speed
Charactor_speed = 1
enemy1_speed = 5
# Event Loop
while True: # For days in the game
dt = clock.tick(150)
For event in pygame.event.get(): # Some event occurs
If event.type == pygame.QUIT: # Release an event that closes the window
pygame.quit() # exit pygame
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
to_x -= Charactor_speed
elif event.key == pygame.K_RIGHT:
to_x += Charactor_speed
elif event.key == pygame.K_UP:
to_y -= Charactor_speed
elif event.key == pygame.K_DOWN:
to_y += Charactor_speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
charactor_x += to_x * dt
charactor_y += to_y * dt
if charactor_x < 0:
charactor_x = 0
elif charactor_x > 1150:
charactor_x = 1150
if charactor_y < 0:
charactor_y = 0
elif charactor_y > 450:
charactor_y = 450
enemy1_x += enemy1_speed
# # crash event
charactor_rect = charactor.get_rect()
charactor_rect.left = charactor_x
charactor_rect.top = charactor_y
enemy1_rect = enemy1.get_rect()
enemy1_rect.left = enemy1_x
enemy1_rect.top = enemy1_y
#Confirm collision
if charactor_rect.colliderect(enemy1_rect):
del enemy1
screen.blit(background,(0,0)) #Drawing a background
screen.blit(character, (character_x, character_y)) # Draw a character
screen.blit(enemy1, (enemy1_x, enemy1_y))
pygame.display.update() # Redraw game screen
It works well, but when my character and my enemy collide, the enemy must disappear, but when they collide, the game turns off and says NameError: name 'enemy1' is not defined. Let me know what's wrong!
pygame python
#conflict check
if charactor_rect.colliderect(enemy1_rect):
del enemy1
enemy1
becomes del
while riding the if condition of this phrase. First of all, this is the problem.
© 2024 OneMinuteCode. All rights reserved.