1. 打开浏览器
利用webbrowser 模块的 open()函数可以启动一个新浏览器,打开指定的 URL。
python">import webbrowser
webbrowser.open('http://inventwithpython.com/')
2. 猜数字游戏
python"># -*- coding: utf-8 -*-
# This is a guess the number game.
import randomsecretNumber = 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. 贪吃蛇游戏
python"># -*- coding: utf-8 -*-
import curses
import randomdef 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] orsnake[0][1] in [0, sw-1] orsnake[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. 井子棋
python"># -*- coding: utf-8 -*-
import curses
import randomdef 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 Truereturn Falsedef 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() # 运行主函数