首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当一个矩形发生冲突时,如何让它重新出现在屏幕的不同部分

当一个矩形发生冲突时,如何让它重新出现在屏幕的不同部分
EN

Stack Overflow用户
提问于 2019-11-04 06:42:03
回答 1查看 57关注 0票数 2

我正在制作一个简单的蛇游戏,它所要做的就是显示一个计时器(蛇持续了多长时间),并在蛇击中任何白色(侧面或自身)时显示gameover屏幕。我还必须加入积分系统,这是当蛇吃食物的时候。食物是紫色的,我创建了一行代码,当“蛇”与紫色相撞时,将foodx和foody设置到一个新的位置,但它并没有这样做,而是创建了另外5个食物方块,直到系统崩溃……有什么帮助吗?

以下是我的代码

食物变量-第36行,食物碰撞线282,食物绘制- 297,(或者只是ctrl+F和类型食物,它不会重复那么多)

代码语言:javascript
复制
# 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()

如果可以,请帮助我!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-04 06:58:40

你得到多个食物的原因是碰撞被多次触发。修改代码如下:

代码语言:javascript
复制
# 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“。

解决这个问题的一种方法是删除现有的食物,然后在其他地方重新绘制它:

代码语言:javascript
复制
# 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)的碰撞。

此外,代码还需要处理屏幕外的情况,但我希望您已经知道这一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58685294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档