【Python实操】如何快速写一个乒乓球游戏?

news2024/9/25 7:27:08

文章目录

  • 前言
  • 一、 导入 turtle 和 Screen
  • 二、创建一个球
  • 3.创建一个 AI 挡板
  • 4.创建自己的挡板
  • 5.创建移动AI挡板的函数
  • 6.创建一个函数以移动你的挡板并用键盘控制它
  • 7.全部代码
  • 总结


前言

本文提供了一个 Python 实现的乒乓球游戏代码,你只需要将代码复制并粘贴到编辑器中即可。
你好,亲爱的 Python 爱好者,今天我想分享一下如何在 Python 中编写一个带有自定义机器人 AI 的乒乓球游戏。我们的挑战是制作两个用户,第一个用户是你,第二个用户是精准度达到 100% 的AI机器人。
在这里插入图片描述

一、 导入 turtle 和 Screen


# Step 1 import set up turtle and Screen
import turtle
import random
s = turtle.Screen()
s.title("Pong")
s.bgcolor("black")
s.setup(width=600, height=400)

二、创建一个球


# Step 2 Create ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 4
ball.dy = 4

3.创建一个 AI 挡板

代码如下(示例):


# Step 3 Create AI paddle
ai = turtle.Turtle()
ai.speed(0)
ai.shape("square")
ai.color("white")
ai.penup()
ai.goto(-250, 0)
ai.shapesize(stretch_wid=5, stretch_len=1)

4.创建自己的挡板


# Step 4 Create a paddle For You
you = turtle.Turtle()
you.speed(0)
you.shape("square")
you.color("white")
you.penup()
you.goto(250, 0)
you.shapesize(stretch_wid=5, stretch_len=1)

5.创建移动AI挡板的函数

# Step 5 Create Function to move AI paddle
def move_ai_paddle():
    y = ball.ycor()
    if y > 0:
        ai.sety(ai.ycor() + 2)
    else:
        ai.sety(ai.ycor() - 2)

6.创建一个函数以移动你的挡板并用键盘控制它


# Step 6 Create a Function to move the your paddle with up and down key
def paddle2_up():
    y = you.ycor()
    y += 20
    you.sety(y)

def paddle2_down():
    y = you.ycor()
    y -= 20
    you.sety(y)
# Your Paddle control it with key
s.listen()
s.onkeypress(paddle2_up, "Up")
s.onkeypress(paddle2_down, "Down")
Step 7 使用 while 循环开始游戏
# Step 7 Start the game with a while loop
while True:
    s.update()
    
    # Move the ball
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)
    
    # Check for collisions with the walls
    if ball.ycor() > 190 or ball.ycor() < -190:
        ball.dy *= -1
    
    # Move the robot paddle towards the ball
    if ball.ycor() > ai.ycor():
        ai.sety(ai.ycor() + 4)
    elif ball.ycor() < ai.ycor():
        ai.sety(ai.ycor() - 4)
    
           # Check for end game conditions
    if ball.xcor() > 300:
        turtle.textinput("Game End", "You Loss Pong Game With AI!")
        break
    if ball.xcor() < -300:
        turtle.textinput("Game End", "You Win Pong Game With AI!")
        break
    
    # Check for collisions with the robot paddle
    if (ball.xcor() < -240 and ball.xcor() > -250) and (ball.ycor() < ai.ycor() + 40 and ball.ycor() > ai.ycor() - 40):
        if random.random() < 0.9: # 90% chance of collision
            ball.dx *= -1
    
        # Check for collisions with the user paddle
    if (ball.xcor() > 240 and ball.xcor() < 250) and (ball.ycor() < you.ycor() + 40 and ball.ycor() > you.ycor() - 40):
        ball.dx *= -1

7.全部代码


# Step 1 import set up turtle and Screen
import turtle
import random
s = turtle.Screen()
s.title("Pong")
s.bgcolor("black")
s.setup(width=600, height=400)

# Step 2 Create ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 4
ball.dy = 4

# Step 3 Create AI paddle
ai = turtle.Turtle()
ai.speed(0)
ai.shape("square")
ai.color("white")
ai.penup()
ai.goto(-250, 0)
ai.shapesize(stretch_wid=5, stretch_len=1)

# Step 4 Create a paddle For You
you = turtle.Turtle()
you.speed(0)
you.shape("square")
you.color("white")
you.penup()
you.goto(250, 0)
you.shapesize(stretch_wid=5, stretch_len=1)

# Step 5 Create Function to move AI paddle
def move_ai_paddle():
    y = ball.ycor()
    if y > 0:
        ai.sety(ai.ycor() + 2)
    else:
        ai.sety(ai.ycor() - 2)

# Step 6 Create a Function to move the your paddle
def paddle2_up():
    y = you.ycor()
    y += 20
    you.sety(y)

