首页 > 作文

Pygame代码 制作一个贪吃蛇小游戏

更新时间:2023-04-04 11:54:28 阅读: 评论:0

用到的 pygame 函数

贪吃蛇小游戏用到的函数

功能描述init()初始化 pygamedisplay.t_mode()以元组或列表为参数创建窗口update()更新屏幕quit()用于取消初始化的 pygamet_caption()在屏幕的顶部设置文字event.get()返回所有事件的列表surface.fill()使用纯色填充屏幕time.clock()追踪时间font.font()设置字体

创建屏幕

我们使用函数 display.t_mode() 来创建 pygame 窗口,同时我们还要在程序的开始和结尾处进行 init() quit() 函数,以保证程序可以正确开始和结束。

import pygamepygame.init()dis=pygame.display.t_mode((400,300))pygame.display.update()pygame.quit()quit()

这要我们运行程序,就可以得到如下:

但是这要的代码,我们的程序创建只会一闪而过,下面我们增加一些代码,来保持住程序窗口

import pygamepygame.init()dis=pygame.display.t_mode((400,300))pygame.display.update()pygame.display.t_caption('snake game by edureka')game_over=falwhile not game_over:    for event in pygame.event.get():        print(event)   # 打印出所有事件pygame.quit()quit()

我们增加了游戏窗口的名称,同时还可以在 python 控制台中看到我们在 pygame 窗口上操作时的所有事件

下面我们来增加关闭响应事件

pygame.init()dis = pygame.display.t_mode((400, 300))pygame.display.update()pygame.display.t_caption('贪吃蛇')game_over = falwhile not game_over:    for event in pygame.event.get():        if event.type==pygame.quit:            game_over=truepygame.quit()quit()

至此我们的游戏窗口就设置好了,下面就可以来画 snake

创建 snake

我们首先创建一些颜色变量,用来表示 snakefoodscreen

pygame.init()dis = pygame.display.t_mode((400, 300))pygame.display.update()pygame.display.t_caption('贪吃蛇')blue=(0,0,255)red=(255,0,0)game_over = falwhile not game_over:    for event in pygame.event.get():        if event.type==pygame.quit:            game_over=true    pygame.draw.rect(dis, blue, [200, 150, 10, 10])    pygame.displ关于爱的古诗ay.update()pygame.quit()quit()

这样,一只(条)贪吃蛇就创建完成了,就是那个小蓝点儿

使 snake 动起来

为了实现 snake 的移动,我们需要用到的关键事件是 keydown,它包含四个 key 值,k_up, k_down, k_left, 和 k_right,分别表示向上、向下、向左和向右

pygame.init()pygame.display.t_caption('贪吃蛇')white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)dis = pygame.display.t_mode((800, 600))game_over = falx1 = 300y1 = 300x1_change = 0y1_change = 0clock = pygame.time.clock()while not game_over:    for event in pygame.event.get():        if event.type == pygame.quit:            game_over = true        if event.type == pygame.keydown:            if event.key == pygame.k_left:                x1_change = -10                y1_change = 0            elif event.key == pygame.k_right:                x1_change = 10                y1_change = 0            elif event.key == pygame.k_up:                y1_change = -10                x1_change = 0            elif event.key == pygame.k_down:                y1_change = 10                x1_change = 0    x1 += x1_change    y1 += y1_change    dis.fill(white)    pygame.draw.rect(dis, black, [x1, y1, 10, 10])    pygame.display.update()    clock.tick(30)pygame.quit()quit()

我这里创建了 x1_change y1_change 变量来更新 x 和 y 坐标,使得我们的 snake 可以移动起来

处理 game over

对于贪吃蛇游戏来说,如果 snake 移动出了游戏屏幕,那么游戏就已经失败了,下面我们就来处理这部分逻辑

import pygameimport timepygame.init()pygame.display.t_caption('贪吃蛇')white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)dis_width = 600dis_height = 400dis = pygame.display.t_mode((dis_width, dis_width))game_over = falx1 = dis_width / 2y1 = dis_height / 2snake_block = 10x1_change = 0y1_change = 0clock = pygame.time.clock()snake_speed = 30font_style = pygame.font.font("c:/windows/fonts/stfangso.ttf", 20)def message(msg, color):    mesg = font_style.render(msg, true, color)    dis.blit(mesg, [dis_width / 2, dis_height / 2])while not game_over:    for event in pygame.event.get():        if event.type == pygame.quit:            game_over = true        if event.type == pygame.keydown:            if event.key == pygame.k_left:                x1_change = -snake_block                y1_change = 0            elif event.key == pygame.k_right:                x1_change = snake_block                y1_change = 0            elif event.key == pygame.k_up:                y1_change = -snake_block                x1_change = 0            elif event.key == pygame.k_down:                y1_change = snake_block                x1_change = 0    if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:        game_over = true    x1 += x1_change    y1 += y1_change    dis.fill(white)    pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])    pygame.display.update()    clock.tick(snake_speed)message("你失败了,请重新开始游戏!", red)pygame.display.update()time.sleep(2)pygame.quit()quit()

