pygame入门教程-绘制篇

1. 基础绘制

直线

line(surface, color, start_pos, end_pos) -> Rect
line(surface, color, start_pos, end_pos, width=1) -> Rect

连续的多条线

lines(surface, color, closed, points) -> Rect
lines(surface, color, closed, points, width=1) -> Rect

circle(surface, color, center, radius) -> Rect
circle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect

多边形

polygon(surface, color, points) -> Rect
polygon(surface, color, points, width=0) -> Rect

2. 五子棋

在这里插入图片描述

五子棋很简单,先绘制网格线,然后绘制圆就行了

import pygame
import time

pygame.init()
WIDTH,HEIGHT=600,600
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("这是一个给我们画画用的窗口")

clock = pygame.time.Clock()

nrows,ncols=10,10
dx = WIDTH // nrows
dy = HEIGHT // ncols
radius = dx // 4

going = True
while going:
    for event in pygame.event.get():  # 遍历事件
        if event.type == pygame.QUIT:  # 退出事件
            going=False

    pygame.draw.circle(screen,(255,0,0),(dx*2,dy*2), radius)
    pygame.draw.circle(screen,(255,0,0),(dx*5,dy*4), radius)

    for i in range(1, nrows): # 绘制横线
        pygame.draw.line(screen,(255,0,0),(0+dx,i*dy),(WIDTH-dx, i*dy))
    
    for j in range(1, ncols): # 绘制纵线
        pygame.draw.line(screen,(255,0,0),(j*dx,0+dy),(j*dx, HEIGHT-dy))


    pygame.display.update()
    clock.tick(10)
pygame.quit()

加入鼠标点击事件,点击左键就落子,即绘制一个圆

    for event in pygame.event.get():  # 遍历事件
        if event.type == pygame.QUIT:  # 退出事件
            going=False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x,y=event.pos # 获取当前鼠标的位置
            pygame.draw.circle(screen, (255, 255, 0), (x, y), radius)

由于是手动点击的,因此很难正好落在交叉点,可以判断点击位置距离哪个交叉点最近。我们直接算距离哪个位置近即可

    for event in pygame.event.get():  # 遍历事件
        if event.type == pygame.QUIT:  # 退出事件
            going=False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x,y=event.pos
            x = ((x + dx//2) // dx)*dx
            y = ((y + dy//2) // dy)*dy

            pygame.draw.circle(screen, (255, 255, 0), (x,y), radius)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值