用python自己动手做一个小游戏01

今天我们来用python做一款属于自己的小游戏——贪吃蛇。众所周知哈,pygame入门级游戏应该是非贪吃蛇莫属了,只需要一点简单的算法就能够完美还原童年的感觉。当然了,目前网上的贪吃蛇数量众多,质量参差不齐,直接复制别人的代码多多少少还是有点不安心的。于是乎,我们能不能打造一款完全属于自己的贪吃蛇小游戏呢,让我们来试试吧!

先附上源码:

import pygame as py
import sys, random, time


def RandomColor():
    R = random.randint(0, 200)
    G = random.randint(0, 200)
    B = random.randint(0, 200)
    color = [R, G, B]
    return color


def score(color):
    s = sum(color) / 255 * (10 / 3)
    return s


def food(X):
    position = [10 * random.randint(0, 79), 10 * random.randint(31, 59)]
    while True:
        if position in X:
            position = [10 * random.randint(0, 79), 10 * random.randint(0, 59)]
        else:
            break
    return position


def DrawScore(GameScore, BasicFont):
    py.draw.rect(screen, [255, 255, 255], [0, 0, 800, 30], 0)
    ScoreSurf = BasicFont.render('Score:{}'.format(int(GameScore)), True, (0, 0, 128))
    ScoreRect = ScoreSurf.get_rect()
    ScoreRect.midtop = (400, 0)
    screen.blit(ScoreSurf, ScoreRect)
    py.display.flip()


def ThroughWall():
    global Snake
    if Snake[-1][0] >= 800:
        Snake[-1][0] = 0
    elif Snake[-1][1] >= 600:
        Snake[-1][1] = 0
    elif Snake[-1][1] < 0:
        Snake[-1][1] = 590
    elif Snake[-1][0] < 0:
        Snake[-1][0] = 790


def SnakeMove(Direction):
    global SnakeColor, Snake
    Dele = [0, 0]
    if Direction == 'up':
        SnakeHead = [Snake[-1][0], Snake[-1][1] - 10]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
    elif Direction == 'down':
        SnakeHead = [Snake[-1][0], Snake[-1][1] + 10]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
    elif Direction == 'left':
        SnakeHead = [Snake[-1][0] - 10, Snake[-1][1]]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
    elif Direction == 'right':
        SnakeHead = [Snake[-1][0] + 10, Snake[-1][1]]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
    ThroughWall()
    for rect in range(0, len(Snake)):
        py.draw.rect(screen, SnakeColor[rect], Snake[rect] + [10, 10], 0)
        py.draw.rect(screen, [255, 255, 255], Dele + [10, 10], 0)
        py.display.flip()


def PlaySound_eat():
    global GameVoice
    name = random.randint(1, 3)
    sound = py.mixer.Sound('0{}.wav'.format(name))
    py.mixer.music.set_volume(GameVoice)
    sound.play(0, 0, 1)


def SnakeEatFood():
    global food_position, food_screen, food_list, GameScore, food_color_list, GameVoice
    if len(food_screen) == 1:
        if food_position in Snake:  # 吃到食物
            PlaySound_eat()
            food_list.append(food_position)
            food_position = []
            food_screen = []
            GameScore += 1  # 计算得分
            DrawScore(GameScore, BasicFont)
    elif len(food_screen) == 0:
        food_position = food(Snake)
        food_screen.append(food_position)
        food_color = RandomColor()
        food_color_list.append(food_color)
        py.draw.rect(screen, food_color, food_position + [10, 10], 0)
        py.display.flip()


def SnakeGrowth(Snake):
    global food_list, food_color_list
    if len(food_list) > 0:
        if food_list[0] not in Snake:
            Snake.insert(0, food_list.pop(0))
            SnakeColor.insert(0, food_color_list.pop(0))


