如何让守护者在python和pygame中追逐忍者?

时间:2017-04-14 04:46:41

标签: python pygame

当你试图收集寿司时,我试图让忍者追逐忍者。但是当我尝试运行代码时,它只是让警卫向右移动(到屏幕上运行的地方但从未返回到屏幕上)并且不会试图追逐忍者。我希望能够让警卫在屏幕上追逐忍者。如果我的代码没有充分理解,我会提前道歉。这对我来说都是新的。我目前正在使用Python 3.2.5来运行此代码。我如何把它带到守卫追逐忍者的地方?

import pygame
import time
import random

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('The Hungry Sushi Warrior')

clock = pygame.time.Clock()
block_size = 40
SushiThickness = 40
GuardThickness = 50
FPS = 15

direction = "right"
smallfont = pygame.font.SysFont("comicsansms", 18)
medfont = pygame.font.SysFont("comicsansms", 40)
largefont = pygame.font.SysFont("comicsansms", 80)

def pause():

    paused = True

    while paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    paused = False

                elif event.key == pygame.K_q:
                    pygame.quit()
                    quit()

        gameDisplay.fill(white)
        message_to_screen("Paused",
                          black,
                          -100,
                          size = "large")
        message_to_screen("Press C to continue or Q to quit.",
                          black,
                          25)
        pygame.display.update()
        clock.tick(5)

def gamelives(lives):
    text = smallfont.render("Lives: "+str(lives), True, black)
    gameDisplay.blit(text, [700, 0])

def score(score):
    text = smallfont.render("Score: "+str(score), True, black)
    gameDisplay.blit(text, [0, 0])

def ninjaGuardGen():
    randGuardX = round(random.randrange(0, display_width-GuardThickness))
    randGuardY = round(random.randrange(0, display_height-GuardThickness))

    return randGuardX, randGuardY

def randSushiGen():
    randSushiX = round(random.randrange(0, display_width-SushiThickness))
    randSushiY = round(random.randrange(0, display_height-SushiThickness))

    return randSushiX, randSushiY

def game_intro():

    intro = True

    while intro:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    intro = False
                if event.key == pygame.K_q:
                    pygame.quit()
                    quit()

        gameDisplay.fill(white)
        message_to_screen("Welcome to The Hungry Sushi Warrior",
                           green,
                           -100,
                           size = "medium")
        message_to_screen("The objective of the game is to eat the different sushi",
                          black,
                          -30)
        message_to_screen("The more sushi you eat the faster the guards move and the more upgrades you get",
                          black,
                          10)
        message_to_screen("If you run into the edges or if you run into a guard you die!",
                          black,
                          50)
        message_to_screen("Press C to play, P to pause, or Q to quit.",
                          black,
                          180)
        pygame.display.update()
        clock.tick(15)

def guard(block_size, guardList):
    global guardHead

    if guardDirection == "rght":
       guardHead = pygame.transform.rotate(guardimg, 0)

    elif guardDirection == "left":
        gaurdHead = pygame.transform.rotate(guardimg, 0)

    elif guardDirection == "up":
        guardHead = guardimg

    else: 
        guardHead = pygame.transform.rotate(guardimg, 0)

    if len(guardList) == 1:
        gameDisplay.blit(guardHead, (guardList[0][0], guardList[0][1]))
    else:
        gameDisplay.blit(guardHead, (guardList[-1][0], guardList[-1][1]))


def ninja(block_size, ninjaList):

    if direction == "right":
        head = pygame.transform.rotate(ninjaimg, 270)

    if direction == "left":
        head = pygame.transform.rotate(ninjaimg, 90)

    if direction == "up":
        head = ninjaimg

    if direction == "down":
        head = pygame.transform.rotate(ninjaimg, 180)

    if len (ninjaList) == 1:
        gameDisplay.blit(head,(ninjaList[0][0], ninjaList[0][1]))
    else:
        gameDisplay.blit(head, (ninjaList[-1][0], ninjaList[-1][1]))

    # for XnY in ninjaList[:-1]:
        # pygame.draw.rect(gameDisplay, green, [XnY[0], XnY[1], block_size, block_size])

def text_objects(text, color, size):
    if size == "small":
        textSurface = smallfont.render(text, True, color)
    elif size == "medium":
        textSurface = medfont.render(text, True, color)
    elif size == "large":
        textSurface = largefont.render(text, True, color)

    return textSurface, textSurface.get_rect()

def message_to_screen(msg, color, y_displace = 0, size = "small"):
    textSurf, textRect = text_objects(msg, color, size)
    textRect.center = (display_width/2), (display_height/2) + y_displace
    gameDisplay.blit(textSurf, textRect)