def paddle2_down():
    y = you.ycor()
    y -= 20
    you.sety(y)
# Your Paddle control it with key
s.listen()
s.onkeypress(paddle2_up, "Up")
s.onkeypress(paddle2_down, "Down")

# Step 7 Start the game with a while loop
while True:
    s.update()
    
    # Move the ball
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)
    
    # Check for collisions with the walls
    if ball.ycor() > 190 or ball.ycor() < -190:
        ball.dy *= -1
    
    # Move the robot paddle towards the ball
    if ball.ycor() > ai.ycor():
        ai.sety(ai.ycor() + 4)
    elif ball.ycor() < ai.ycor():
        ai.sety(ai.ycor() - 4)
    
           # Check for end game conditions
    if ball.xcor() > 300:
        turtle.textinput("Game End", "You Loss Pong Game With AI!")
        break
    if ball.xcor() < -300:
        turtle.textinput("Game End", "You Win Pong Game With AI!")
        break
    
    # Check for collisions with the robot paddle
    if (ball.xcor() < -240 and ball.xcor() > -250) and (ball.ycor() < ai.ycor() + 40 and ball.ycor() > ai.ycor() - 40):
        if random.random() < 0.9: # 90% chance of collision
            ball.dx *= -1
    
        # Check for collisions with the user paddle
    if (ball.xcor() > 240 and ball.xcor() < 250) and (ball.ycor() < you.ycor() + 40 and ball.ycor() > you.ycor() - 40):
        ball.dx *= -1
 
turtle.exitonclick()

总结

以上就是今天要讲的内容,希望大家继续支持徐浪大讲堂

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/498081.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何防御流量攻击

随着互联网的发展&#xff0c;网络安全问题也日益突出。其中&#xff0c;流量攻击成为网络攻击的一种常见手段。那么流量攻击属于什么攻击&#xff0c;服务器防御流量攻击的方法有哪些呢?本文小编将为您一一解答。 一、流量攻击是什么? 流量攻击即DDoS攻击&#xff0c;全称为…

如何进行DNS优化

在互联网时代&#xff0c;网站的访问速度直接影响着用户体验和转化率。而DNS(Domain Name System)作为域名解析系统&#xff0c;负责将域名转换为IP地址&#xff0c;是网站访问速度的重要因素之一。因此&#xff0c;DNS优化成为了提升网站速度的重要手段之一。 DNS优化到底是什…

SpringMVC-RESTful

REST风格 1. REST简介1.1 REST介绍1.2 RESTful介绍1.3 注意事项 2. RESTful入门案例2.1 快速入门2.2 PathVariable介绍2.3 RequestBody、RequestParam、PathVariable区别和应用 3. REST快速开发【重点】3.1 代码中的问题3.2 Rest快速开发 4. 案例&#xff1a;基于RESTful页面数…

拿捏c语言循环

&#x1f4d5;博主介绍&#xff1a;目前大一正在学习c语言&#xff0c;数据结构&#xff0c;计算机网络。 c语言学习&#xff0c;是为了更好的学习其他的编程语言&#xff0c;C语言是母体语言&#xff0c;是人机交互接近底层的桥梁。 本章用循环去写一些题目。 让我们开启c语言…

Kubernetes系列---Kubernetes 理论知识 | 初识

Kubernetes系列---Kubernetes 理论知识 | 初识 1.K8s 是什么&#xff1f;2.K8s 特性3.小拓展&#xff08;业务升级&#xff09;4.K8s 集群架构与组件①架构拓扑图&#xff1a;②Master 组件③Node 组件 五 K8s 核心概念六 官方提供的三种部署方式 1.K8s 是什么&#xff1f; K…

springboot打包成jar包运行到服务器 java v 1.8

1.项目打包成jar包 1.1 1.2 2 jdk安装 2.1 jdk 官网 -> oracle 官方的jdk https://www.oracle.com/java/technologies/downloads/#java8 2.2 本地上传文件到服务器 2.3 配置安装 tar -zvxf jdk-8u131-linux-x64.tar.gz -->解压修改配置文件 source /etc/profile /…

Java 10 字符串

1.API 1.1API 概述 什么是API ​ API (Application Programming Interface) &#xff1a;应用程序编程接口 java 中的 API ​ 指的就是 JDK 中提供的各种功能的 Java 类&#xff0c;这些类将底层的实现封装了起来&#xff0c;我们不需要关心这些类是如何实现的&#xff0c;只…

C++好难(3):类和对象(中篇)

【本章目标】 类的6个默认成员函数构造函数析构函数拷贝构造函数赋值运算符重载const成员函数取地址及const取地址操作符重载 目录 【本章目标】 1.类的6个默认成员函数 2.构造函数 2.1概念 2.2构造函数的特性 特性一 特性二 特性三 特性四 特性五 特性六 特性七 …