def key_contrl(event):
    global Direction, MusicPause, SnakeColor, Snake, GameVoice
    Dele = [0, 0]
    if event.key == py.K_UP and Direction != 'down':
        SnakeHead = [Snake[-1][0], Snake[-1][1] - 10]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
        Direction = 'up'
    elif event.key == py.K_DOWN and Direction != 'up':
        SnakeHead = [Snake[-1][0], Snake[-1][1] + 10]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
        Direction = 'down'
    elif event.key == py.K_LEFT and Direction != 'right':
        SnakeHead = [Snake[-1][0] - 10, Snake[-1][1]]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
        Direction = 'left'
    elif event.key == py.K_RIGHT and Direction != 'left':
        SnakeHead = [Snake[-1][0] + 10, Snake[-1][1]]
        Dele = Snake.pop(0)
        Snake.append(SnakeHead)
        Direction = 'right'
    elif event.key == py.K_SPACE and MusicPause == False:
        py.mixer.music.pause()
        MusicPause = True
    elif event.key == py.K_SPACE and MusicPause == True:
        py.mixer.music.unpause()
        MusicPause = False
    elif event.key == py.K_1:
        GameVoice += 0.1
    elif event.key == py.K_2:
        GameVoice -= 0.1
    ThroughWall()
    for rect in range(0, len(Snake)):
        py.draw.rect(screen, SnakeColor[rect], Snake[rect] + [10, 10], 0)
        py.draw.rect(screen, [255, 255, 255], Dele + [10, 10], 0)
        py.display.flip()


def GameOver(Snake, BasicFont):
    copy_SnakeHead = Snake[-1]
    if Snake.count(copy_SnakeHead) > 1:
        # py.quit()
        OverSurf = BasicFont.render('Game Over', True, (0, 0, 0))
        OverRect = OverSurf.get_rect()
        OverRect.midtop = (400, 300)
        screen.blit(OverSurf, OverRect)
        py.display.flip()
        time.sleep(3)
        sys.exit()


def head_path(food_position, Snake):
    SnakeHead = Snake[-1]
    Dir = []
    if food_position[0] > SnakeHead[0] and food_position[1] > SnakeHead[1]:
        Dir = [3, 1]
    elif food_position[0] < SnakeHead[0] and food_position[1] > SnakeHead[1]:
        Dir = [2, 1]
    elif food_position[0] > SnakeHead[0] and food_position[1] < SnakeHead[1]:
        Dir = [3, 0]
    elif food_position[0] < SnakeHead[0] and food_position[1] < SnakeHead[1]:
        Dir = [2, 0]
    return Dir


def AiContrlSnake(Snake, Direction):
    global food_position
    ShortPath = []
    CopySnake = Snake
    load_path = ['up', 'down', 'left', 'right']
    Dir = head_path(food_position, Snake)
    DirLoadPath = [load_path[Dir[0]], load_path[Dir[1]]]
    # 同方向
    if Direction in DirLoadPath:
        SnakeHead = Snake[-1]
        CopySnake.pop(0)
        SnakeHead_path = [SnakeHead[0] + 2 * (Dir[0] - 2.5) * 10, SnakeHead[1] + 2 * (0.5 - Dir[1]) * 10]
        SnakeHead1 = [SnakeHead[0], SnakeHead_path[1]]
        SnakeHead2 = [SnakeHead_path[0], SnakeHead[1]]
        VirSnake = [SnakeHead1, SnakeHead2]
        path = []
        for S in VirSnake:
            if S in CopySnake:
                path.append(False)
            else:
                path.append(True)


if __name__ == '__main__':
    py.init()
    GameVoice = 0.1  # 定义游戏音效
    py.mixer.music.load('BGM.mp3')  # 加载背景音乐
    py.mixer.music.play(-1, 0.0)  # 循环播放
    py.mixer.music.set_volume(GameVoice)  # 设置音量

    FPSCLOCK = py.time.Clock()
    screen = py.display.set_mode((800, 600))
    py.display.set_caption('至尊彩虹贪吃蛇')
    screen.fill([255, 255, 255])
    py.display.flip()
    BasicFont = py.font.SysFont("'resources/ARBERKLEY.ttf'", 40)

    GameScore = 0
    DrawScore(GameScore, BasicFont)
    food_list, food_screen = [], []
    Snake = [[0, 0], [10, 0], [20, 0]]  # 定义蛇
    SnakeColor = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]  # 定义初始皮肤颜色
    food_color_list = []
    food_position = []
    Direction = 'right'
    Score = 0
    MusicPause = False
    while True:
        SnakeEatFood()
        SnakeMove(Direction)
        GameOver(Snake, BasicFont)
        SnakeGrowth(Snake)
        for event in py.event.get():
            if event.type == py.QUIT:
                sys.exit()
            elif event.type == py.KEYDOWN:
                key_contrl(event)
                SnakeGrowth(Snake)
        py.display.flip()
        FPSCLOCK.tick(11)

最终效果图:

