как сделать так, чтобы прямоугольник появлялся в другой части экрана, когда он сталкивался с [исправлено] - PullRequest
2 голосов
/ 04 ноября 2019

Я делаю простую игру со змеями, в которой все, что от нее требуется, это отобразить таймер (как долго длится змея) и показать экран игры, если змея ударит любого белого (по бокам или по себе). Я также должен включить систему баллов, когда змея ест пищу. еда окрашена в ФИОЛЕТОВЫЙ, я создал строку кода, которая говорит, что когда «змея» сталкивается с ФИОЛЕТОВЫМ, установите foodx и foody на новую позицию, но вместо этого он создает еще 5 квадратов пищи, пока система просто не рухнет... любая помощь

вот мой код

переменные пищи - строка 36, столкновение с едой - строка 282, отобранная еда - 297, (или просто Ctrl + F и введите food,его не так много)

# October 14, 2019
# Simple Snake Game

# importing variables
import pygame
import sys
import time
import random

pygame.init()

# colours
WHITE = (255,255,255)
BLACK = (0, 0, 0)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
CADETBLUE = (100,149,237)
SPRINGGREEN = (0,255,127)
PURPLE = (154, 136, 180)

# screen variables
screenX = 800
screenY = 600
screenSize = (screenX, screenY)
screen = pygame.display.set_mode((screenSize), 0)
screenW = screen.get_width() # gets screen width and height
screenH = screen.get_height()
screenCenterX = int(screenW/2) # gets center of screen
screenCenterY = int(screenH/2)
pygame.display.set_caption("Hajar's Snake Game")

# apple (food point) variable
foodX = random.randint(50,700)
foodY = random.randint(50,600)
foodW = 2
foodH = 2
p1_score = 0

# timer text
timerTitle = pygame.font.SysFont("Consolas", 30)

#set up clock to control frames per second of main loop
clock = pygame.time.Clock()

# crash collision variables
collisionX = 0
collisionY = 0
collisionColour = None

screen.fill(BLACK)
pygame.display.update()
clock = pygame.time.Clock()

# snake variables
snakeHeadX = 100
snakeHeadY = 300
snakeHeadW = 10
snakeHeadH = 10
snakeHeadDX = 0
snakeHeadDY = 0

# timer / FPS
startTime = time.perf_counter()
elapsedTime = 0

# set loops to false
intro = True
level = False
game = False
final = False

# loops
while intro:
    FPS = 60
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            intro = False
            level = False
            game = False
            final = False
            # code for moving snake by itself for the start animation
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_c: # when c is pressed the intro closes and opens the levels up
                intro = False
                level = True
                pygame.display.update()
            elif event.key == pygame.K_q:
                sys.exit()       
        elif intro == True:
            snakeHeadDX = 1
            smnakeHeadDY = 0
     # makes the snake turn by itself       
    if snakeHeadX > 770:
        snakeHeadDX = 0
        snakeHeadDY = 1
    if snakeHeadY > 550:
        snakeHeadDX = -1
        snakeHeadDY = 0
    if snakeHeadX < 20:
        snakeHeadDX = 0
        snakeHeadDY = -1

    # setting the text for the title and instructions
    titleFont = pygame.font.SysFont("arial", 30)
    instructions1Font = pygame.font.SysFont("arial", 27)
    # creates the texts that will be blitted onto the screen
    title = titleFont.render("The Snake Game", True, WHITE)
    instructions1 = instructions1Font.render("Instructions:", True, WHITE)
    instructions2 = instructions1Font.render("- use arrow keys to move the snake", True, WHITE)
    instructions3 = instructions1Font.render("- do not hit the walls or your snake!", True, WHITE)
    instructions4 = instructions1Font.render("- try to collect food to up your score.", True, WHITE)
    instructions5 = instructions1Font.render("Levels:", True, WHITE)
    instructions6 = instructions1Font.render("- easy, slow-paced, points are normal.", True, WHITE)
    instructions7 = instructions1Font.render("- medium, slightly more paced, points are doubled.", True, WHITE)
    instructions8 = instructions1Font.render("- hard, super fast, points are quadrupled", True, WHITE)
    instructions9 = instructions1Font.render("press 'c' to continue to choose level", True, WHITE)


    # blits the texts onto screen
    screen.blit(title, (200,350))
    screen.blit(instructions1, (200,370))
    screen.blit(instructions2, (200,385))
    screen.blit(instructions3, (200,400))
    screen.blit(instructions4, (200,415))
    screen.blit(instructions5, (200,438))
    screen.blit(instructions6, (200,453))
    screen.blit(instructions7, (200,468))
    screen.blit(instructions8, (200,483))
    screen.blit(instructions9, (200,519))

    # moves the snake
    snakeHeadX = snakeHeadX + snakeHeadDX
    snakeHeadY = snakeHeadY + snakeHeadDY

    # draws the snake      
    pygame.draw.rect(screen, WHITE,(snakeHeadX, snakeHeadY, snakeHeadW, snakeHeadH), 0)
    pygame.display.update()

