pygame物体碰撞

news/2024/11/18 17:22:29/文章来源:https://www.cnblogs.com/xuxiaobo/p/18373954

代码:

#coding=utf-8import os,sys,re,time
import pygame
import random
import math
from win32api import GetSystemMetrics
from tkinter import messageboxpygame.init()
pygame.display.set_caption("我的游戏")percent = 0.6
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
window_width = int(screen_width*percent)
window_height = int(screen_height*percent)dt = 0
clock = pygame.time.Clock()screen = pygame.display.set_mode((window_width, window_height))#停止处理输入法事件
pygame.key.stop_text_input()font_path = os.path.join(os.path.dirname(sys.argv[0]), 'simsun.ttc')
font = pygame.font.Font(font_path, 20)rect_width = 50
rect_height = 50
rect_position = ((window_width-rect_width)//2, (window_height-rect_height)//2, rect_width, rect_height)
rect_position_x_min = 0
rect_position_x_max = window_width - rect_width
rect_position_y_min = 0
rect_position_y_max = window_height - rect_heightdef getCircle(i = 0):circle_width = random.randint(25, 35)min_x = circle_widthmax_x = window_width - circle_widthmin_y = circle_widthmax_y = window_height - circle_widthcircle_position = [random.randint(min_x, max_x), random.randint(min_y, max_y)]circle_color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))circle_direct = random.randint(0, 360)circle_speed = random.randint(200, 800)position_range = {'min_x' : min_x, 'max_x' : max_x, 'min_y' : min_y, 'max_y' : max_y}circle_text = font.render(str(i), 1, (255-circle_color[0], 255-circle_color[1], 255-circle_color[2]))return {'width' : circle_width, 'position' : circle_position, 'color' : circle_color, 'speed' : circle_speed,'position_range' : position_range,'direct' : circle_direct,'newdirect' : circle_direct,'name' : '第%s个球' % i,'text' : circle_text,}def calculate_distance(point1, point2):x1, y1 = point1x2, y2 = point2ret = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)return ret#print(calculate_distance([1,2], [2,2]))
#sys.exit(0)

