广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python贪吃蛇游戏编写代码
  • 532
分享到

Python贪吃蛇游戏编写代码

贪吃蛇代码游戏 2022-06-04 18:06:38 532人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

最近在学python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。 由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃

最近在学python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。

由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下:

查看图片

要求:用#表示边框,用*表示食物,o表示蛇的身体,O表示蛇头,使用wsad来移动

Python版本:3.6.1

系统环境:Win10

类:

  board:棋盘,也就是游戏区域

  snake:贪吃蛇,通过记录身体每个点来记录蛇的状态

  game:游戏类

  本来还想要个food类的,但是food只需要一个坐标,和一个新建,所以干脆使用list来保存坐标,新建food放在game里面,从逻辑上也没有太大问题

源码:


# Write By Guobao
# 2017/4//7
#
# 贪吃蛇
# 用#做边界,*做食物,o做身体和头部
# python 3.6.1

import copy
import random
import os
import msvcrt

# the board class, used to put everything
class board:

  __points =[]

  def __init__(self):
    self.__points.clear()
    for i in range(22):
      line = []
      if i == 0 or i == 21:
        for j in range(22):
          line.append('#')
      else:
        line.append('#')
        for j in range(20):
          line.append(' ')
        line.append('#')
      self.__points.append(line)

  def getPoint(self, location):
    return self.__points[location[0]][location[1]]

  def clear(self):
    self.__points.clear()
    for i in range(22):
      line = []
      if i == 0 or i == 21:
        for j in range(22):
          line.append('#')
      else:
        line.append('#')
        for j in range(20):
          line.append(' ')
        line.append('#')
      self.__points.append(line)

  def put_snake(self, snake_locations):
    # clear the board
    self.clear()

    # put the snake points
    for x in snake_locations:
      self.__points[x[0]][x[1]] = 'o'

    # the head
    x = snake_locations[len(snake_locations) - 1]
    self.__points[x[0]][x[1]] = 'O'

  def put_food(self, food_location):
    self.__points[food_location[0]][food_location[1]] = '*'

  def show(self):
    os.system("cls")
    for i in range(22):
      for j in range(22):
        print(self.__points[i][j], end='')
      print()

# the snake class
class snake:
  __points = []

  def __init__(self):
    for i in range(1, 6):
      self.__points.append([1, i])

  def getPoints(self):
    return self.__points

  # move to the next position
  # give the next head
  def move(self, next_head):
    self.__points.pop(0)
    self.__points.append(next_head)

  # eat the food
  # give the next head
  def eat(self, next_head):
    self.__points.append(next_head)

  # calc the next state
  # and return the direction
  def next_head(self, direction='default'):

    # need to change the value, so copy it
    head = copy.deepcopy(self.__points[len(self.__points) - 1])

    # calc the "default" direction
    if direction == 'default':
      neck = self.__points[len(self.__points) - 2]
      if neck[0] > head[0]:
        direction = 'up'
      elif neck[0] < head[0]:
        direction = 'down'
      elif neck[1] > head[1]:
        direction = 'left'
      elif neck[1] < head[1]:
        direction = 'right'

    if direction == 'up':
      head[0] = head[0] - 1
    elif direction == 'down':
      head[0] = head[0] + 1
    elif direction == 'left':
      head[1] = head[1] - 1
    elif direction == 'right':
      head[1] = head[1] + 1
    return head

# the game
class game:

  board = board()
  snake = snake()
  food = []
  count = 0

  def __init__(self):
    self.new_food()
    self.board.clear()
    self.board.put_snake(self.snake.getPoints())
    self.board.put_food(self.food)

  def new_food(self):
    while 1:
      line = random.randint(1, 20)
      column = random.randint(1, 20)
      if self.board.getPoint([column, line]) == ' ':
        self.food = [column, line]
        return

  def show(self):
    self.board.clear()
    self.board.put_snake(self.snake.getPoints())
    self.board.put_food(self.food)
    self.board.show()


  def run(self):
    self.board.show()

    # the 'w a s d' are the directions
    operation_dict = {b'w': 'up', b'W': 'up', b's': 'down', b'S': 'down', b'a': 'left', b'A': 'left', b'd': 'right', b'D': 'right'}
    op = msvcrt.getch()

    while op != b'q':
      if op not in operation_dict:
        op = msvcrt.getch()
      else:
        new_head = self.snake.next_head(operation_dict[op])

        # get the food
        if self.board.getPoint(new_head) == '*':
          self.snake.eat(new_head)
          self.count = self.count + 1
          if self.count >= 15:
            self.show()
            print("Good Job")
            break
          else:
            self.new_food()
            self.show()

        # 反向一Q日神仙
        elif new_head == self.snake.getPoints()[len(self.snake.getPoints()) - 2]:
          pass

        # rush the wall
        elif self.board.getPoint(new_head) == '#' or self.board.getPoint(new_head) == 'o':
          print('GG')
          break

        # nORMal move
        else:
          self.snake.move(new_head)
          self.show()
      op = msvcrt.getch()

game().run()

笔记:

  1.Python 没有Switch case语句,可以利用dirt来实现

  2.Python的=号是复制,复制引用,深复制需要使用copy的deepcopy()函数来实现

  3.即使在成员函数内,也需要使用self来访问成员变量,这和c++、JAVA很不一样

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: Python贪吃蛇游戏编写代码

