日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python pygame实战1: 小球碰撞balls collision

發布時間:2024/8/1 python 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python pygame实战1: 小球碰撞balls collision 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

學了點基礎, 開始實戰吧, 先做個小球碰撞的小游戲:

import pygame
import random
import numpy as np

SCREEN_WIDTH =500
SCREEN_HEIGHT = 400 ?
FPS = 50
? ? ? ?
class circle(pygame.sprite.Sprite): ? ? ? ?
? ? def __init__(self, screen,r=20): ?
? ? ? ? pygame.sprite.Sprite.__init__(self) ?
? ? ? ? self.r=r
? ? ? ? self.screen=screen
? ? ? ? self.color=(random.randrange(50,255),random.randrange(50,255),random.randrange(50,255))
? ? ? ? self.image = pygame.Surface((2*r,2*r))
? ? ? ? self.image.set_colorkey((20,120,20))
? ? ? ? self.image.fill((20,120,20))
? ? ? ? self.rect=self.image.get_rect()
? ? ? ? self.rect.x = random.randrange(SCREEN_WIDTH-self.rect.width)?
? ? ? ? self.rect.y = random.randrange(SCREEN_HEIGHT-self.rect.height)
? ? ? ? pygame.draw.circle(self.image,self.color,(self.r,self.r),self.r)?
? ? ? ? self.radius=r ?#this makes ".collide_circle" to detect using circle,rather than rect
? ? ? ? self.speedx = random.randrange(1,5)
? ? ? ? self.speedy = random.randrange(1,5)?
? ? def update(self):
? ? ? ? self.rect.move_ip(self.speedx, self.speedy)
? ? ? ? self.v=np.array([self.speedx,self.speedy])
? ? ? ? if (self.rect.y<=0 or self.rect.y>=SCREEN_HEIGHT-self.rect.height):
? ? ? ? ? ? self.speedy=-self.speedy
? ? ? ? if self.rect.x<=0 or self.rect.x>=SCREEN_WIDTH-self.rect.width:
? ? ? ? ? ? self.speedx=-self.speedx
? ? ? ? self.screen.blit(self.image, self.rect)
? ? ? ? ? ??
? ? ?
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH , SCREEN_HEIGHT))
c1=circle(screen,30)
balls=pygame.sprite.Group()
for i in range(10):
? ? c=circle(screen)
? ? balls.add(c)
run=True
while pygame.sprite.spritecollideany(c1,balls): #避免一開始就碰撞在一起
? ? c1=circle(screen,30)
while run:
? ? for event in pygame.event.get():
? ? ? ? if event.type == pygame.QUIT:
? ? ? ? ? ? run=False
? ? c=pygame.sprite.spritecollideany(c1,balls)
? ? if c: ? ?
? ? ? ? #exchange the speed of c1, and c2
? ? ? ? c1.speedy,c.speedy=c.speedy,c1.speedy
? ? ? ? c1.speedx,c.speedx=c.speedx,c1.speedx
? ? ? ? screen.fill((220, 0, 220)) ? ? ? ? ? ? ? ? ??
? ? else:
? ? ? ? screen.fill((0,0,0))
? ? c1.update()
? ? balls.update()
? ? pygame.display.update()
? ? clock.tick(FPS)

總結

以上是生活随笔為你收集整理的python pygame实战1: 小球碰撞balls collision的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。