当前位置:   article > 正文

【python知识】用 Tkinter实现“剪刀-石头-布”和“弹球游戏 ”_python中石头剪刀布带图片

python中石头剪刀布带图片

一、提要

        Tkinter是一个Python内置模块,它提供了一个简单易用的界面来创建GUI。

        在实现一些动态的画面、如游戏还是需要一些创新性思维的。在本文中,我们将使用 Tkinter 探索 Python GUI 编程。我们将介绍 Tkinter 的基础知识,并演示如何使用 Tkinter 创建一个简单的 GUI 应用程序。

二、Tkinter的基础介绍

        Tkinter是一个Python内置模块,它提供了一个简单易用的界面来创建GUI

        Tkinter 提供了一组可用于创建 GUI 的小部件。小部件是提供特定功能(如按钮、标签或输入字段)的图形元素。小部件可以排列在窗口中以创建 GUI。

创建 Tkinter GUI 的基本步骤是:

  1. 导入 Tkinter 模块
  2. 创建窗口
  3. 向窗口添加微件
  4. 配置微件
  5. 向微件添加功能
  6. 启动主事件循环

下面是使用 Tkinter 创建窗口的简单示例:

  1. import tkinter as tk
  2. window = tk.Tk()
  3. window.mainloop()

三、剪刀石头布游戏

        如果您想了解有关 Tkinter 的更多信息,我会在本文末尾放置一个链接。所以,我想和Tk一起做点什么。我最终做了石头剪刀布,我想和你分享。让我们看一下代码和结果。

        代码不长。它拥有这款游戏所需的所有东西。首先,我们制作可以玩游戏的屏幕。

  1. # Import Required Library
  2. from tkinter import *
  3. import random
  4. # Create Object
  5. root = Tk()
  6. # Set geometry
  7. root.geometry("300x300")
  8. # Set title
  9. root.title("Rock Paper Scissor Game")

        接下来,我为计算机分配值,因为在游戏过程中,您将与计算机竞争。

  1. # Computer Value
  2. computer_value = {
  3. "0": "Rock",
  4. "1": "Paper",
  5. "2": "Scissor"
  6. }

        然后,我做了一些功能。根据玩家的选择,计算机或玩家获胜。因此,如果玩家选择石头,并且函数也选择石头,他们就会平局。当然,这也适用于剪刀对剪刀。如果你不知道这个游戏,中间有一个简短的解释:

  • 石头>剪刀
  • 剪刀>纸
  • >石头

