python爬虫初体验(五)—— 边学边玩小游戏
1. 打开浏览器
利用webbrowser 模块的 open()函数可以启动一个新浏览器,打开指定的 URL。
import webbrowser
webbrowser.open('http://inventwithpython.com/')
2. 猜数字游戏
# -*- coding: utf-8 -*-
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too hight.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job!You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
3. 贪吃蛇游戏
# -*- coding: utf-8 -*-
import curses
import random
def main(stdscr):
# 隐藏光标
curses.curs_set(0)
# 设置非阻塞输入模式
stdscr.nodelay(1)
# 设置刷新间隔为100毫秒
stdscr.timeout(100)
# 获取屏幕的高度和宽度
sh, sw = stdscr.getmaxyx()
# 初始化蛇的位置,初始时蛇只有一个单元格
snake = [(sh//2, sw//2)]
# 初始方向为向右
direction = curses.KEY_RIGHT
# 随机生成食物的位置
food = (random.randint(1, sh-2), random.randint(1, sw-2))
# 在屏幕上显示食物
stdscr.addch(food[0], food[1], '*')
while True:
# 获取用户输入的按键
key = stdscr.getch()
# 根据用户输入更新方向
if key in [curses.KEY_RIGHT, curses.KEY_LEFT, curses.KEY_UP, curses.KEY_DOWN]:
direction = key
# 获取蛇头的位置
head = snake[0]
# 根据当前方向计算新的蛇头位置
if direction == curses.KEY_RIGHT:
new_head = (head[0], head[1] + 1)
elif direction == curses.KEY_LEFT:
new_head = (head[0], head[1] - 1)
elif direction == curses.KEY_UP:
new_head = (head[0] - 1, head[1])
elif direction == curses.KEY_DOWN:
new_head = (head[0] + 1, head[1])
# 将新的蛇头插入到蛇的头部
snake.insert(0, new_head)
# 如果新的蛇头位置与食物位置相同,则生成新的食物
if snake[0] == food:
food = (random.randint(1, sh-2), random.randint(1, sw-2))
stdscr.addch(food[0], food[1], '*')
else:
# 如果没有吃到食物,移除蛇尾
tail = snake.pop()
stdscr.addch(tail[0], tail[1], ' ')
# 检查游戏是否结束
if (snake[0][0] in [0, sh-1] or
snake[0][1] in [0, sw-1] or
snake[0] in snake[1:]):
# 显示游戏结束信息
stdscr.addstr(sh//2, sw//2 - 5, "Game Over!")
stdscr.refresh()
# 暂停2秒
curses.napms(2000)
break
# 在屏幕上显示新的蛇头
stdscr.addch(snake[0][0], snake[0][1], '#')
# 使用curses.wrapper来初始化和清理curses环境
curses.wrapper(main)
4. 井子棋
# -*- coding: utf-8 -*-
import curses
import random
def print_board(board):
"""
打印当前的游戏棋盘。
:param board: 3x3 的二维列表,表示当前的棋盘状态。
"""
for row in board:
print " | ".join(row) # 使用 '|' 分隔符打印每一行
print "-" * 5 # 打印分隔线
def check_winner(board, player):
"""
检查当前玩家是否赢了。
:param board: 3x3 的二维列表,表示当前的棋盘状态。
:param player: 当前玩家的符号 ('X' 或 'O')。
:return: 如果当前玩家赢了,返回 True;否则返回 False。
"""
# 检查每一行是否有三个相同的符号
for row in board:
if all([cell == player for cell in row]):
return True
# 检查每一列是否有三个相同的符号
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
# 检查两条对角线是否有三个相同的符号
if all([board[i][i] == player for i in range(3)]) or all([board[i][2-i] == player for i in range(3)]):
return True
return False
def main():
"""
主函数,控制游戏的流程。
"""
# 初始化棋盘
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X' # 当前玩家
while True:
print_board(board) # 打印当前棋盘
# 获取用户输入的行和列
row = int(raw_input("Enter row (0, 1, 2): "))
col = int(raw_input("Enter column (0, 1, 2): "))
# 检查所选单元格是否已被占用
if board[row][col] != ' ':
print "Cell already occupied. Try again."
continue
# 更新棋盘
board[row][col] = current_player
# 检查当前玩家是否赢了
if check_winner(board, current_player):
print_board(board) # 再次打印棋盘
print "Player {} wins!".format(current_player)
break
# 检查是否平局
if all([cell != ' ' for row in board for cell in row]):
print_board(board) # 再次打印棋盘
print "It's a tie!"
break
# 切换玩家
current_player = 'O' if current_player == 'X' else 'X'
if __name__ == "__main__":
main() # 运行主函数