在python中向pygame snake添加巨石

2024-04-27 19:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个蛇游戏,我用Python做的,我想给他添加巨石,会出现每10个“苹果”他得到,所以你能帮我吗?这是现在的密码

import pygame
import random
__author__ = 'Kfir_Kahanov'
init = pygame.init()


def quit_game():
    """
    this function will quit the game
    :return:
    """
    pygame.quit()
    quit()


# this will set a nice sound when the player gets an apple
BLOP = pygame.mixer.Sound("Blop.wav")
pygame.mixer.Sound.set_volume(BLOP, 1.0)
volume = pygame.mixer.Sound.get_volume(BLOP)
# making colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 155, 0)
BLUE = (0, 0, 255)
YELLOW = (217, 217, 0)
SNAKE_RED = (152, 2, 2)


def display_fill():
    """
    this will fill the screen with a color of my choice
    :return:
    """
    game_display.fill(GREEN)


def mute():
    """
    this will mute the game or unmute it
    :return:
    """
    if volume == 1.0:
        pygame.mixer.Sound.set_volume(BLOP, 0.0)
    else:
        pygame.mixer.Sound.set_volume(BLOP, 10.0)


# all the pygame stuff for the display
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
game_display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The hungry Cobra")
ICON = pygame.image.load("apple_icon.png")
pygame.display.set_icon(ICON)
pygame.display.update()

# deciding on FPS, the size of the snake, apples, and making the fonts for the text

CLOCK = pygame.time.Clock()
BLOCK_SIZE = 20
APPLE_THICKNESS = 30
fps = 15
# BOULDER_THICKNESS = 30

direction = "right"  # deciding the starting direction
tiny_font = pygame.font.SysFont("comicsansms", 10)
small_font = pygame.font.SysFont("comicsansms", 25)
med_font = pygame.font.SysFont("comicsansms", 50)
large_font = pygame.font.SysFont("comicsansms", 80)


def text_objects(text, color, size):
    """
    defining the text
    :param text:
    :param color:
    :param size:
    :return:
    """
    global text_surface
    if size == "tiny":
        text_surface = tiny_font.render(text, True, color)
    if size == "small":
        text_surface = small_font.render(text, True, color)

    if size == "medium":
        text_surface = med_font.render(text, True, color)

    if size == "large":
        text_surface = large_font.render(text, True, color)
    return text_surface, text_surface.get_rect()


# loading apple and snake img
IMG = pygame.image.load("snake_head.png")
APPLE_IMG = pygame.image.load("apple_icon.png")


# BOULDER_IMG = pygame.image.load("boulder.png")


def rand_apple_gen():
    """
    making apple function
    :return:
    """
    rand_apple_x = round(random.randrange(10, DISPLAY_WIDTH - APPLE_THICKNESS))  # / 10.0 * 10.0
    rand_apple_y = round(random.randrange(10, DISPLAY_HEIGHT - APPLE_THICKNESS))  # / 10.0 * 10.0
    return rand_apple_x, rand_apple_y


"""
def rand_boulder_gen():

    making the boulder parameters
    :return:

    rand_boulder_x = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
    rand_boulder_y = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
    return rand_boulder_x, rand_boulder_y
    """


def message(msg, color, y_displace=0, size="small"):
    """
    making a function for the making of the text
    :param msg:
    :param color:
    :param y_displace:
    :param size:
    :return:
    """
    text_surf, text_rect = text_objects(msg, color, size)
    text_rect.center = ((DISPLAY_WIDTH / 2), (DISPLAY_HEIGHT / 2) + y_displace)
    game_display.blit(text_surf, text_rect)


def intro_message():
    """
    making the intro
    :return:
    """
    intro = True
    while intro:
        display_fill()
        message("Welcome to ", BLACK, -200, "large")
        message("The hungry Cobra!", BLACK, -100, "large")
        message("Eat apples to grow, but be care full", BLACK)
        message("if you run into yourself or outside the screen", BLACK, 30)
        message("you gonna have a bad time", BLACK, 60)
        message("Press S to start or E to exit", BLACK, 90)
        message("Created by Kfir Kahanov", BLACK, 200, "tiny")
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                display_fill()
                pygame.display.update()
                quit_game()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_m:
                    mute()
                if event.key == pygame.K_s:
                    intro = False
                if event.key == pygame.K_e:
                    display_fill()
                    pygame.display.update()
                    quit_game()


score_edit = 0


def score_f(score):
    """
    making a score_f on the top left
    :param score:
    :return:
    """
    text = small_font.render("Score:" + str(score + score_edit), True, YELLOW)
    game_display.blit(text, [0, 0])


def pause_f():
    """
    making a pause_f screen
    :return:
    """
    pause = True
    if pause:
        message("Paused", RED, -50, "large")
        message("Press R to start over, E to exit or C to continue", BLACK)
        pygame.display.update()

    while pause:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                display_fill()
                pygame.display.update()
                quit_game()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_m:
                    mute()
                if event.key == pygame.K_c or pygame.K_ESCAPE or pygame.K_p:
                    pause = False
                if event.key == pygame.K_r:
                    global score_edit, direction, cheat1, cheat4, cheat3, cheat2
                    direction = "right"
                    score_edit = 0
                    cheat1 = 16
                    cheat2 = 16
                    cheat3 = 16
                    cheat4 = 16
                    game_loop()
                if event.key == pygame.K_e:
                    display_fill()
                    pygame.display.update()
                    quit_game()

        CLOCK.tick(5)


# making cheats
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16