这部分提供匹配结果。

  1. # Reset The Game
  2. def reset_game():
  3. b1["state"] = "active"
  4. b2["state"] = "active"
  5. b3["state"] = "active"
  6. l1.config(text="Player ")
  7. l3.config(text="Computer")
  8. l4.config(text="")
  9. # Disable the Button
  10. def button_disable():
  11. b1["state"] = "disable"
  12. b2["state"] = "disable"
  13. b3["state"] = "disable"
  14. # If player selected rock
  15. def isrock():
  16. c_v = computer_value[str(random.randint(0, 2))]
  17. if c_v == "Rock":
  18. match_result = "Match Draw"
  19. elif c_v == "Scissor":
  20. match_result = "Player Win"
  21. else:
  22. match_result = "Computer Win"
  23. l4.config(text=match_result)
  24. l1.config(text="Rock ")
  25. l3.config(text=c_v)
  26. button_disable()
  27. # If player selected paper
  28. def ispaper():
  29. c_v = computer_value[str(random.randint(0, 2))]
  30. if c_v == "Paper":
  31. match_result = "Match Draw"
  32. elif c_v == "Scissor":
  33. match_result = "Computer Win"
  34. else:
  35. match_result = "Player Win"
  36. l4.config(text=match_result)
  37. l1.config(text="Paper ")
  38. l3.config(text=c_v)
  39. button_disable()
  40. # If player selected scissor
  41. def isscissor():
  42. c_v = computer_value[str(random.randint(0, 2))]
  43. if c_v == "Rock":
  44. match_result = "Computer Win"
  45. elif c_v == "Scissor":
  46. match_result = "Match Draw"
  47. else:
  48. match_result = "Player Win"
  49. l4.config(text=match_result)
  50. l1.config(text="Scissor ")
  51. l3.config(text=c_v)
  52. button_disable()

        代码的最后一部分,将所有内容打包在一起并编写最后的细节,以便它能够工作并完成代码。这包括在石头、纸或剪刀之间进行选择的按钮。还需要制作文本。

  1. # Add Labels, Frames and Button
  2. Label(root,
  3. text="Rock Paper Scissor",
  4. font="normal 20 bold",
  5. fg="blue").pack(pady=20)
  6. frame = Frame(root)
  7. frame.pack()
  8. l1 = Label(frame,
  9. text="Player ",
  10. font=10)
  11. l2 = Label(frame,
  12. text="VS ",
  13. font="normal 10 bold")
  14. l3 = Label(frame, text="Computer", font=10)
  15. l1.pack(side=LEFT)
  16. l2.pack(side=LEFT)
  17. l3.pack()
  18. l4 = Label(root,
  19. text="",
  20. font="normal 20 bold",
  21. bg="white",
  22. width=15,
  23. borderwidth=2,
  24. relief="solid")
  25. l4.pack(pady=20)
  26. frame1 = Frame(root)
  27. frame1.pack()
  28. b1 = Button(frame1, text="Rock",
  29. font=10, width=7,
  30. command=isrock)
  31. b2 = Button(frame1, text="Paper ",
  32. font=10, width=7,
  33. command=ispaper)
  34. b3 = Button(frame1, text="Scissor",
  35. font=10, width=7,
  36. command=isscissor)
  37. b1.pack(side=LEFT, padx=10)
  38. b2.pack(side=LEFT, padx=10)
  39. b3.pack(padx=10)
  40. Button(root, text="Reset Game",
  41. font=10, fg="red",
  42. bg="black", command=reset_game).pack(pady=20)
  43. # Execute Tkinter
  44. root.mainloop()

四、更复杂游戏--弹球游戏  

4.1 窗口布局类实现

        窗口和外观,首先是最外层Frame的设定,请看代码:

  1. from tkinter import *
  2. import random
  3. import time
  4. # Creating the window:
  5. window = Tk()
  6. window.title("Bounce")
  7. window.geometry('600x600')
  8. window.resizable(False, False)

        这里对窗口一系列设定:

窗口语句功能
window = Tk()创建最外层主窗口
window.title("Bounce")设标题
window.geometry('600x600')设窗口高度、宽度
window.resizable(False, False)设定窗口固定大小

4.2 建立画布对象

        画布是刻画动画功能的对象,画布需要放置在桌面,不可独立存在。因此,桌面就是画布的承载对象。因此,画布有一系列初始化函数,请看下面代码:

  1. window = Tk()
  2. # Creating the canvas containing the game:
  3. canvas = Canvas(window, width = 450, height = 450, bg = "black")
  4. canvas.pack(padx = 50, pady= 50)
  5. score = canvas.create_text(10, 20, fill = "white")
  6. window.update()

4.3 建立小球对象

4.3.1 小球对象类

        小球相关的物体是:画布、球拍;即小球在画布内游动,小球被球拍打击而折返。

        因此,小球对象初始化需要两个外界物体,画布、球拍。 

  1. class Ball:
  2.     def __init__(self, canvas1, paddle1, color):

4.3.2 小球绘制

        小球是椭圆绘制函数,原型如下:

id = C.create_oval(x0, y0, x1, y1, option, ...)

  1. self.canvas.move(self.id, 190, 160)
  2. starting_direction = [-3, -2, -1, 0, 1, 2, 3]
  3. random.shuffle(starting_direction)
  4. self.x = starting_direction[0]
  5. self.y = -3
  6. self.canvas_height = self.canvas.winfo_height()
  7. self.canvas_width = self.canvas.winfo_width()
小球内初始化代码意义
        self.canvas.move(self.id, 190, 160)将小球移动到画布的位置。
        starting_direction = [-3, -2, -1, 0, 1, 2, 3]小球移动方向【横、竖、斜】
        random.shuffle(starting_direction)混淆方向
        self.x = starting_direction[0]            选一个初始方向
        self.y = -3
        self.canvas_height = self.canvas.winfo_height()取出画布的高、宽,用以判别小球移动范围
        self.canvas_width = self.canvas.winfo_width()

 def hit_paddle(self, ballcoords):  球拍击球处理

 def draw(self):   随小球位置重画
        self.canvas.move(self.id, self.x, self.y)