增加食物

既然是贪吃蛇,当然要投食了,下面我们就来处理食物

import pygameimport timeimport randompygame.init()pygame.display.t_caption('贪吃蛇')white = (255, 255, 255)black = (0, 0, 0)red = (255, 0, 0)blue = (0, 0, 255)dis_width = 800dis_height = 600dis = pygame.display.t_mode((dis_width, dis_height))clock = pygame.time.clock()snake_block = 10snake_speed = 30font_style = pygame.font.font("c:/windows/fonts/stfangso.ttf", 20)def message(msg, color):    mesg = font_style.render(msg, true, color)    dis.blit(mesg, [dis_width / 3, dis_height / 3])def gameloop():  # creating a function    game_over = fal    game_clo = fal    x1 = dis_width / 2    y1 = dis_height / 2    x1_change = 0    y1_change = 0    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0    foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0    while not game_over:        while game_clo == true:            dis.fill(white)            message("你失败了,请重新开始游戏!", red)            pygame.display.update()            for event in pygame.event.get():                if event.type == pygame.keydown:                    if event.key == pygame.k_q:                        game_over = true                        game_clo = fal                    if event.key == pygame.k_c:                        gameloop()        for event in pygame.event.get():            if event.type == pygame.quit:                game_over = true            if event.type == pygame.keydown:                if event.key == pygame.k_left:                    x1_change = -snake_block                    y1_change = 0                elif event.key == pygame.k_right:                    x1_change = snake_block                    y1_change = 0                elif event.key == pygame.k_up:                    y1_change = -snake_block                    x1_change = 0                elif event.key == pygame.k_down:                    y1_change = snake_block                    x1_change = 0        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:            game_clo = true        x1 += x1_change        y1 += y1_change        dis.fill(white)        pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])        pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])        pygame.display.update()        if x1 == foodx and y1 == foody:            print("good!")        clock.tick(snake_speed)    pygame.quit()    quit()gameloop()

我这里创建了一个函数 gameloop 作为我们的主函数,同时还初始化了 snake 的食物,还同时增加了键盘 c 和 q 关键字,来重新开始游戏和退出游戏

snake 的成长

下面我们就开始在 snake 吃掉食物之后,增加 snake 的长度,这也是游戏的基本规则

import pygameimport timeimport randompygame.init()pygame.display.t_caption('贪吃蛇')font_style = pygame.font.font("c:/windows/fonts/stfangso.ttf", 20)score_font = pygame.font.font("c:/windows/fonts/stcaiyun.ttf", 30)white = (255, 255, 255)yellow = (255, 255, 102)black = (0, 0, 0)red = (213, 50, 80)green = (0, 255, 0)blue = (50, 153, 213)dis_width = 600dis_height = 400dis = pygame.display.t_mode((dis_width, dis_height))clock = pygame.time.clock()snake_block = 10snake_speed = 15def our_snake(snake_block, snake_list):    for x in snake_list:        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])def message(msg, color):    mesg = font_style.render(msg, true, color)    dis.blit(mesg, [dis_width / 6, dis_height / 3])def gameloop():    game_over = fal    game_clo = fal    x1 = dis_width / 2    y1 = dis_height / 2    x1_change = 0    y1_change = 0    snake_list = []    length_of_snake = 1    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0    while not game_over:        while game_clo == true:            dis.fill(blue)            message("你失败了,请重新开始游戏!", red)            pygame.display.update()            for event in pygame.event.get():                if event.type == pygame.keydown:                    if event.key == pygame.k_q:                        game_over = true                        game_clo = fal                    if event.key == pygame.k_c:                        gameloop()        for event in pygame.event.get():            if event.type == pygame.quit:                game_over = true            if eve不拘一格的近义词nt.type == pygame.keydown:                if event.key == pygame.k_left:                    x1_change = -snake_block                    y1_change = 0                elif event.key == pygame.k_right:                    x1_change = snake_block                    y1_change = 0                elif event.key == pygame.k_up:                    y1_change = -snake_block                    x1_change = 0                elif event.key == pygame.k_down:                    y1_change = snake_block                    x1_change = 0        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:            game_clo = true        x1 += x1_change        y1 += y1_change        dis.fill(blue)        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])        snake_head = []        snake_head.append(x1)        snake_head.append(y1)        snake_list.append(snake_head)        if len(snake_list) > length_of_snake:            del snake_list[0]        for x in snake_list[:-1]:            if x == snake_head:                game_clo = true        our_snake(snake_block, snake_list)        pygame.display.update()        if x1 == foodx and y1 == foody:            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0            length_of_snake += 1        clock.tick(snake_speed)    pygame.quit()    quit()    gameloop()

