当前位置:   article > 正文

随想录(python编写的计算器和贪吃蛇游戏)_python写一个随想录

python写一个随想录

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】


    python除了用来开发server、web之外,一般还可以用来开发客户端,特别是用来做一些demo原型还是比较合适的。这里找了一份python编写的计算器,供大家参考一下。代码出处在

  1. import Tkinter as tk
  2. calc = tk.Tk()
  3. calc.title("CrappyCalc")
  4. buttons = [
  5. '7', '8', '9', '*', 'C',
  6. '4', '5', '6', '/', 'Neg',
  7. '1', '2', '3', '-', '$',
  8. '0', '.', '=', '+', '@' ]
  9. # set up GUI
  10. row = 1
  11. col = 0
  12. for i in buttons:
  13. button_style = 'raised'
  14. action = lambda x = i: click_event(x)
  15. tk.Button(calc, text = i, width = 7, height = 7, relief = button_style, command = action) \
  16. .grid(row = row, column = col, sticky = 'nesw', )
  17. col += 1
  18. if col > 4:
  19. col = 0
  20. row += 1
  21. display = tk.Entry(calc, width = 40, bg = "white")
  22. display.grid(row = 0, column = 0, columnspan = 5)
  23. def click_event(key):
  24. # = -> calculate results
  25. if key == '=':
  26. # safeguard against integer division
  27. if '/' in display.get() and '.' not in display.get():
  28. display.insert(tk.END, ".0")
  29. # attempt to evaluate results
  30. try:
  31. result = eval(display.get())
  32. display.insert(tk.END, " = " + str(result))
  33. except:
  34. display.insert(tk.END, " Error, use only valid chars")
  35. # C -> clear display
  36. elif key == 'C':
  37. display.delete(0, tk.END)
  38. # $ -> clear display
  39. elif key == '$':
  40. display.delete(0, tk.END)
  41. display.insert(tk.END, "$$$$C.$R.$E.$A.$M.$$$$")
  42. # @ -> clear display
  43. elif key == '@':
  44. display.delete(0, tk.END)
  45. display.insert(tk.END, "wwwwwwwwwwwwwwwwebsite")
  46. # neg -> negate term
  47. elif key == 'neg':
  48. if '=' in display.get():
  49. display.delete(0, tk.END)
  50. try:
  51. if display.get()[0] == '-':
  52. display.delete(0)
  53. else:
  54. display.insert(0, '-')
  55. except IndexError:
  56. pass
  57. # clear display and start new input
  58. else:
  59. if '=' in display.get():
  60. display.delete(0, tk.END)
  61. display.insert(tk.END, key)
  62. # RUNTIME
  63. calc.mainloop()

    大家可以在此基础上做一些改写,比如如果没有eval函数,怎么用状态机来进行设计呢?


