中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PyGame貪吃蛇的實現代碼示例

發布時間:2020-09-30 15:20:38 來源:腳本之家 閱讀:177 作者:Harpsichord1207 欄目:開發技術

最近幫人做了個貪吃蛇的游戲(交作業用),很簡單,界面如下:

開始界面:

PyGame貪吃蛇的實現代碼示例

游戲中界面:

PyGame貪吃蛇的實現代碼示例

是不是很簡單、樸素。(歡迎大家訪問GitHub)

游戲是基于PyGame框架制作的,程序核心邏輯如下:

  • 游戲界面分辨率是640*480,蛇和食物都是由1個或多個20*20像素的正方形塊兒(為了方便,下文用點表示20*20像素的正方形塊兒)組成,這樣共有32*24個點,使用pygame.draw.rect來繪制每一個點;
  • 初始化時蛇的長度是3,食物是1個點,蛇初始的移動的方向是右,用一個數組代表蛇,數組的每個元素是蛇每個點的坐標,因此數組的第一個坐標是蛇尾,最后一個坐標是蛇頭;
  • 游戲開始后,根據蛇的當前移動方向,將蛇運動方向的前方的那個點append到蛇數組的末位,再把蛇尾去掉,蛇的坐標數組就相當于往前挪了一位;
  • 如果蛇吃到了食物,即蛇頭的坐標等于食物的坐標,那么在第2點中蛇尾就不用去掉,就產生了蛇長度增加的效果;食物被吃掉后,隨機在空的位置(不能與蛇的身體重合)再生成一個;
  • 通過PyGame的event監控按鍵,改變蛇的方向,例如當蛇向右時,下一次改變方向只能向上或者向下;
  • 當蛇撞上自身或墻壁,游戲結束,蛇頭裝上自身,那么蛇坐標數組里就有和舌頭坐標重復的數據,撞上墻壁則是蛇頭坐標超過了邊界,都很好判斷;
  • 其他細節:做了個開始的歡迎界面;食物的顏色隨機生成;吃到實物的時候有聲音提示等。

代碼:

#!/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事件的循環中賦值,避免按鍵太快
      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()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

古交市| 垦利县| 图们市| 霍林郭勒市| 安康市| 汉源县| 乐山市| 安达市| 博乐市| 册亨县| 侯马市| 从化市| 台湾省| 新密市| 赤城县| 湖口县| 临夏市| 象山县| 安化县| 永福县| 定安县| 晋中市| 化德县| 汤原县| 岳西县| 江源县| 莆田市| 昌平区| 花莲县| 自贡市| 侯马市| 黄龙县| 益阳市| 伊吾县| 凤山县| 辽阳县| 务川| 韶山市| 安远县| 瑞金市| 昭苏县|