def snake(snake_list):
    """
    defining the snake head
    :param snake_list:
    :return:
    """
    global head
    if direction == "right":
        head = pygame.transform.rotate(IMG, 270)
    elif direction == "left":
        head = pygame.transform.rotate(IMG, 90)
    elif direction == "down":
        head = pygame.transform.rotate(IMG, 180)
    elif direction == "up":
        head = IMG

    game_display.blit(head, (snake_list[-1][0], snake_list[-1][1]))

    for x_n_y in snake_list[:-1]:
        pygame.draw.rect(game_display, SNAKE_RED, [x_n_y[0], x_n_y[1], BLOCK_SIZE, BLOCK_SIZE])


def game_loop():
    """
    this will be the game itself
    :return:
    """
    global cheat1
    global cheat2
    global cheat3
    global cheat4
    global direction
    global fps
    game_exit = False
    game_over = False
    global score_edit
    lead_x = DISPLAY_WIDTH / 2
    lead_y = DISPLAY_HEIGHT / 2
    # rand_boulder_x, rand_boulder_y = -50, -50
    lead_x_change = 10
    lead_y_change = 0
    snake_list = []
    snake_length = 1
    rand_apple_x, rand_apple_y = rand_apple_gen()

    while not game_exit:
        if game_over:
            message("Game over!", RED, -50, "large")
            message("Press E to exit or R to retry.", BLACK, 20, "medium")
            pygame.display.update()
        while game_over:
            fps = 15

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
                    game_over = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_m:
                        mute()
                    if event.key == pygame.K_e:
                        game_exit = True
                        game_over = False
                    if event.key == pygame.K_r:
                        direction = "right"
                        score_edit = 0
                        cheat1 = 16
                        cheat2 = 16
                        cheat3 = 16
                        cheat4 = 16
                        game_loop()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_m:
                    mute()
                if event.key == pygame.K_LEFT and lead_x_change is not BLOCK_SIZE and direction is not "right":
                    lead_x_change = -BLOCK_SIZE
                    lead_y_change = 0
                    direction = "left"
                elif event.key == pygame.K_RIGHT and lead_x_change is not -BLOCK_SIZE and direction is not "left":
                    lead_x_change = BLOCK_SIZE
                    lead_y_change = 0
                    direction = "right"

                elif event.key == pygame.K_UP and lead_y_change is not BLOCK_SIZE and direction is not "down":
                    lead_y_change = -BLOCK_SIZE
                    lead_x_change = 0
                    direction = "up"
                elif event.key == pygame.K_DOWN and lead_y_change is not -BLOCK_SIZE and direction is not "up":
                    lead_y_change = BLOCK_SIZE
                    lead_x_change = 0
                    direction = "down"
                elif event.key == pygame.K_p:
                    pause_f()
                elif event.key == pygame.K_ESCAPE:
                    pause_f()
                elif event.key == pygame.K_k:  # the cheat
                    cheat1 = 0
                elif event.key == pygame.K_f:
                    cheat2 = 4
                elif event.key == pygame.K_i:
                    cheat3 = 0
                elif event.key == pygame.K_r:
                    cheat4 = 3
                elif cheat1 == 0 and cheat2 == 4 and cheat3 == 0 and cheat4 == 3:
                    score_edit = 10000
        if lead_x >= DISPLAY_WIDTH or lead_x < 0 or lead_y >= DISPLAY_HEIGHT or lead_y < 0:
            game_over = True

        lead_x += lead_x_change
        lead_y += lead_y_change

        display_fill()

        game_display.blit(APPLE_IMG, (rand_apple_x, rand_apple_y))

        snake_head = [lead_x, lead_y]
        snake_list.append(snake_head)
        if len(snake_list) > snake_length:
            del snake_list[0]
        for eachSegment in snake_list[:-1]:
            if eachSegment == snake_head:
                game_over = True

        snake(snake_list)
        score_f(snake_length * 10 - 10)

        pygame.display.update()

        if rand_apple_x < lead_x < rand_apple_x + APPLE_THICKNESS or rand_apple_x < lead_x + BLOCK_SIZE < rand_apple_x \
                + APPLE_THICKNESS:
            if rand_apple_y < lead_y < rand_apple_y + APPLE_THICKNESS or rand_apple_y < lead_y + BLOCK_SIZE < \
                    rand_apple_y + APPLE_THICKNESS:
                pygame.mixer.Sound.play(BLOP)
                rand_apple_x, rand_apple_y = rand_apple_gen()
                snake_length += 1
                fps += 0.15
                """
                if snake_length * 10 - 10 == 20:
                    rand_boulder_x, rand_boulder_y = rand_boulder_gen()
                    game_display.blit(BOULDER_IMG, (rand_boulder_x, rand_boulder_y))



        elif rand_boulder_x < lead_x < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_x < lead_x + BLOCK_SIZE < \
                rand_boulder_x + BOULDER_THICKNESS:
            if rand_boulder_x < lead_y < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_y < lead_y + BLOCK_SIZE < \
                    rand_boulder_y + BOULDER_THICKNESS:
                game_over = True
                """
        CLOCK.tick(fps)
    display_fill()

pygame.display.update()
quit_game()


intro_message()
game_loop()

Tags: thekeytexteventgameappleifdisplay
1条回答
网友
1楼 · 发布于 2024-04-27 19:32:12

也许可以试着解释一下你所做的尝试以及为什么它不起作用。那样你会得到更好的帮助。你知道吗

从你的代码中我可以看到。。。。你知道吗

在注释掉的代码中,您似乎在正确的轨道上。在游戏循环中评估蛇的长度或分数变量,然后在屏幕上生成一个随机的巨石。下一步就是处理所有巨石的碰撞逻辑,我看到了两种方法。第一种方法是创建一个boulder属性列表,比如x,y位置,类似于snake列表。第二种方法是为boulders创建一个类,然后当分数或snake length达到10时,创建一个新的boulder对象。使用类可以使冲突逻辑更易于处理。你知道吗

相关问题 更多 >