展示得分

最后我们来显示得分,毕竟对于游戏来说,玩家的得分还是很重要的

import pygameimport timeimport randompygame.init()pygame.display.t_caption('贪吃蛇')font_style = pygame.font.font("c:/windows/fonts/stfangso.ttf", 20)score_font = pygame.font.font("c:/windows/fonts/stcaiyun.ttf", 30)white = (255, 255, 255)yellow = (255, 255, 102)black = (0, 0, 0)red = (213, 50, 80)green = (0, 255, 0)blue = (50, 153, 213)dis_width = 600dis_height = 400dis = pygame.display.t_mode((dis_width, dis_height))clock = pygame.time.clock()snake_block = 10snake_speed = 15def your_score(score):    value = score_font.render("your score: " + str(score), true, yellow)    dis.blit(value, [0, 0])def our_snake(snake_block, snake_list):    for x in snake_list:        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])def message(msg, color):    mesg = font_style.render(msg, true, color)    dis.blit(mesg, [dis_width / 6, dis_height / 3])def gameloop():    game_over = fal    game_clo = fal    x1 = dis_width / 2    y1 = dis_height / 2    x1_change = 0    y1_change = 0    snake_list = []    length_of_snake = 1    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0    while not game_over:        while game_clo == true:            dis.fill(blue)            message("你失败了,请重新开始游戏!", red)            your_score(length_of_snake - 1)            pyg云南大学排名ame.display.update()            for event in pygame.event.get():                if event.type == pygame.keydown:                    if event.key == pygame.k_q:                        game_over = true                        game_clo = fal                    if event.key == pygame.k_c:                        gameloop()        for event in pygame.event.get():            if event.type == pygame.quit:                game_over = true            if event.type == pygame.keydown:                if event.key == pygame.k_left:                    x1_change = -snake_block     适合情人节发的文案               y1_change = 0                elif event.key == pygame.k_right:                    x1_change = snake_block                    y1_change = 0                elif event.key == pygame.k_up:                    y1_change = -snake_block                    x1_change = 0                elif event.key == pygame.k_down:                    y1_change = snake_block                    x1_change = 0        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:            game_clo = true        x1 += x1_change        y1 += y1_change        di成长的故事作文s.fill(blue)        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])        snake_head = []        snake_head.append(x1)        snake_head.append(y1)        snake_list.append(snake_head)        if len(snake_list) > length_of_snake:            del snake_list[0]        for x in snake_list[:-1]:            if x == snake_head:                game_clo = true        our_snake(snake_block, snake_list)        your_score(length_of_snake - 1)        pygame.display.update()        if x1 == foodx and y1 == foody:            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0            length_of_snake += 1        clock.tick(snake_speed)    pygame.quit()    quit()gameloop()

这里创建了一个 your_score 函数来记录玩家得分

这样,我们就完成了一个简易的贪吃蛇小游戏了

最后的最后,我们再给游戏添加音乐背景,让游戏的时光更加惬意吧

# 播放音乐pygame.init()pygame.mixer.music.load(r"game.mp3")pygame.mixer.music.play()

到此这篇关于100行pygame代码 制作一个贪吃蛇小游戏的文章就介绍到这了,更多相关pygame制作一个贪吃蛇小游戏内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 11:54:26,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/0a198c672442e7fe22d956aea5ebbd65.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Pygame代码 制作一个贪吃蛇小游戏.doc

本文 PDF 下载地址:Pygame代码 制作一个贪吃蛇小游戏.pdf

标签:贪吃蛇   游戏   函数   小游戏
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图