def gameLoop():
    guardStartX, guardStartY = ninjaGuardGen()
    global direction
    global guardDirection
    ninjascore = 0
    lives = 3
    direction = 'right'
    guardDirection = 'right'
    gameExit = False
    gameOver = False

    lead_x = display_width/2
    lead_y = display_height/2

    speed = 15

    guardSpeed = 7

    guardX = guardStartX
    guardY = guardStartY


    guardXChange = guardSpeed
    guardYChange = 0

    lead_x_change = speed
    lead_y_change = 0


    guardList = []
    guardLength = 1

    ninjaList = []
    ninjaLength = 1

    randSushiX, randSushiY = randSushiGen()

    randGuardX, randGuardY = ninjaGuardGen()



    while not gameExit:

        while gameOver == True:
            gameDisplay.fill(white)
            message_to_screen("Game Over",
                              red, -50,
                              size = "large")
            message_to_screen("Press C to play agian or Q to quit",
                              black,
                              50,
                              size = "medium")

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameOver = False
                    gameExit = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()

            pygame.display.update()

        gameLives = False
        while gameOver == False:
            GuardDirections = ['left', 'right', 'up', 'down']
            GetGuardDirectionNum = round(random.randrange(0, len(GuardDirections)))
            guardDirection = GuardDirections[GetGuardDirectionNum]
            if guardDirection == 'left':
                GuardXChange = -guardSpeed
                GuardYChange = 0
            elif guardDirection == 'right':
                GuardXChange = guardSpeed
                GuardYChange = 0
            elif guardDirection == 'up':
                GuardYChange = -guardSpeed
                GuardXChange = 0
            elif guardDirection == 'down':
                GuardYChange = guardSpeed
                GuardXChange = 0

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameExit = True
                    gameOver = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        direction = "left"
                        lead_x_change = -speed
                        lead_y_change = 0
                    elif event.key == pygame.K_RIGHT:
                        direction = "right"
                        lead_x_change = speed
                        lead_y_change = 0
                    elif event.key == pygame.K_UP:
                        direction = "up"
                        lead_y_change = -speed
                        lead_x_change = 0
                    elif event.key == pygame.K_DOWN:
                        direction = "down"
                        lead_y_change = speed
                        lead_x_change = 0
                    elif event.key == pygame.K_p:
                        pause()

            if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
                gameOver = True

            lead_x += lead_x_change
            lead_y += lead_y_change

            guardX += guardXChange
            guardY += guardYChange


            gameDisplay.fill(white)

            gameDisplay.blit(sushiimg, (randSushiX, randSushiY))


            guardHead = []
            guardHead.append(guardX)
            guardHead.append(guardY)
            guardList.append(guardHead)

            ninjaHead = []
            ninjaHead.append(lead_x)
            ninjaHead.append(lead_y)
            ninjaList.append(ninjaHead)

##            if len(ninjaHead) > ninjaLength:
##                del ninjaList[0]

            score(ninjascore)


            gamelives(lives)

            guard(block_size, guardList)

            ninja(block_size, ninjaList)

            pygame.display.update()

            if lead_x > randGuardX and lead_x < randGuardX + GuardThickness or lead_x + block_size > randGuardX and lead_x + block_size < randGuardX + GuardThickness:
                if lead_y > randGuardY and lead_y < randGuardY + GuardThickness:
                    randGuardX, randGuardY = ninjaGuardGen()
                    lives -= 1
                    if lives == 0:
                        gameOver = True
                        gameDisplay.fill(white)
                        message_to_screen("Game Over",
                                  red, -50,
                                  size = "large")
                        message_to_screen("Press C to play agian or Q to quit",
                                  black,
                                  50,
                                  size = "medium")
                    else:
                        gameOver = False

                elif lead_y + block_size > randGuardY and lead_y + block_size < randGuardY + GuardThickness:
                    randGuardX, randGuardY = ninjaGuardGen()
                    lives -= 1
                    if lives == 0:
                        gameOver = True
                        gameDisplay.fill(white)
                        message_to_screen("Game Over",
                                  red, -50,
                                  size = "large")
                        message_to_screen("Press C to play agian or Q to quit",
                                  black,
                                  50,
                                  size = "medium")
                    else:
                        gameOver = False

            if lead_x > randSushiX and lead_x < randSushiX + SushiThickness or lead_x + block_size > randSushiX and lead_x + block_size < randSushiX + SushiThickness:
                if lead_y > randSushiY and lead_y < randSushiY + SushiThickness:
                    randSushiX, randSushiY = randSushiGen()
                    ninjascore += 1

                elif lead_y + block_size > randSushiY and lead_y + block_size < randSushiY + SushiThickness:
                    randSushiX, randSushiY = randSushiGen()
                    ninjascore += 1

            if ninjascore != 0 and ninjascore % 10 == 0 and gameLives == False:
                lives += 1
                gameLives = True
                speed += 5
            elif ninjascore % 10 == 1:
                gameLives == False

            pygame.display.update()

            clock.tick(FPS)
    pygame.quit()
    quit()

game_intro()
gameLoop()

1 个答案:

答案 0 :(得分:-1)

警卫方向代码中存在错误。寻找GuardYChange = 10。 (我想应该是0。)

那就是说,我没有看到主循环中的任何逻辑将守卫的位置与忍者的比较。尝试减去后卫的X和领先的X,后卫的Y和领先的Y,并比较哪些是更大的差异。然后让警卫走向那个方向。

就是这样:

dx = lead_x - GuardX
dy = lead_y - GuardY

if abs(dx) > abs(dy):
    # chase left-right
    guardDirection = 'right' if dx > 0 else 'left'
else:
    # chase up-down
    guardDirection = 'down' if dy > 0 else 'up'