Monkey Patching in Go

gomonkey 用来给函数打桩&#xff0c;这种使用一个新的方法实现来替换原来的实现逻辑&#xff0c;怎么看都觉得很神奇。举个例子&#xff0c;在单测中方法 json.Marshal 可以被 gomonkey 覆写成另一种逻辑实现&#xff0c;我准备从原理和使用的角度来看看 gomonkey。主要是来看…

LeetCode 第 344 场周赛

相当的惨烈&#xff0c;乱交 Q1 前后缀分解,用set统计不同元素的个数 class Solution {public:vector<int> distinctDifferenceArray(vector<int>& nums) {int n nums.size();vector<int> L(n 1, 0), R(n 1, 0); // 前缀不同数的个数set<int&g…

MLC LLM - 大模型本地部署解决方案

MLC LLM 是一种通用解决方案&#xff0c;它允许将任何语言模型本地部署在各种硬件后端和本地应用程序上&#xff0c;此外还提供了一个高效的框架&#xff0c;供每个人根据自己的用例进一步优化模型性能。 推荐&#xff1a;用 NSDT设计器 快速搭建可编程3D场景。 我们的使命是让…

【Python】使用Print函数制作旋转的动画

1. 引言 如果你想有效地学习Python&#xff0c;这篇文章可能不适合你。接下来的一切都可能是愚蠢、和浪费时间&#xff0c;但哪有怎么样&#xff0c;毕竟这玩意很有趣呀&#xff01; 2. 好玩的脚本 首先&#xff0c;我们来看两个好玩的Python脚本&#xff0c;如下&#xff1…

开关电源基础03:正激和反激开关电源拓扑(3)-反激拓扑

说在开头&#xff1a;关于不确定性原理 1927年2月&#xff0c;那个冬天对海森堡来说简直是一场噩梦&#xff0c;越来越多的人转向了薛定谔和他那该死的波动理论&#xff0c;把他的矩阵忘得一干二净&#xff1b;而最让他伤心和委屈的是&#xff0c;玻尔也转向了他的对立面&…

大规模并行处理架构Doris编译部署篇

目录 1 Doris编译1.1 使用 Docker 开发镜像编译&#xff08;推荐&#xff09;1.1.1 遇到的问题1.1.1 遇到的问题 1.2 直接编译&#xff08;CentOS/Ubuntu&#xff09;1.2.1 环境准备1.2.2 系统依赖&#xff08;一次性安装&#xff09;1.2.3 手动安装系统依赖1.2.3.1 CMake 3.11…

Linux驱动开发:SPI子系统

1、SPI简介 1.1 四根线 MISO&#xff1a;主设备数据输入&#xff0c;从设备数据输出。 MOSI&#xff1a;主设备数据输出&#xff0c;从设备数据输入。 SCLK&#xff1a;时钟信号&#xff0c;由主设备产生。 CS&#xff1a; 从设备片选信号&#xff0c;由主设备控制。 1.2…

《string类的使用介绍》

本文主要介绍string的常见的接口的使用 文章目录 一、什么是string类二、string类的使用1、string类对象的常见构造2、string类对象的容量操作3、string类对象的访问及遍历操作①operator[ ]的用法②迭代器③范围for 4、string类对象的修改操作①push_back②append③operator&a…

刷题笔记8| 344.反转字符串, 541. 反转字符串II, 剑指Offer 05.替换空格

344.反转字符串 编写一个函数&#xff0c;其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。 不要给另外的数组分配额外的空间&#xff0c;你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 输入&#xff1a;s ["h","e",…

索引—MySQL

文章目录 1.定义以及相关知识1.1定义1.2数据库保存数据的基本单位 2.MySQL中索引分类2.1B树和B树2.2主键索引&#xff08;聚簇索引&#xff09;2.3非聚簇索引2.4覆盖索引2.5复合索引&#xff08;联合索引&#xff09;2.6基于B树的索引2.7hash索引 1.定义以及相关知识 1.1定义 …

okio篇--总览

看源码第一步&#xff0c;先去看看官网对okio的介绍&#xff1a; Okio 首先第一段&#xff1a; okio对bytes&#xff0c;做了两种形式的封装&#xff1a;ByteString和Buffer。 其中ByteString&#xff0c;是针对字符类的数据&#xff0c;内部封装一个byte数组&#xff0c;封…

网络协议与攻击模拟-06-ICMP重定向

■0网络不可达 ■2协议不可达 类型4源抑制 类型5重定向 2、 ICMP 常见的报文 响应请求 使用 ping 请求&#xff08; type 0)响应&#xff08; type 8) 目标不可达 type 3 源抑制 源抑制则充当一个控制流量的角色&#xff0c;它通知主机减少数据报流量&#xff0c;由于 I…