PyGame貪吃蛇的實(shí)現(xiàn)代碼示例
更新時(shí)間:2018年11月21日 14:48:37 作者:Harpsichord1207
貪吃蛇是款經(jīng)典游戲,本文將帶你一步步用python語言實(shí)現(xiàn)一個(gè)貪吃蛇小游戲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
最近幫人做了個(gè)貪吃蛇的游戲(交作業(yè)用),很簡單,界面如下:
開始界面:
游戲中界面:
是不是很簡單、樸素。(歡迎大家訪問GitHub)
游戲是基于PyGame
框架制作的,程序核心邏輯如下:
- 游戲界面分辨率是640*480,蛇和食物都是由1個(gè)或多個(gè)20*20像素的正方形塊兒(為了方便,下文用點(diǎn)表示20*20像素的正方形塊兒)組成,這樣共有32*24個(gè)點(diǎn),使用pygame.draw.rect來繪制每一個(gè)點(diǎn);
- 初始化時(shí)蛇的長度是3,食物是1個(gè)點(diǎn),蛇初始的移動的方向是右,用一個(gè)數(shù)組代表蛇,數(shù)組的每個(gè)元素是蛇每個(gè)點(diǎn)的坐標(biāo),因此數(shù)組的第一個(gè)坐標(biāo)是蛇尾,最后一個(gè)坐標(biāo)是蛇頭;
- 游戲開始后,根據(jù)蛇的當(dāng)前移動方向,將蛇運(yùn)動方向的前方的那個(gè)點(diǎn)append到蛇數(shù)組的末位,再把蛇尾去掉,蛇的坐標(biāo)數(shù)組就相當(dāng)于往前挪了一位;
- 如果蛇吃到了食物,即蛇頭的坐標(biāo)等于食物的坐標(biāo),那么在第2點(diǎn)中蛇尾就不用去掉,就產(chǎn)生了蛇長度增加的效果;食物被吃掉后,隨機(jī)在空的位置(不能與蛇的身體重合)再生成一個(gè);
- 通過PyGame的event監(jiān)控按鍵,改變蛇的方向,例如當(dāng)蛇向右時(shí),下一次改變方向只能向上或者向下;
- 當(dāng)蛇撞上自身或墻壁,游戲結(jié)束,蛇頭裝上自身,那么蛇坐標(biāo)數(shù)組里就有和舌頭坐標(biāo)重復(fù)的數(shù)據(jù),撞上墻壁則是蛇頭坐標(biāo)超過了邊界,都很好判斷;
- 其他細(xì)節(jié):做了個(gè)開始的歡迎界面;食物的顏色隨機(jī)生成;吃到實(shí)物的時(shí)候有聲音提示等。
代碼:
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @version: v1.0 @author: Harp @contact: liutao25@baidu.com @software: PyCharm @file: MySnake.py @time: 2018/1/15 0015 23:40 """ import pygame from os import path from sys import exit from time import sleep from random import choice from itertools import product from pygame.locals import QUIT, KEYDOWN def direction_check(moving_direction, change_direction): directions = [['up', 'down'], ['left', 'right']] if moving_direction in directions[0] and change_direction in directions[1]: return change_direction elif moving_direction in directions[1] and change_direction in directions[0]: return change_direction return moving_direction class Snake: colors = list(product([0, 64, 128, 192, 255], repeat=3))[1:-1] def __init__(self): self.map = {(x, y): 0 for x in range(32) for y in range(24)} self.body = [[100, 100], [120, 100], [140, 100]] self.head = [140, 100] self.food = [] self.food_color = [] self.moving_direction = 'right' self.speed = 4 self.generate_food() self.game_started = False def check_game_status(self): if self.body.count(self.head) > 1: return True if self.head[0] < 0 or self.head[0] > 620 or self.head[1] < 0 or self.head[1] > 460: return True return False def move_head(self): moves = { 'right': (20, 0), 'up': (0, -20), 'down': (0, 20), 'left': (-20, 0) } step = moves[self.moving_direction] self.head[0] += step[0] self.head[1] += step[1] def generate_food(self): self.speed = len(self.body) // 16 if len(self.body) // 16 > 4 else self.speed for seg in self.body: x, y = seg self.map[x//20, y//20] = 1 empty_pos = [pos for pos in self.map.keys() if not self.map[pos]] result = choice(empty_pos) self.food_color = list(choice(self.colors)) self.food = [result[0]*20, result[1]*20] def main(): key_direction_dict = { 119: 'up', # W 115: 'down', # S 97: 'left', # A 100: 'right', # D 273: 'up', # UP 274: 'down', # DOWN 276: 'left', # LEFT 275: 'right', # RIGHT } fps_clock = pygame.time.Clock() pygame.init() pygame.mixer.init() snake = Snake() sound = False if path.exists('eat.wav'): sound_wav = pygame.mixer.Sound("eat.wav") sound = True title_font = pygame.font.SysFont('arial', 32) welcome_words = title_font.render('Welcome to My Snake', True, (0, 0, 0), (255, 255, 255)) tips_font = pygame.font.SysFont('arial', 24) start_game_words = tips_font.render('Click to Start Game', True, (0, 0, 0), (255, 255, 255)) close_game_words = tips_font.render('Press ESC to Close', True, (0, 0, 0), (255, 255, 255)) gameover_words = title_font.render('GAME OVER', True, (205, 92, 92), (255, 255, 255)) win_words = title_font.render('THE SNAKE IS LONG ENOUGH AND YOU WIN!', True, (0, 0, 205), (255, 255, 255)) screen = pygame.display.set_mode((640, 480), 0, 32) pygame.display.set_caption('My Snake') new_direction = snake.moving_direction while 1: for event in pygame.event.get(): if event.type == QUIT: exit() elif event.type == KEYDOWN: if event.key == 27: exit() if snake.game_started and event.key in key_direction_dict: direction = key_direction_dict[event.key] new_direction = direction_check(snake.moving_direction, direction) elif (not snake.game_started) and event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() if 213 <= x <= 422 and 304 <= y <= 342: snake.game_started = True screen.fill((255, 255, 255)) if snake.game_started: snake.moving_direction = new_direction # 在這里賦值,而不是在event事件的循環(huán)中賦值,避免按鍵太快 snake.move_head() snake.body.append(snake.head[:]) if snake.head == snake.food: if sound: sound_wav.play() snake.generate_food() else: snake.body.pop(0) for seg in snake.body: pygame.draw.rect(screen, [0, 0, 0], [seg[0], seg[1], 20, 20], 0) pygame.draw.rect(screen, snake.food_color, [snake.food[0], snake.food[1], 20, 20], 0) if snake.check_game_status(): screen.blit(gameover_words, (241, 310)) pygame.display.update() snake = Snake() new_direction = snake.moving_direction sleep(3) elif len(snake.body) == 512: screen.blit(win_words, (33, 210)) pygame.display.update() snake = Snake() new_direction = snake.moving_direction sleep(3) else: screen.blit(welcome_words, (188, 100)) screen.blit(start_game_words, (236, 310)) screen.blit(close_game_words, (233, 350)) pygame.display.update() fps_clock.tick(snake.speed) if __name__ == '__main__': main()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- pygame實(shí)現(xiàn)貪吃蛇游戲
- python實(shí)戰(zhàn)之利用pygame實(shí)現(xiàn)貪吃蛇游戲(二)
- python實(shí)戰(zhàn)之利用pygame實(shí)現(xiàn)貪吃蛇游戲(一)
- 五分鐘學(xué)會怎么用Pygame做一個(gè)簡單的貪吃蛇
- 使用Python第三方庫pygame寫個(gè)貪吃蛇小游戲
- python 使用pygame工具包實(shí)現(xiàn)貪吃蛇游戲(多彩版)
- pygame實(shí)現(xiàn)貪吃蛇游戲(下)
- pygame實(shí)現(xiàn)貪吃蛇游戲(上)
- 使用pygame模塊編寫貪吃蛇的實(shí)例講解
- pygame實(shí)現(xiàn)貪吃蛇小游戲
相關(guān)文章
Tensorflow 如何從checkpoint文件中加載變量名和變量值
這篇文章主要介紹了Tensorflow 如何從checkpoint文件中加載變量名和變量值的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05pytorch cuda上tensor的定義 以及減少cpu的操作詳解
這篇文章主要介紹了pytorch cuda上tensor的定義 以及減少cpu的操作詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python利用PyMuPDF模塊實(shí)現(xiàn)快速轉(zhuǎn)換PDF文件
PDF是一種廣泛使用的文件格式,可以在任何設(shè)備上查看和打印,那么如何用Python和PyMuPDF制作你想要大小的PDF文件呢,本文就來和大家詳細(xì)講講2023-08-08Python根據(jù)文件后綴實(shí)現(xiàn)文件夾整理
這篇文章主要為大家詳細(xì)介紹了Python如何根據(jù)文件后綴實(shí)現(xiàn)文件夾整理,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的可以參考下2024-02-02