2017.1.4 补充:

    发现网上有一份python编写的贪吃蛇代码,也不错,大家可以借此多学习学习,原来地址在

  1. # -*- coding:utf-8 -*-
  2. from turtle import Vec2D
  3. import Tkinter as tk, random, itertools
  4. kGridWidth, kGridHeight, kGridPixels = 15, 15, 20 # 网格尺寸、网格像素数
  5. kCanvasWidth, kCanvasHeight = kGridWidth * kGridPixels, kGridHeight * kGridPixels # 画布尺寸
  6. kDirs = {'Up': Vec2D(0, -1), 'Left': Vec2D(-1, 0), 'Down': Vec2D(0, 1), 'Right': Vec2D(1, 0)} # 方向
  7. kSceneStart, kScenePlay, kSceneOver = 0, 1, 2 # 场景
  8. kUpdateDelay = 500 # 更新间隔(ms)
  9. class SnakeGame:
  10. def __init__(self):
  11. self.root = tk.Tk()
  12. self.canvas = tk.Canvas(self.root, width=kCanvasWidth, height=kCanvasHeight, bg='gray')
  13. self.canvas.pack()
  14. self.root.bind('<KeyPress>', self.update)
  15. self.valid_pos = set(map(lambda t: Vec2D(*t), itertools.product(range(kGridWidth), range(kGridHeight)))) # 有效网格坐标集合
  16. self.rand_pos = lambda w, h: Vec2D(random.randint(0, w - 1), random.randint(0, h - 1)) # 生成随机网格坐标
  17. self.food = (None, self.canvas.create_oval(0, 0, 0, 0, fill='green')) # 食物:(网格坐标, 图形对象)
  18. self.snake_dir = None # 蛇头方向:Vec2D(x, y)
  19. self.snake_bodys = [] # 蛇身:[(网格坐标,图形对象), ...]
  20. self.scene = kSceneStart # 场景编号
  21. self.score = 0 # 分数
  22. self.update_funcs = [self.update_gamestart, self.update_gameplay, self.update_gameover] # 场景更新函数
  23. self.next_update = self.root.after(kUpdateDelay, self.update) # 延迟执行下一次更新
  24. def next_food(self): # 生成下一个食物
  25. while True:
  26. pos = self.rand_pos(kGridWidth, kGridHeight)
  27. if pos not in map(lambda b: b[0], self.snake_bodys): # 判定是否与蛇身冲突
  28. self.canvas.coords(self.food[1], (pos[0] * kGridPixels + 2, pos[1] * kGridPixels + 2,
  29. pos[0] * kGridPixels + kGridPixels, pos[1] * kGridPixels + kGridPixels))
  30. self.food = (pos, self.food[1])
  31. return
  32. def move(self): # 移动蛇头
  33. new_pos = self.snake_bodys[0][0] + self.snake_dir
  34. if new_pos not in self.valid_pos or new_pos in map(lambda b: b[0], self.snake_bodys[:-1]): # 测试新的蛇头位置是否有效
  35. return False
  36. if new_pos == self.food[0]: # 吃到食物时
  37. self.snake_bodys.insert(0, (new_pos, self.canvas.create_oval(new_pos[0] * kGridPixels + 2, new_pos[1] * kGridPixels + 2,
  38. new_pos[0] * kGridPixels + kGridPixels, new_pos[1] * kGridPixels + kGridPixels,
  39. fill='red', tags='SnakeBodys')))
  40. self.next_food()
  41. self.score += 1
  42. else:
  43. self.canvas.coords(self.snake_bodys[-1][1], (new_pos[0] * kGridPixels + 2, new_pos[1] * kGridPixels + 2,
  44. new_pos[0] * kGridPixels + kGridPixels, new_pos[1] * kGridPixels + kGridPixels))
  45. self.snake_bodys.insert(0, (new_pos, self.snake_bodys.pop()[1])) # 直接将蛇尾移动至新蛇头
  46. return True
  47. def update(self, event=None):
  48. self.update_funcs[self.scene](event) # 执行当前场景的更新函数
  49. def update_gamestart(self, event): # 游戏开始场景
  50. if event and event.keysym == 'Return': # 按下回车
  51. self.canvas.delete('GameStartString')
  52. self.snake_dir = random.choice(kDirs.values())
  53. head = self.rand_pos(kGridWidth, kGridHeight)
  54. self.snake_bodys = [(head, self.canvas.create_oval(head[0] * kGridPixels + 2, head[1] * kGridPixels + 2,
  55. head[0] * kGridPixels + kGridPixels, head[1] * kGridPixels + kGridPixels,
  56. fill='red', tags='SnakeBodys'))]
  57. self.next_food()
  58. self.scene = kScenePlay
  59. self.next_update = self.root.after(kUpdateDelay, self.update)
  60. elif not self.canvas.find_withtag('GameStartString'): # 画面初始化
  61. self.canvas.create_text((kCanvasWidth / 2, kCanvasHeight / 6 * 2), text='Welcome to the simple snake game.', tags='GameStartString')
  62. self.canvas.create_text((kCanvasWidth / 2, kCanvasHeight / 6 * 3), text='Move the snake with <Up, Left, Down, Right>.', tags='GameStartString')
  63. self.canvas.create_text((kCanvasWidth / 2, kCanvasHeight / 6 * 4), text='Please press <Enter> to start.', tags='GameStartString')
  64. def update_gameplay(self, event): # 游戏进行场景
  65. try:
  66. if event and event.keysym in kDirs and kDirs[event.keysym] + self.snake_dir != Vec2D(0, 0): # 按下方向键且与当前方向不相反时
  67. self.root.after_cancel(self.next_update)
  68. self.snake_dir = kDirs[event.keysym]
  69. if not self.move():
  70. raise # 懒
  71. elif not event: # 自动更新时
  72. if not self.move():
  73. raise
  74. else: # 忽略其他按键
  75. return
  76. except: # 死亡
  77. self.canvas.delete('SnakeBodys')
  78. self.canvas.coords(self.food[1], (0, 0, 0, 0))
  79. self.scene = kSceneOver
  80. self.next_update = self.root.after(kUpdateDelay, self.update) # 延迟执行下一次更新
  81. def update_gameover(self, event): # 游戏结束场景
  82. if event and event.keysym == 'Escape': # 按下Esc
  83. self.canvas.delete('GameOverString')
  84. self.scene = kSceneStart
  85. self.next_update = self.root.after(kUpdateDelay, self.update)
  86. elif not self.canvas.find_withtag('GameOverString'): # 画面初始化
  87. self.canvas.create_text((kCanvasWidth / 2, kCanvasHeight / 5 * 2), text='Your score is: %d' % self.score, tags='GameOverString')
  88. self.canvas.create_text((kCanvasWidth / 2, kCanvasHeight / 5 * 3), text='Please press <Esc> to restart.', tags='GameOverString')
  89. if __name__ == '__main__':
  90. SnakeGame().root.mainloop()



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/618880
推荐阅读
相关标签
  

闽ICP备14008679号