前言
最近在用python 做项目,也想对python有多一些了解,之前有用C语言和C++写过python游戏,刚好可以通过这个游戏来对python多一些了解。
文章内容翻译自以下链接
https://www.edureka.co/blog/snake-game-with-pygame/
pygame 介绍
pygame是一个利用SDK库编写的游戏库,SDL全名是Simple DirectMediaLayer,SDK是用C编写的,不过也可以用C++开发,很多很多人已经加入pygame中,pygame会越来越好。
pygame链接地址
www.pygame.org
pygame安装方式
pip install pygame
使用pygame创建一个窗体
import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.quit()
quit()
上面的代码会直接一闪而过,如果想看到窗体,如果加点调试
import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:for event in pygame.event.get():print(event) #prints out all the actions that take place on the screenpygame.quit()
quit()
输出
update
函数是用来接收窗体的触发事件,比如点击窗体,按键响应等等。还有一个类似的函数是filp()
上面的代码可以看到窗体,鼠标点击滑动也能收到事件,但是点击关闭窗体并没有响应,因为我们代码里面没有接收这个事件,修改代码如下。
import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:for event in pygame.event.get():if event.type==pygame.QUIT:game_over=Truepygame.quit()
quit()
创建一个贪吃蛇的基础模块
代码如下,这个部分代码比较简单,可以看到一个简单的贪吃蛇颜色块
import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))pygame.display.set_caption('Snake game by Edureka')blue=(0,0,255)
red=(255,0,0)game_over=False
while not game_over:for event in pygame.event.get():if event.type==pygame.QUIT:game_over=Truepygame.draw.rect(dis,blue,[200,150,10,10])pygame.display.update()
pygame.quit()
quit()
让贪吃蛇可以随着按键控制移动
import pygamepygame.init()white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)dis = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake Game by Edureka')game_over = Falsex1 = 300
y1 = 300x1_change = 0
y1_change = 0clock = pygame.time.Clock()while not game_over:for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -10y1_change = 0elif event.key == pygame.K_RIGHT:x1_change = 10y1_change = 0elif event.key == pygame.K_UP:y1_change = -10x1_change = 0elif event.key == pygame.K_DOWN:y1_change = 10x1_change = 0x1 += x1_changey1 += y1_changedis.fill(white)pygame.draw.rect(dis, black, [x1, y1, 10, 10])pygame.display.update()clock.tick(30)pygame.quit()
quit()
动图如下:
墙壁撞击检测
import pygame
import time
pygame.init()white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake Game by Edureka')game_over = Falsex1 = dis_width/2
y1 = dis_height/2snake_block=10x1_change = 0
y1_change = 0clock = pygame.time.Clock()
snake_speed=30font_style = pygame.font.SysFont(None, 50)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 = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_over = Truex1 += x1_changey1 += y1_changedis.fill(white)pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])pygame.display.update()clock.tick(snake_speed)message("You lost",red)
pygame.display.update()
time.sleep(2)pygame.quit()
quit()
给贪吃蛇添加食物
import pygame
import time
import randompygame.init()white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)dis_width = 800
dis_height = 600dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')clock = pygame.time.Clock()snake_block = 10
snake_speed = 30font_style = pygame.font.SysFont(None, 30)def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width/3, dis_height/3])def gameLoop(): # creating a functiongame_over = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(white)message("You Lost! Press Q-Quit or C-Play Again", red)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.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("Yummy!!")clock.tick(snake_speed)pygame.quit()quit()gameLoop()
如果贪吃蛇吃到食物的话,就会输出打印消息Yummy!!
.
如果贪吃蛇碰到食物,让贪吃蛇变长
import pygame
import time
import randompygame.init()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 = 600
dis_height = 400dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')clock = pygame.time.Clock()snake_block = 10
snake_speed = 15font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)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 = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0snake_List = []Length_of_snake = 1foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(blue)message("You Lost! Press C-Play Again or Q-Quit", red)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.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_close = Trueour_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.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0Length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()gameLoop()
增加分数显示
import pygame
import time
import randompygame.init()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 = 600
dis_height = 400dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Edureka')clock = pygame.time.Clock()snake_block = 10
snake_speed = 15font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)def 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 = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0snake_List = []Length_of_snake = 1foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(blue)message("You Lost! Press C-Play Again or Q-Quit", red)Your_score(Length_of_snake - 1)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.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_close = Trueour_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.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0Length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()gameLoop()