4.3.3 小球数据的合理设计 

        小球数据因该分成两种:显式数据、隐含数据;显式数据针对画布而言,隐式数据针对小球运动,方向、位置变化等而设定。

4.4 全部程序代码

        在以上游戏调试完成后,我们实现一个更复杂的动态任务。实现弹球游戏,通过<--和-->件移动平板接球,下文是tkinter的应用实例:

  1. from tkinter import *
  2. import random
  3. import time
  4. # Creating the window:
  5. window = Tk()
  6. window.title("Bounce")
  7. window.geometry('600x600')
  8. window.resizable(False, False)
  9. # Creating the canvas containing the game:
  10. canvas = Canvas(window, width = 450, height = 450, bg = "black")
  11. canvas.pack(padx = 50, pady= 50)
  12. score = canvas.create_text(10, 20, fill = "white")
  13. window.update()
  14. class Ball:
  15. def __init__(self, canvas1, paddle1, color):
  16. self.canvas = canvas1
  17. self.paddle = paddle1
  18. self.id = canvas1.create_oval(10, 10, 25, 25, fill = color) # The starting point of the ball
  19. self.canvas.move(self.id, 190, 160)
  20. starting_direction = [-3, -2, -1, 0, 1, 2, 3]
  21. random.shuffle(starting_direction)
  22. self.x = starting_direction[0]
  23. self.y = -3
  24. self.canvas_height = self.canvas.winfo_height()
  25. self.canvas_width = self.canvas.winfo_width()
  26. # Detecting the collision between the ball and the paddle:
  27. def hit_paddle(self, ballcoords):
  28. paddle_pos = self.canvas.coords(self.paddle.id)
  29. if ballcoords[0] <= paddle_pos[2] and ballcoords[2] >= paddle_pos[0]:
  30. if paddle_pos[3] >= ballcoords[3] >= paddle_pos[1]:
  31. return True
  32. return False
  33. # Detecting the collision between the the ball and the canvas sides:
  34. def draw(self):
  35. self.canvas.move(self.id, self.x, self.y)
  36. ballcoords = self.canvas.coords(self.id)
  37. if ballcoords[1] <= 0:
  38. self.y = 3
  39. if ballcoords[3] >= self.canvas_height:
  40. self.y = 0
  41. self.x = 0
  42. self.canvas.create_text(225, 150, text = "Game Over!", font = ("Arial", 16), fill = "white")
  43. if ballcoords[0] <= 0:
  44. self.x = 3
  45. if ballcoords[2] >= self.canvas_width:
  46. self.x = -3
  47. if self.hit_paddle(ballcoords):
  48. self.y = -3
  49. class Paddle:
  50. def __init__(self, canvas1, color):
  51. self.canvas1 = canvas
  52. self.id = canvas.create_rectangle(0, 0, 100, 10, fill = color)
  53. self.canvas1.move(self.id, 180, 350)
  54. self.x = 0
  55. self.y = 0
  56. self.canvas1_width = canvas1.winfo_width()
  57. self.canvas1.bind_all("<Left>", self.left)
  58. self.canvas1.bind_all("<Right>", self.right)
  59. def draw(self):
  60. self.canvas1.move(self.id, self.x, 0)
  61. paddlecoords = self.canvas1.coords(self.id)
  62. if paddlecoords[0] <= 0:
  63. self.x = 0
  64. if paddlecoords[2] >= self.canvas1_width:
  65. self.x = 0
  66. def right(self, event):
  67. self.x = 3
  68. def left(self, event):
  69. self.x = -3
  70. paddle = Paddle(canvas, color = "white")
  71. ball = Ball(canvas, paddle, color = "red")
  72. # New code after here
  73. def handler():
  74. global run
  75. run = False
  76. window.protocol("WM_DELETE_WINDOW", handler)
  77. run = True
  78. while run:
  79. # New code before here
  80. ball.draw()
  81. paddle.draw()
  82. window.update_idletasks()
  83. window.update()
  84. time.sleep(0.01)
  85. window.destroy() # should always destroy window before exit

五、程序结果 

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

闽ICP备14008679号