贪吃蛇编程代码python_Python贪吃蛇游戏编写代码「建议收藏」

贪吃蛇编程代码python_Python贪吃蛇游戏编写代码「建议收藏」最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下:要求:用#表示边框,用*表示食物,o表示蛇的身体,O表示蛇头,使用wsad来移动Python版本:3.6.1系统环境:Win10类:board:棋盘…

大家好,又见面了,我是你们的朋友全栈君。

贪吃蛇编程代码python_Python贪吃蛇游戏编写代码「建议收藏」

最近在学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很不一样

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154052.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • oracle怎么测试包,用ORACLE自带包测试FUSIONIO的IOPS「建议收藏」

    oracle怎么测试包,用ORACLE自带包测试FUSIONIO的IOPS「建议收藏」settimingonserveroutputondeclarev_max_iopsBINARY_INTEGER;v_max_mbpsBINARY_INTEGER;v_act_latBINARY_INTEGER;begindbms_resource_manager.CALIBRATE_IO(num_physical_disks=>1,max_latency…

    2025年5月22日
    5
  • STL vector用法介绍

    STL vector用法介绍介绍这篇文章的目的是为了介绍std::vector,如何恰当地使用它们的成员函数等操作。本文中还讨论了条件函数和函数指针在迭代算法中使用,如在remove_if()和for_each()中的使用。通过阅读这篇文章读者应该能够有效地使用vector容器,而且应该不会再去使用C类型的动态数组了。 Vector总览vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种

    2022年6月16日
    25
  • Android MVP+RxJava+Retrofit (2) RxJava+Retrofit

    Android MVP+RxJava+Retrofit (2) RxJava+Retrofit

    2021年3月12日
    142
  • matlab中find函数用法[通俗易懂]

    matlab中find函数用法[通俗易懂]1.返回素有非零元素的位置例如:注:竖着数!!2.条件:find(A==1)例如:返回的仍然是位置!3.返回前N个非零元素的位置,find(A,X)例如:4.返回最后一个非零值的位置find(A,1,‘last’)例如:5.返回最后一个非零值的行列位置或者A中非零元素位置例如:6.[a,b,v]=find(A),找出A中非零元素所在的行和列,分别存储在a和b中,…

    2022年7月17日
    9
  • java integer范围值的大小_求最大值最小值的代码

    java integer范围值的大小_求最大值最小值的代码java中的Integer.MAX_VALUE和Integer.MIN_VLAUE最近在刷leetcode的题时,才发现有几道题的利用到Integer类型的最大值和最小值,尤其是在判断是否溢出的时候,有道题就非常经典直接判断最后一位,比如最大值231-1的最后一位是7,而最小值-231的最后一位是8,这样进行一个判断8.字符串转换整数(atoi)这道题对我在面试过程中被问到如何判…

    2022年9月8日
    0
  • RedisClient的安装及基本使用[通俗易懂]

    RedisClient的安装及基本使用[通俗易懂]管理redis的可视化客户端目前较流行的有三个:RedisClient;RedisDesktopManager;RedisStudio.这里目前给大家介绍RedisClient的下载安装及基本使用。RedisClient是Redis客户端的GUI工具,使用Javaswt和jedis编写,可以方便开发者浏览Redis数据库。该软件支持简体中文,非常适合国内用户使用,不需要汉化就可以直接使用。RedisClient将redis数据以资源管理器的界面风格呈现给用户,可以帮助redis

    2022年8月31日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号