while level:
    clock.tick(FPS)
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            level = False
            # code for moving snake by itself for the start animation
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e: # when e is the easy level starts
                FPS = 60
                level = False
                game = True
                pygame.display.update()
            if event.key == pygame.K_m: # when m is the medium level starts
                FPS = 300
                game = True
                level = False
                pygame.display.update()
            if event.key == pygame.K_h: # when h is the hard level starts
                pygame.display.update()
                FPS = 550
                game = True
                screen.fill(BLACK)
                level = False
                screen.fill(BLACK)
            elif event.key == pygame.K_q:
                sys.exit()  
    # updates the screen
    pygame.display.update()
    # creates the font/size for the levels
    levelTitleFont = pygame.font.SysFont("arial", 30)
    levelFont = pygame.font.SysFont("arial", 27)

    # creates the text content
    levelTitle = levelTitleFont.render("Level Menu:", True, RED)
    easyLevel = levelFont.render("- press 'e' for easy.", True, RED)
    mediumLevel = levelFont.render("- press 'm' for medium.", True, RED)
    hardLevel = levelFont.render("- press 'h' for hard.", True, RED)

    # blits the text onto the screen 
    screen.blit(levelTitle, (100,300))
    screen.blit(easyLevel, (200,390))
    screen.blit(mediumLevel, (200,410))
    screen.blit(hardLevel, (200,430))

    # updates the screen
    pygame.display.update()

