Python简单游戏练习——贪吃蛇

2020.7.7

  1. 参考
    python练习实例——用curses在终端实现贪吃蛇小游戏
    curses — 终端字符单元显示的处理
    用 Python 进行 Curses 编程
  2. 运行环境
    Win10子系统Ubuntu 18.04 LTS,miniconda+python 3.8.3
  3. 代码
# -*- coding: utf-8 -*-
#!/usr/bin/env python3

import random
import curses
from curses import textpad
import time

class GameSnake(object):
    def __init__(self):
        self.score = 0
        self.ROW = 20
        self.COL = 48

        self.snake = [[int(self.ROW / 2), int(self.COL / 2)], [int(self.ROW / 2), int(self.COL / 2) + 1], [int(self.ROW / 2), int(self.COL / 2) + 2]] # 左是头,右是尾
        self.food = [int(self.ROW / 2) + 2, int(self.COL / 2)]
        self.blank = []
        for row in range(1, self.ROW - 1):
            for col in range(1, self.COL - 1):
                self.blank.append([row, col])
        for node in self.snake:
            self.blank.remove(node)
        self.direction = ord("a")
     
    def MoveSnake(self, nowwin):
        now_head = self.snake[0][:]
        next_head = now_head[:]
        if self.direction in [ord("w"), ord("W")]:
            next_head[0] = now_head[0] - 1
        elif self.direction in [ord("s"), ord("S")]:
            next_head[0] = now_head[0] + 1
        elif self.direction in [ord("a"), ord("A")]:
            next_head[1] = now_head[1] - 1
        else:
            next_head[1] = now_head[1] + 1
        
        if next_head[0] in [0, self.ROW - 1] or next_head[1] in [0, self.COL - 1] or next_head in self.snake[1:]: # 撞墙或撞蛇身了
            return -1
        elif next_head == self.food: # 吃到食物了
            self.score += 1
            nowwin.addstr(0, 2, (" Score: %d " % self.score))
            self.snake.insert(0, next_head)
            self.blank.remove(next_head)
            self.food = random.choice(self.blank)
            nowwin.addstr(self.food[0], self.food[1], "*")
        else:
            tail = self.snake.pop()
            self.blank.append(tail)
            nowwin.addstr(tail[0], tail[1], " ")
            self.snake.insert(0, next_head)
            self.blank.remove(next_head)
            nowwin.addstr(next_head[0], next_head[1], "*")
            nowwin.refresh()

    def GetInput(self, nowwin):
        self.DIRECTIONS = [ord("w"), ord("W"), ord("s"), ord("S"), ord("a"), ord("A"), ord("d"), ord("D")]

        user_input = nowwin.getch()
        if user_input != -1:
            if user_input not in self.DIRECTIONS + [ord('q'), ord('Q')]: 
                nowwin.addstr(self.ROW + 2, 0, "Wrong operator!")
            else:
                nowwin.addstr(self.ROW + 2, 0, "               ")
            nowwin.refresh()
        return user_input

    def ChangeDirection(self, tmp_direction):
        if tmp_direction == self.direction \
            or tmp_direction in [ord("w"), ord("W")] and self.direction in [ord("s"), ord("S")] \
            or tmp_direction in [ord("s"), ord("S")] and self.direction in [ord("w"), ord("W")] \
            or tmp_direction in [ord("a"), ord("A")] and self.direction in [ord("d"), ord("D")] \
            or tmp_direction in [ord("d"), ord("D")] and self.direction in [ord("a"), ord("A")]:
            return
        self.direction = tmp_direction

    def Play(self, stdscr):
        curses.curs_set(0)
        curses.cbreak()

        nowwin = curses.newwin(self.ROW + 3, self.COL + 2, 0, 0)
        nowwin.keypad(True)
               
        nowwin.clear()
        for node in self.snake:
            nowwin.addstr(node[0], node[1], "*")
        nowwin.addstr(self.food[0], self.food[1], "*")
        nowwin.addstr(self.ROW + 1, 0, "Input: w(up), s(down), a(left), d(right)   q(quit)")
        textpad.rectangle(nowwin, 0, 0, self.ROW - 1, self.COL - 1)
        nowwin.addstr(0, 2, " Score: 0 ")
        nowwin.refresh()

        nowwin.timeout(100)
        while self.MoveSnake(nowwin) != -1: 
            user_input = self.GetInput(nowwin)
            if user_input in [ord('q'), ord('Q')]:
                break
            elif user_input in self.DIRECTIONS:
                self.ChangeDirection(user_input)
            
        return self.score


game = GameSnake()
score = curses.wrapper(game.Play)
print("Game Over! Your total score is : %d" % score)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值