Python之freegames 零代码的22个小游戏集合

yizhihongxing

Python之freegames 零代码的22个小游戏集合攻略

1. 介绍

Python之freegames是一个由Python语言实现的,由22个小游戏组成的集合。这些游戏非常容易上手,因为它们都是使用Python标准库和freegames模块编写的。更重要的是,它们没有任何代码,因此无需担心程序语法错误或逻辑错误。

这些游戏的难度各不相同,既有简单的,也有复杂的。这些游戏包括连连看、2048、弹球、跳跃方块等。

2. 安装

安装Python,访问 https://www.python.org/downloads/ 查找相应版本。

在终端中输入以下命令来安装 freegames

pip install freegames

3. 游戏示例

  1. 连连看
from random import randrange
from turtle import *
from freegames import line

def grid():
    "Draw tic-tac-toe grid."
    line(-67, 200, -67, -200)
    line(67, 200, 67, -200)
    line(-200, -67, 200, -67)
    line(-200, 67, 200, 67)

def drawx(x, y):
    "Draw X player."
    line(x, y, x + 133, y + 133)
    line(x, y + 133, x + 133, y)

def drawo(x, y):
    "Draw O player."
    up()
    goto(x + 67, y + 5)
    down()
    circle(62)

def floor(value):
    "Round value down to grid with square size."
    return ((value + 200) // 133) * 133 - 200

state = {'player': 0}
players = [drawx, drawo]

def tap(x, y):
    "Draw X or O in tapped square."
    x = floor(x)
    y = floor(y)
    player = state['player']
    draw = players[player]
    draw(x, y)
    update()
    state['player'] = not player

def draw():
    "Draw slightly thick tic-tac-toe grid."
    pensize(5)
    grid()
    pensize(1)
    hideturtle()
    tracer(False)
    update()
    onscreenclick(tap)
    done()

draw()

在命令行中输入该代码即可开始游戏。

  1. 2048
"""
2048 5x5 grid version by Filipe Kiss <filipe.kiss@gmail.com>
"""

from itertools import *
from random import *
import os
import sys
import tty
import termios
import atexit

def display(game):
    size = len(game)
    for i in range(size):
        for j in range(size):
            v = game[i][j]
            print("+------", end="")
        print("+")
        for j in range(size):
            v = game[i][j]
            print("|{0: ^6}".format(v), end="")
        print("|")
    for j in range(size):
        print("+------", end="")
    print("+")

def axisRotation(game):
    lines = []
    size = len(game)
    for i in range(size):
        line = []
        for j in range(size):
            line.append(game[size-j-1][i])
        lines.append(line)
    return lines 

def collapse(line):
    def collapsePairs(line):
        i = 1
        while i < len(line):
            if line[i] == line[i-1]:
                line[i-1] += 1
                line[i] = 0
            i += 1
        return line

    res = []
    for i in range(len(line)):
        if line[i] > 0:
            res.append(line[i])
    res = collapsePairs(res)
    while len(res) < len(line):
        res.append(0)

    return res

def slide(game, direction):
    axis = game
    if direction == 'w':     
        axis = axisRotation(game)
        axis = list(transpose(collapse(transpose(axis))))

        axis = axisRotation(axisRotation(axisRotation(axis))))
        game = axis
    elif direction == 's':
        axis = axisRotation(axisRotation(axisRotation(game)))
        axis = list(transpose(collapse(transpose(axis))))

        axis = axisRotation(game)
        game = axis
    elif direction == 'd':
        game = [collapse(line) for line in game]
    elif direction == 'a':
        game = [collapse(line[::-1])[::-1] for line in game]
    return game

def transpose(matrix):
    """
    Transpose matrix nxn.
    """
    size = len(game)
    return [[matrix[j][i] for j in range(size)] for i in range(size)]

def update_board(game):
    game_len = len(game[0])*len(game)
    if not any(x == 0 for row in game for x in row):
        return False, "Game Over"
    if any(x == 2048 for row in game for x in row):
        return False, "You Won"
    if game != slide(slide(game, "w"), "s"):
        return True, None
    if game != slide(slide(game, "d"), "a"):
        return True, None
    return False, None

def get_input():
    x = getch()
    if ord(x) == 27:
        x2 = getch()
        x3 = getch()
        return x+x2+x3
    return x

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        return sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

def init_game():
    """Sets up the game"""
    os.system('clear')
    game = []
    size = 4

    for i in range(size):
        r = []
        for j in range(size):
            r.append(0)
        game.append(r)

    game[randint(0, size-1)][randint(0, size-1)] = 2

    return game

