使用python game写一个贪吃蛇游戏
生活随笔
收集整理的這篇文章主要介紹了
使用python game写一个贪吃蛇游戏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
最近在用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()最終的效果動圖
總結
以上是生活随笔為你收集整理的使用python game写一个贪吃蛇游戏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kuangbin RMQ
- 下一篇: 增选54位院士,京东副总裁梅涛等18位华