circleList = [] 
for i in range(0, 10):circleInfo = getCircle(i+1)circleList.append(circleInfo)running = True
while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falsekeys_pressed = pygame.key.get_pressed()#ESC键if keys_pressed[pygame.K_ESCAPE]:running = Falserect_position_value = list(rect_position)if keys_pressed[pygame.K_a]:rect_position_value[0] = rect_position_value[0] - 300 * dtif keys_pressed[pygame.K_d]:rect_position_value[0] = rect_position_value[0] + 300 * dtif keys_pressed[pygame.K_w]:rect_position_value[1] = rect_position_value[1] - 300 * dtif keys_pressed[pygame.K_s]:rect_position_value[1] = rect_position_value[1] + 300 * dtif rect_position_value[0] < rect_position_x_min:rect_position_value[0] = rect_position_x_minif rect_position_value[0] > rect_position_x_max:rect_position_value[0] = rect_position_x_maxif rect_position_value[1] < rect_position_y_min:rect_position_value[1] = rect_position_y_minif rect_position_value[1] > rect_position_y_max:rect_position_value[1] = rect_position_y_maxrect_position = tuple(rect_position_value)rect1 = pygame.Rect(rect_position_value[0], rect_position_value[1], rect_position_value[2], rect_position_value[3])for i,circleInfo in enumerate(circleList):name = circleInfo['name']width = circleInfo['width']speed = circleInfo['speed']direct = circleInfo['direct']newdirect = circleInfo['newdirect']position = circleInfo['position']oldposition = positioncolor = circleInfo['color']position_range = circleInfo['position_range']text = circleInfo['text']min_x = position_range['min_x']max_x = position_range['max_x']min_y = position_range['min_y']max_y = position_range['max_y']truespeed_x = math.cos(direct) * speed * dttruespeed_y = math.sin(direct) * speed * dtif newdirect > 0 and newdirect < 90:position[0] += truespeed_xposition[1] += truespeed_yif position[0] > max_x and position[1] < min_y:if abs(position[0] - max_x) > abs(position[1] - min_y):newdirect = 180 - newdirectelif abs(position[0] - max_x) < abs(position[1] - min_y):newdirect = 360 - newdirectelif random.randint(0, 1):newdirect = 180 - newdirectelse:newdirect = 360 - newdirectelif position[0] > max_x:newdirect = 180 - newdirectelif position[1] < min_y:newdirect = 360 - newdirectelse:passelif newdirect > 90 and newdirect < 180:position[0] -= truespeed_xposition[1] += truespeed_yif position[0] < min_x and position[1] < min_y:if abs(position[0] - min_x) > abs(position[1] - min_y):newdirect = 180 - newdirectelif abs(position[0] - min_x) < abs(position[1] - min_y):newdirect = 360 - newdirectelif random.randint(0, 1):newdirect = 180 - newdirectelse:newdirect = 360 - newdirectelif position[0] < min_x:newdirect = 180 - newdirectelif position[1] < min_y:newdirect = 360 - newdirectelse:passelif newdirect > 180 and newdirect < 270:position[0] -= truespeed_xposition[1] -= truespeed_yif position[0] < min_x and position[1] > max_y:if abs(position[0] - min_x) > abs(position[1] - max_y):newdirect = 540 - newdirectelif abs(position[0] - min_x) < abs(position[1] - max_y):newdirect = 360 - newdirectelif random.randint(0, 1):newdirect = 540 - newdirectelse:newdirect = 360 - newdirectelif position[0] < min_x:newdirect = 540 - newdirectelif position[1] > max_y:newdirect = 360 - newdirectelse:passelif newdirect > 270 and newdirect < 360:position[0] += truespeed_xposition[1] -= truespeed_yif position[0] > max_x and position[1] > max_y:if abs(position[0] - max_x) > abs(position[1] - max_y):newdirect = 540 - newdirectelif abs(position[0] - max_x) < abs(position[1] - max_y):newdirect = 360 - newdirectelif random.randint(0, 1):newdirect = 540 - newdirectelse:newdirect = 360 - newdirectelif position[0] > max_x:newdirect = 540 - newdirectelif position[1] > max_y:newdirect = 360 - newdirectelse:passelif newdirect == 0 or newdirect == 360:newdirect = 180elif newdirect == 90:newdirect = 270elif newdirect == 180:newdirect = 0elif newdirect == 270:newdirect = 90if position[0] <= min_x:position[0] = min_x#color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))if position[0] >= max_x:position[0] = max_x#color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))if position[1] <= min_y:position[1] = min_y#color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))if position[1] >= max_y:position[1] = max_y#color = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))
            circleInfo['position'] = positioncircleInfo['newdirect'] = newdirectcircleInfo['color'] = colorcircleInfo['speed'] = speedcircleList[i] = circleInfopzFlag = Falsefor i,circleInfo in enumerate(circleList):circle1 = pygame.Rect(circleInfo['position'][0], circleInfo['position'][1], circleInfo['width'], circleInfo['width'])if rect1.colliderect(circle1):pzFlag = Truebreakif pzFlag:screen.fill("white")else:screen.fill("purple")pygame.draw.rect(screen, 'red', rect_position_value)for i,circleInfo in enumerate(circleList):pygame.draw.circle(screen, circleInfo['color'], circleInfo['position'], circleInfo['width'])#更新显示
    pygame.display.flip()#pygame.display.update()if pzFlag:messagebox.askokcancel ("提示"," 碰到了")dt = clock.tick(60) / 600pygame.quit()

 

效果:

 

 

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NSSCTF [HNCTF 2022 Week1]Interesting_include

NSSCTF [HNCTF 2022 Week1]Interesting_include<?php //WEB手要懂得搜索 //flag in ./flag.phpif(isset($_GET[filter])){$file = $_GET[filter];if(!preg_match("/flag/i", $file)){die("error");}include($file); }else{highlight_file(__FILE__); }…

02-HTMLJS相关练习