def game_loop():
    """Constantly receives input from user"""
    game = init_game()

    os.system('clear')
    display(game)

    while True:
        x = get_input()
        if x == "q":
            break
        elif x == "A":
            game = slide(game, 'w')
        elif x == "B":
            game = slide(game, 's')
        elif x == "D":
            game = slide(game, 'a')
        elif x == "C":
            game = slide(game, 'd')

        updated, info = update_board(game)
        os.system('clear')
        if info:
            print(info)
            break
        display(game)
        if updated:
            game[randint(0, len(game)-1)][randint(0, len(game[0])-1)] = 2

        updated, info = update_board(game)
        if info:
            print(info)
            break

def reset_terminal():
    termios.tcsetattr(IPT, termios.TCSANOW, old_settings)

if __name__ == '__main__':
    IPT = sys.stdin.fileno()
    old_settings = termios.tcgetattr(IPT)

    atexit.register(reset_terminal)

    game_loop()

在命令行中输入该代码即可开始游戏。

4. 总结

通过Python之freegames,我们可以很容易地制作出不同类型的小游戏,而且不需要编写任何代码。不仅适合初学者,还对有经验的Python用户来说也是一个有趣的挑战。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python之freegames 零代码的22个小游戏集合 - Python技术站

(0)
上一篇 2023年6月3日
下一篇 2023年6月3日

相关文章

  • python3实现mysql导出excel的方法

    下面为大家详细讲解 Python3 实现 MySQL 导出 Excel 的方法。 环境准备 Python3 环境 (建议使用 Python3.6 及以上版本); 第三方库 pymysql、xlwt、xlsxwriter、xlrd(可在命令行通过 pip 工具进行安装); MySQL 数据库。(可通过 官网 下载安装) 导出 Excel 实现 连接 MySQL…

    python 2023年5月13日
    00
  • 使用 python 发送电子邮件:如何形成消息?

    【问题标题】:Send emails using python: how to form the message?使用 python 发送电子邮件:如何形成消息? 【发布时间】:2023-04-07 04:08:02 【问题描述】: 我正在制作一个程序,该程序将从谷歌表中检索数据,这是我一周花费多少的支出日记。成功检索数据后,程序会向我发送一封电子邮件,告诉…

    Python开发 2023年4月8日
    00
  • Python实战小程序利用matplotlib模块画图代码分享

    下面是关于“Python实战小程序利用matplotlib模块画图代码分享”的完整攻略。 1. 安装matplotlib模块 在开始使用matplotlib模块绘图前,我们需要先安装matplotlib模块。可以在终端执行以下命令进行安装: pip install matplotlib 2. 导入matplotlib模块 安装完matplotlib模块后,在…

    python 2023年5月19日
    00
  • python类定义的讲解

    Python类定义的讲解 Python是一种面向对象的编程语言,其中类是面向对象编程最重要的概念之一。类是一种用户定义的数据类型,它封装了数据和操作数据的方法。 定义一个类 定义一个类使用 class 关键字,后面跟着类名。类名通常使用大写字母开头,遵循驼峰命名法。类定义的语法如下: class ClassName: ‘类的帮助信息’ #可选的类文档字符串 …

    python 2023年6月5日
    00
  • python中字符串最常用的十三个处理操作记录

    下面我将详细讲解“python中字符串最常用的十三个处理操作记录”的攻略。 1. 切片操作 字符串切片就是通过指定起始位置和结束位置来截取字符串中的一部分。 s = "Hello World" s1 = s[0:5] # 取出前5个字符,结果为 "Hello" s2 = s[6:] # 取出第7个字符及之后的所有字符,…

    python 2023年6月5日
    00
  • Python进行文件处理的示例详解

    下面我就给你详细讲解“Python进行文件处理的示例详解”的完整攻略。 简介 在Python中,文件处理是非常常见的操作,Python的文件处理模块提供了很多便捷的方法和函数,能够轻松地读取、写入和处理各种文件,比如文本文件、CSV文件、JSON文件等。 具体步骤 下面我们就来看一下Python进行文件处理的一般步骤: 打开文件 使用Python的内置函数o…

    python 2023年5月20日
    00
  • Python 代码实现列表的最小公倍数

    首先需要了解“最小公倍数”的概念。最小公倍数,指的是一个数既是若干数的倍数,且是它们之中最小的那个数。比如,4和6的最小公倍数是12,因为4×3=12,6×2=12。 然后需要了解“列表”的概念。列表是Python中的一种数据类型,它由一系列有序元素组成,可以包含任何类型的数据。列表可以用方括号([])来创建,元素之间用逗号分隔。 接下来,我们可以通过编写P…

    python 2023年6月3日
    00
  • python将html转成PDF的实现代码(包含中文)

    Python将HTML转成PDF的实现代码(包含中文) 在本文中,我们将介绍如何使用Python将HTML转换为PDF。我们将提供两个示例,以帮助读者更好地理解如何实现这个目标。 步骤1:安装必要的库 在使用Python将HTML转换为PDF之前,我们需要安装必要的库。我们将使用以下库: pdfkit:用于将HTML转换为PDF。 wkhtmltopdf:用…

    python 2023年5月15日
    00
合作推广
合作推广
分享本页
返回顶部