>  기사  >  백엔드 개발  >  Python으로 뱀 게임을 작성하기 위한 코드 예제

Python으로 뱀 게임을 작성하기 위한 코드 예제

Y2J
Y2J원래의
2017-04-27 09:24:318485검색

이 글은 주로 파이썬 스네이크 게임의 작성 코드를 자세하게 소개하고 있습니다. 관심 있는 친구들이 참고하면 좋을 것 같습니다.

요즘 파이썬을 배우고 있는데 연습해 보겠습니다. 명령줄 위의 스네이크는 보통 C 연습 프로젝트인데 한동안 다른 것을 찾을 수 없어서 간단한 문법 연습을 위해 먼저 스네이크를 만들어봤습니다.

파이썬에서는 키보드를 모니터링하기가 번거롭고 C언어에는 kbhit()이 없기 때문에 이 욕심쟁이 뱀이 스스로 움직이지 않게 되는 효과는 다음과 같습니다.

요구 사항: #을 사용하여 테두리를 나타내고, *를 사용하여 음식을 나타내고, o를 사용하여 뱀의 몸을 나타내고, O를 사용하여 뱀의 머리를 나타내고, wsad를 사용하여 이동합니다.

Python 버전: 3.6.1

시스템 환경: Win10

카테고리:

보드: 게임 영역인 체스보드

뱀 : 탐욕스러운 뱀, 각 몸을 기록하여 뱀의 상태를 기록하려면 클릭하세요

게임 : 게임 카테고리

원래는 음식 카테고리를 원했는데 음식 좌표는 하나만 있으면 됩니다 그리고 새로운 음식이 있기 때문에 단순히 목록을 사용하여 좌표를 저장하는 것은 논리적으로 큰 문제가 아닙니다.

소스 코드:

# 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 = &#39;down&#39;
      elif neck[1] > head[1]:
        direction = &#39;left&#39;
      elif neck[1] < head[1]:
        direction = &#39;right&#39;

    if direction == &#39;up&#39;:
      head[0] = head[0] - 1
    elif direction == &#39;down&#39;:
      head[0] = head[0] + 1
    elif direction == &#39;left&#39;:
      head[1] = head[1] - 1
    elif direction == &#39;right&#39;:
      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]) == &#39; &#39;:
        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 &#39;w a s d&#39; are the directions
    operation_dict = {b&#39;w&#39;: &#39;up&#39;, b&#39;W&#39;: &#39;up&#39;, b&#39;s&#39;: &#39;down&#39;, b&#39;S&#39;: &#39;down&#39;, b&#39;a&#39;: &#39;left&#39;, b&#39;A&#39;: &#39;left&#39;, b&#39;d&#39;: &#39;right&#39;, b&#39;D&#39;: &#39;right&#39;}
    op = msvcrt.getch()

    while op != b&#39;q&#39;:
      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) == &#39;*&#39;:
          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) == &#39;#&#39; or self.board.getPoint(new_head) == &#39;o&#39;:
          print(&#39;GG&#39;)
          break

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

game().run()

참고:

1. Python에는 Switch Case 문이 없으므로 Dirt를 사용하여 구현할 수 있습니다.

2. Python의 = 기호는 복사, 복사 참조, 심층입니다. copy는

3을 구현하기 위해 copy의 deepcopy() 함수를 사용해야 합니다. 멤버 함수 내에서도 멤버 변수에 액세스하려면 self를 사용해야 하는데, 이는 C++ 및 JAVA와 매우 다릅니다

위 내용은 Python으로 뱀 게임을 작성하기 위한 코드 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.