1、使用 html 写一个网页,要求满足以下条件: (1)网页中含有任意一张图片,图片路径使用绝对路径(这里绝对路径无法识别故使用相对路径),鼠标悬停在图片时出现“马哥教育”文本,且点击图片可跳转至马哥教育官方页面 (2)网页中包含账号、密码登录,且账号提前定义好是 …

织梦dedecms判断文章是否为推荐文章

{dede:arclist row=10 typeid=typeid titlelen=36 runphp=yes} {dede:loop value=$dls}{if preg_match(/c/, $fields[flag])}<strong>推荐文章: </strong>{/if}<a href="[field:arcurl]" title="[field:title]">[field:title]</a>…

织梦dedecms判断缩略图是否存在

{dede:field name=litpic runphp=yes} if(!empty(@me)) {<img src="@me" alt="缩略图" /> } else {<img src="/images/no-image.png" alt="默认图片" /> } [/dede:field]扫码添加技术【解决问题】专注中小企业网站建设、网…

织梦dedecms判断子菜单是否存在

{dede:channeltype typeid=typeid runphp=yes} if(@list != ) {<ul class="submenu">{dede:loop value=@list}<li><a href="[url]">[@typename]</a></li>{/dede:loop}</ul> } else {"没有子菜单" } {/dede:…

使用SiliconCloud快速体验SimpleRAG(手把手教程)

使用SiliconCloud快速体验SimpleRAG(手把手教程)SiliconCloud介绍 SiliconCloud 基于优秀的开源基础模型,提供高性价比的 GenAI 服务。 不同于多数大模型云服务平台只提供自家大模型 API,SiliconCloud上架了包括 Qwen、DeepSeek、GLM、Yi、Mistral、LLaMA 3、SDXL、Instant…

axis参数讲解

axis在python使用中非常常见,比如numpy、pandas等使用情景。但是笔者几乎每次都会忘记axis = 0和axis = 1各自对应的是行还是列,最终决定写下笔记以防再次忘记。axis的作用:指明以行为单位进行处理数据,还是以列为单位处理数据。下图就已经很清晰地展示了axis = 0和axis = …

电磁介质 知识梳理

新概念物理:电磁介质知识梳理1.电介质 \[\def\oiint{{\bigcirc}\kern-11.5pt{\int}\kern-6.5pt{\int}} \def\oiiint{{\bigcirc}\kern-12.3pt{\int}\kern-7pt{\int}\kern-7pt{\int}} \]1.1 极化的微观机制 在一类电介质中,当外电场不存在时,电介质分子的正负电荷中心是重合的…

2024年关于短信轰炸机原理研究并实现的流程 (290021243

偶然看到gitHub上面有短信轰炸机源码,于是产生了研究的想法。 经过研究源码发现是通过抓包进行第三方网站抓包并且收集,最终进行post/get请求。携带header和token进行第三方网站模拟请求。 于是在mac上面下载了fiddler 进行代理配置 开放了本机ip下的8888商品,用手机同时访问…

从企业管理到智慧城市:数据可视化大屏的多领域应用详解(AxureRP原型多行业案例演示)

前言: 在现代商业环境中,广泛应用于政府、金融、互联网、制造业等多个领域,数据驱动决策已成为企业提升竞争力的关键要素之一。无论是智慧城市的管理中心,还是企业的数据中心,都能见到其身影。数据可视化大屏,作为一种高效直观的数据展示工具,能够将复杂的数据转化为易于…

HuggingFace初体验

起因 StableDiffusion3的开源项目大致了解了一下项目的介绍,创新点之类的 在old environment基础上,配置了一下new environment(pip安装diffusers库、transformers库) 解决了一下torch和torchvision的版本冲突问题(询问chatGPT)HuggingFace下载需要登陆的模型官网注册,梯…

Tarjan 之 割点 学习笔记

首先,要求割点,我们需要知道割点是什么 割点: 是指在无向连通图中,如果删除某个顶点后,图的连通分量增加,则称该顶点为割点 好,知道了这个,那我们怎么去求他呢? Tarjan 大神给出了一种依然基于时间戳的算法 图片来源:董晓算法割点的求法大概就是这样的 所以细节还是见…