通过以上程序,我们实现了一个彩虹版的贪吃蛇(可以穿越边界),同时每次吃到食物都会弹出一个随机的音效,这里我设置了三款音效。有时间的话,下次我会加入一个排行榜,可以记录每次游戏的时间与最终得分。

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
当然可以,不过这个任务比较复杂,需要一定的编程基础和时间,需要你自己动手实现。以下是一个简单的俄罗斯方块小游戏的代码,你可以参考一下: ```python import pygame import random # 初始化pygame pygame.init() # 设置游戏窗口大小 screen_width = 360 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("俄罗斯方块") # 定义方块大小和颜色 block_size = 30 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) yellow = (255, 255, 0) purple = (128, 0, 128) colors = [red, green, blue, yellow, purple] # 定义方块类型和形状 shapes = [ [[1, 1, 1], [0, 1, 0]], [[0, 2, 2], [2, 2, 0]], [[3, 3, 0], [0, 3, 3]], [[4, 0, 0], [4, 4, 4]], [[0, 0, 5], [5, 5, 5]], [[6, 6], [6, 6]], [[7, 7, 7, 7]] ] # 定义游戏区域和边界 play_width = 10 * block_size play_height = 20 * block_size play_x = (screen_width - play_width) // 2 play_y = screen_height - play_height - 20 top_left_x = play_x top_left_y = play_y - 5 * block_size # 定义方块类 class Block: def __init__(self, shape): self.shape = shape self.color = random.choice(colors) self.x = top_left_x + play_width // 2 - len(shape[0]) // 2 self.y = top_left_y - len(shape) self.rotation = 0 def draw(self): for i in range(len(self.shape)): for j in range(len(self.shape[0])): if self.shape[i][j] != 0: pygame.draw.rect(screen, self.color, (self.x + j * block_size, self.y + i * block_size, block_size, block_size), 0) def move(self, dx, dy): self.x += dx * block_size self.y += dy * block_size def rotate(self): self.rotation = (self.rotation + 1) % len(self.shape) self.shape = rotate_matrix(self.shape) # 旋转矩阵 def rotate_matrix(matrix): return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]) - 1, -1, -1)] # 检查方块是否合法 def is_valid_pos(block, board): for i in range(len(block.shape)): for j in range(len(block.shape[0])): if block.shape[i][j] != 0: x = block.x + j y = block.y + i if x < 0 or x >= play_width // block_size or y < 0 or y >= play_height // block_size or board[y][x] != 0: return False return True # 将方块加入到游戏区域 def add_block_to_board(block, board): for i in range(len(block.shape)): for j in range(len(block.shape[0])): if block.shape[i][j] != 0: x = block.x + j y = block.y + i board[y][x] = block.color # 消除满行 def clear_lines(board): lines_cleared = 0 for i in range(len(board)): if all(block != 0 for block in board[i]): board.pop(i) board.insert(0, [0] * (play_width // block_size)) lines_cleared += 1 return lines_cleared # 绘制游戏区域和方块 def draw_play_area(board, score): font = pygame.font.SysFont(None, 25) label = font.render("Score: " + str(score), True, white) screen.blit(label, (top_left_x, top_left_y - 40)) for i in range(len(board)): for j in range(len(board[0])): pygame.draw.rect(screen, board[i][j], (top_left_x + j * block_size, top_left_y + i * block_size, block_size, block_size), 0) pygame.draw.rect(screen, white, (top_left_x, top_left_y, play_width, play_height), 5) # 主函数 def main(): board = [[0] * (play_width // block_size) for _ in range(play_height // block_size)] score = 0 clock = pygame.time.Clock() block = Block(random.choice(shapes)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: block.move(-1, 0) if not is_valid_pos(block, board): block.move(1, 0) if event.key == pygame.K_RIGHT: block.move(1, 0) if not is_valid_pos(block, board): block.move(-1, 0) if event.key == pygame.K_DOWN: block.move(0, 1) if not is_valid_pos(block, board): block.move(0, -1) if event.key == pygame.K_UP: block.rotate() if not is_valid_pos(block, board): block.rotate() block.move(0, 1) if not is_valid_pos(block, board): block.move(0, -1) add_block_to_board(block, board) lines_cleared = clear_lines(board) score += lines_cleared * 10 block = Block(random.choice(shapes)) if not is_valid_pos(block, board): pygame.quit() quit() screen.fill(black) draw_play_area(board, score) block.draw() pygame.display.update() clock.tick(10) # 运行游戏 if __name__ == '__main__': main() ``` 代码中使用了pygame库来实现游戏界面和操作,具体的实现细节可以自行查阅pygame文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值