一、前言
之前版本很多小伙伴都覺得難度過高,另外也有粉絲問還能不能精簡代碼,
所以這版降低了難度 (由原來過關增加5km/h改為3.5KM/h)
并通過反射代替IF ELSE的寫法,洗掉了一些冗余的代碼,將代碼由85行壓縮到了68行 (不必要的壓縮代碼是不建議的,這里壓縮代碼只是為了好玩)
<<點我獲取【可直接運行】的檔案,或滑至文末獲取<<
個人在用的人工智能學習網站推薦給大家:captainai
文章目錄(PS:原始碼直接點擊第四項)
- 一、前言
- 二、實作效果
- 三、環境要求
- 四、原始碼分享
- 五、總結
二、實作效果

個人最高紀錄

三、環境要求
- python 3+
- pygame包 安裝命令:打開cmd 輸入:
pip install pygame
四、原始碼分享
import pygame,sys,random
SCREEN,dirction_node = 600, {pygame.K_LEFT:['left',-25],pygame.K_RIGHT:['right',25],pygame.K_UP:['top',-25],pygame.K_DOWN:['top',25]} # 螢屏尺寸,移動的定義
class Snake: # 蛇類
def __init__(self): # 初始化各種需要的屬性 [開始時默認向右/身體塊x5]
self.dirction, self.body = pygame.K_RIGHT, []
[self.add_node() for _ in range(5)]
def add_node(self):
node = pygame.Rect(((self.body[0].left, self.body[0].top) if self.body else (0, 0)) + (25, 25)) # 隨時增加蛇塊
setattr(node, dirction_node[self.dirction][0], getattr(node, dirction_node[self.dirction][0]) + dirction_node[self.dirction][1])
self.body.insert(0, node)
def is_dead(self):
body_h = self.body[0]
if body_h.x not in range(SCREEN) or body_h.y not in range(SCREEN) or body_h in self.body[1:]: # 撞墻、撞自己則死亡
return True
def move(self):
self.add_node()
self.body.pop()
def change_direction(self, curkey): # 改變方向 但是左右、上下不能被逆向改變
LR, UD = [pygame.K_LEFT, pygame.K_RIGHT], [pygame.K_UP, pygame.K_DOWN]
if curkey in LR + UD:
if not ((curkey in LR) and (self.dirction in LR) or (curkey in UD) and (self.dirction in UD)):
self.dirction = curkey
class Food: # 食物類
def __init__(self):
self.rect = pygame.Rect(-25, 0, 25, 25)
def remove(self):
self.rect.x = -25
def set(self):
if self.rect.x == -25:
allpos = [pos for pos in range(75, SCREEN - 75, 25)] # 生成的食物距離墻在75 ~ SCREEN-55 之間
self.rect.left, self.rect.top = random.choice(allpos), random.choice(allpos)
def show_text(screen, pos, text, color, font_size=30):
cur_font = pygame.font.SysFont("SimHei", font_size) # 設定文字樣式
text_fmt = cur_font.render(text, True, color) # 設定文字內容
screen.blit(text_fmt, pos) # 繪制文字
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN, SCREEN))
pygame.display.set_caption('貪吃蛇:是男人就堅持到第10關!')
snake,food,clock, scores, isdead = Snake(),Food(),pygame.time.Clock(), 0, False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
snake.change_direction(event.key)
if event.key == pygame.K_SPACE and isdead: # 死后按space重新
return main()
screen.fill((255, 255, 255))
if not isdead: # 畫蛇身 / 每一步+1分
snake.move()
for rect in snake.body:
pygame.draw.rect(screen, (144, 238, 144), rect)
isdead = snake.is_dead() # 顯示死亡文字
if isdead:
show_text(screen, (150, 200), '翻車了!', (227, 29, 18), 80)
show_text(screen, (50, 320), '是男人就超過45KM/h,按空格鍵重試...', (0, 0, 22))
if food.rect == snake.body[0]: # 當食物rect與蛇頭重合,吃掉 -> Snake增加一個Node
scores += 1 # 食物處理 / 吃到+1分
food.remove()
snake.add_node()
food.set() # 食物投遞
pygame.draw.rect(screen, (233, 150, 122), food.rect)
speed = 10 + scores * 3.5 if scores else 10 # 蛇移動速度
show_text(screen, (20, 550), '關卡:' + str(scores) + ' 速度:' + str(speed) + 'KM/h', (0, 0, 205)) # 顯示得分和速度
pygame.display.update()
clock.tick(speed)
main()
五、總結
再強調一遍:這里減少代碼量只是為了好玩,不必要的壓縮代碼是不建議的!代碼可讀性、可維護性才是我們在編碼中首要考慮的事情!
這也只是隨便弄的一個小玩意,如果真要做游戲還是建議使用游戲引擎,
市面上常見的cocos、unity都是不錯的游戲引擎,能夠讓你開發游戲的效率達到事半功倍的效果
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/347056.html
標籤:AI
下一篇:漏洞深入分析-2021