while game:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            intro = False
            level = False
            game = False
            final = False
            # code for moving keys
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT and snakeHeadDX != 1:
                snakeHeadDX = -1
                snakeHeadDY = 0
            elif event.key == pygame.K_RIGHT and snakeHeadDX != -1:
                snakeHeadDX = 1
                snakeHeadDY = 0
            elif event.key == pygame.K_UP and snakeHeadDY != 1:
                snakeHeadDX = 0
                snakeHeadDY = -1
            elif event.key == pygame.K_DOWN and snakeHeadDY != -1:
                snakeHeadDX = 0
                snakeHeadDY = 1
            elif event.key == pygame.K_q:
                sys.exit()
            # code for detecting if snake has hit screen
    # right
    if snakeHeadX > screenW - snakeHeadW:
        snakeHeadX = screenCenterX
        snakeHeadY = screenCenterY
        screen.fill(BLACK)
        snakeHeadDX = 0
        snakeHeadDY = 0
    # left
    if snakeHeadX < 0:
        snakeHeadX = screenCenterX
        snakeHeadY = screenCenterY
        screen.fill(BLACK)
        snakeHeadDX = 0
        snakeHeadDY = 0
    # up
    if snakeHeadY < 0:
        snakeHeadX = screenCenterX
        snakeHeadY = screenCenterY
        screen.fill(BLACK)
        snakeHeadDX = 0
        snakeHeadDY = 0
    # down
    if snakeHeadY > screenH - snakeHeadW:
        snakeHeadX = screenCenterX
        snakeHeadY = screenCenterY
        screen.fill(BLACK)
        snakeHeadDX = 0
        snakeHeadDY = 0

    # checking for right side of snake head
    if snakeHeadDX > 0:
            collisionX = snakeHeadX + snakeHeadW + 1
            collisionY = snakeHeadY + snakeHeadH // 2
            collisionColour = screen.get_at((collisionX,collisionY))
    # checking for left side of snake head
    elif snakeHeadDX < 0:
            collisionX = snakeHeadX - 1
            collisionY = snakeHeadY + snakeHeadH // 2
            collisionColour = screen.get_at((collisionX,collisionY))
    # checking for bottom side of snake head
    elif snakeHeadDY > 0:
            collisionX = snakeHeadX + snakeHeadW // 2
            collisionY = snakeHeadY + snakeHeadH + 1
            collisionColour = screen.get_at((collisionX,collisionY))
    # checking for top side of snake head
    elif snakeHeadDY < 0:
            collisionX = snakeHeadX + snakeHeadW // 2
            collisionY = snakeHeadY - 1
            collisionColour = screen.get_at((collisionX,collisionY))

    # resets when the snake collides into itself   
    if collisionColour == RED:
            screen.fill(BLACK)
            snakeHeadX = screenCenterX
            snakeHeadY = screenCenterY
            snakeHeadDX = 0
            snakeHeadDY = 0

    if collisionColour == WHITE:
            screen.fill(BLACK)
            snakeHeadX = screenCenterX
            snakeHeadY = screenCenterY
            snakeHeadDX = 0
            snakeHeadDY = 0
            elapsedTime = int(time.perf_counter() - startTime)

    # when the snake eats food
    if collisionColour == PURPLE:
        foodX = random.randint(50,700)
        foodY = random.randint(50,650)
        p1_score += 1

    # moves the snake
    snakeHeadX = snakeHeadX + snakeHeadDX
    snakeHeadY = snakeHeadY + snakeHeadDY

    #speed
    clock.tick(FPS)

    # draws the snake      
    pygame.draw.rect(screen, WHITE,(snakeHeadX, snakeHeadY, snakeHeadW, snakeHeadH), 0)
    pygame.draw.rect(screen, PURPLE,(foodX, foodY, foodW, foodH), 0)
    pygame.display.update()

while final:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            main = False
            final = False

    ## put code to display score and message here
    ## put code to ask user to play again here


# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()

пожалуйста, помогите, если можете!

1 Ответ

1 голос
/ 04 ноября 2019

Причина, по которой вы получаете несколько продуктов питания, заключается в том, что столкновение происходит несколько раз. Модифицируя код следующим образом:

# when the snake eats food
if collisionColour == PURPLE:
    print("Nom Nom Nom")                # <-- HERE
    # Move the food
    foodX = random.randint(50,700)
    foodY = random.randint(50,650)
    p1_score += 1

Результатом является несколько отпечатков "Nom Nom Nom" за столкновение с продуктом.

Один из способов исправить это - просто стереть существующую еду передперерисовать его в другом месте:

# when the snake eats food
if collisionColour == PURPLE:
    print("Nom Nom Nom")
    # Erase the current food
    pygame.draw.rect(screen, BLACK,(foodX, foodY, foodW, foodH), 0)
    # Move the food
    foodX = random.randint(50,700)
    foodY = random.randint(50,650)
    p1_score += 1

Во время тестирования вашего кода я обнаружил, что иногда он вообще не обнаруживает столкновения с едой. Чтобы это исправить, я бы определил прямоугольник вокруг головы змеи, а затем использовал pygame.rect.collidepoint () для определения столкновения с (foodX, foodY).

Также код должен обрабатыватьза кадром, но я ожидаю, что вы уже знаете это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...