本文链接: https://www.lsjlt.com/news/13455.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python贪吃蛇游戏编写代码
    最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。 由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃...
    99+
    2022-06-04
    贪吃蛇 代码 游戏
  • python贪吃蛇游戏代码怎么写
    下面是一个简单的Python贪吃蛇游戏的代码示例:```pythonimport pygameimport random# 游戏窗口...
    99+
    2023-08-14
    python
  • 利用TypeScript编写贪吃蛇游戏
    目录Explanation1. tsconfig.json配置2. HTML & CSS 布局相关3. TS核心逻辑项目源码链接先来康康效果图 我接下来将讲解相关配置和代码...
    99+
    2022-11-13
  • 基于AndroidFlutter编写贪吃蛇游戏
    目录前言开发步骤:1.定义蛇和豆子2.让蛇动起来3.使用陀螺仪来控制蛇4.让蛇吃掉豆子5.吃掉豆子随机生成一个豆子前言 放假期间,小T打算回顾一下经典,想用Flutter做一下小游戏...
    99+
    2022-11-13
  • 怎么用Python写贪吃蛇游戏
    怎么用Python写贪吃蛇游戏,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。前几天,有人提到贪吃蛇,一下子就勾起了我的兴趣,毕竟在那个Nokia称霸的年代,这款游戏可是经典...
    99+
    2023-06-02
  • Java实现贪吃蛇游戏代码怎么写
    以下是一个简单的Java实现贪吃蛇游戏的代码示例:```javaimport java.awt.*;import java.awt....
    99+
    2023-08-09
    Java
  • 原生js编写贪吃蛇小游戏
    本文实例为大家分享了js编写贪吃蛇小游戏的具体代码,供大家参考,具体内容如下 刚学完js模仿着教程,把自己写的js原生小程序。 HTML部分 <!DOCTYPE html&...
    99+
    2022-11-12
  • 手把手教你用322行Python代码编写贪吃蛇游戏
    目录效果图安装和导入 规则初始化设定Surface,变量和显示数字的坐标 函数线程 主要部分总结源码下载 效果图 贪吃蛇是一个很常见的小游戏...
    99+
    2023-02-04
    用python写贪吃蛇 python简易贪吃蛇 python贪吃蛇项目介绍
  • python实现贪吃蛇游戏
    文章目录 1、效果2、实现过程3、代码 1、效果 2、实现过程 导入 Pygame 和 random 模块。初始化 Pygame。设置游戏界面大小、背景颜色和游戏标题。定义颜色常量。...
    99+
    2023-09-29
    python 游戏 pygame
  • python学习笔记05:贪吃蛇游戏代码
    首先安装pygame,可以使用pip安装pygame: pip install pygame 运行以下代码即可: #!/usr/bin/env python import pygame,sys,time,random from pyga...
    99+
    2023-01-30
    学习笔记 贪吃蛇 代码
  • JavaScript如何编写一个贪吃蛇游戏
    这篇文章主要介绍了JavaScript如何编写一个贪吃蛇游戏,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。写的比较乱,有个逻辑错误:蛇吃了果...
    99+
    2022-10-19
  • python用海龟绘图写贪吃蛇游戏
    一个简单的贪吃蛇程序,供大家参考,具体内容如下 如图显示 导入海龟绘图库 from turtle import * from random import randrange 常量设置 food_x = r...
    99+
    2022-06-02
    python 贪吃蛇
  • Python代码实现贪吃蛇小游戏的示例
    这篇文章给大家分享的是有关Python代码实现贪吃蛇小游戏的示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。图示基本准备首先,我们需要安装pygame库,小编通过pip install pygame,很快就安装...
    99+
    2023-06-15
  • QT实现贪吃蛇游戏代码详解
    目录一、新建一个Qt项目二、添加要用到的头文件三、写类声明信息四、对类函数的实现构造函数界面刷新随机奖励的生成移动绘图按键事件判断蛇身是否相撞五、结束一、新建一个Qt项目 新建Qt ...
    99+
    2022-11-12
  • C语言实现贪吃蛇游戏代码
    目录一、实现效果二、部分代码解释总结一、实现效果 键位:使用wasd四个键位来控制方向,按q键退出(注意在终用英文输入法实现键控) 规则:蛇每吃一个豆会得10分,同时身体边长、移速加...
    99+
    2022-11-13
  • Python turtle实现贪吃蛇游戏
    本文实例为大家分享了Python turtle实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 # Simple Snake Game in Python 3 for Beginners import tu...
    99+
    2022-06-02
    python turtle 贪吃蛇
  • python 贪吃蛇代码
    import pygame from pygame.locals import * from sys import exit from pygame.color import THECOLORS import random imp...
    99+
    2023-01-31
    贪吃蛇 代码 python
  • 用js编写简单的贪吃蛇小游戏
    本文实例为大家分享了js编写简单的贪吃蛇小游戏的具体代码,供大家参考,具体内容如下 代码如下: HTML 5 部分 <!DOCTYPE html> <html ...
    99+
    2022-11-12
  • 怎么用最少的JS代码写出贪吃蛇游戏
    这篇文章给大家分享的是有关怎么用最少的JS代码写出贪吃蛇游戏的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。效果图:完整脚本代码:<!doctype html>...
    99+
    2022-10-19
  • Python实现智能贪吃蛇游戏的示例代码
    目录前言基本环境配置实现效果实现代码前言 我想大家都玩过诺基亚上面的贪吃蛇吧,本文将带你一步步用python语言实现一个snake小游戏。 基本环境配置 版本:Python3 系统:...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作