
想找一份能直接跑起来的 python简单小游戏代码100行?下面这个接星星小游戏只用了 Python 自带的 tkinter 和 random,不装任何第三方库,整段代码一百行左右:左右方向键或者鼠标移动滑块,接住天上掉下来的彩色圆点,漏掉三个就结束。另存为 game.py,在命令行执行 python game.py 就能玩。
跑之前先确认两件事
第一,检查 Python 版本,命令行输入 python -V 或 python3 -V,3.8 及以上都行。第二,确认 tkinter 可用:执行 python -m tkinter,弹出一个带按钮的小窗口就说明正常。Windows 和 macOS 官方安装包默认自带;Ubuntu、Debian 如果提示 No module named 'tkinter',执行 sudo apt install python3-tk 补上即可。
如果窗口能弹出来但按钮是灰的、或者一闪而过,多半是环境里同时装了多个 Python,换 python3 -m tkinter 再试一次。
完整代码:约 100 行
import random
import tkinter as tk
W, H = 480, 620
BW, BH = 96, 16
FPS = 16
class CatchGame:
def __init__(self, root):
self.root = root
self.cv = tk.Canvas(root, width=W, height=H, bg='#0b1026', highlightthickness=0)
self.cv.pack()
self.bx, self.by = W // 2 - BW // 2, H - 70
self.pad = self.cv.create_rectangle(self.bx, self.by, self.bx + BW, self.by + BH,
fill='#3ddc97', outline='')
self.drops = []
self.score = 0
self.lives = 3
self.level = 1
self.frames = 0
self.hud = self.cv.create_text(14, 12, anchor='nw', fill='#c9d1ff',
font=('Consolas', 15), text='')
root.bind('<Left>', self.left)
root.bind('<Right>', self.right)
self.cv.bind('<Motion>', self.follow)
self.refresh()
self.tick()
def left(self, _):
self.slide(-26)
def right(self, _):
self.slide(26)
def slide(self, d):
self.bx = max(0, min(W - BW, self.bx + d))
self.cv.coords(self.pad, self.bx, self.by, self.bx + BW, self.by + BH)
def follow(self, e):
self.bx = max(0, min(W - BW, e.x - BW // 2))
self.cv.coords(self.pad, self.bx, self.by, self.bx + BW, self.by + BH)
def refresh(self):
bar = '★' * self.lives
self.cv.itemconfig(self.hud, text='分数 %d 生命 %s 等级 %d' % (self.score, bar, self.level))
def spawn(self):
x = random.randint(10, W - 40)
r = random.choice([7, 9, 11])
color = random.choice(['#ffd166', '#