使用python和pygame在游戏板上创建游戏部件并将其放置

如何解决使用python和pygame在游戏板上创建游戏部件并将其放置

我只是一个初学者。我决定使用pygame制作棋盘游戏。我使用以下代码创建了开发板:

import pygame
import sys


pygame.init()
#define colour
white = (255,255,255)
black = (0,0)

red = (255,0)
green = (0,0)
blue = (0,255)
yellow= (255,0)



#opening window
screen = pygame.display.set_mode((800,600))

pygame.draw.rect(screen,red,(200,100,250,250),2)
pygame.draw.rect(screen,green,(150,75,350,300),(100,50,450,350),2)
#draw lines
#upper line
pygame.draw.line(screen,white,(325,50),100),3)
#lower line
pygame.draw.line(screen,400),3)
#left line
pygame.draw.line(screen,200),3)
#right line
pygame.draw.line(screen,(450,(550,3)

#updateing window
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    pygame.display.update()

现在,我想添加两个具有两种不同颜色的游戏作品,在每个角和线的交点处分别为黑色和红色。我该怎么办?

解决方法

每当您发现自己重复使用数字块重复行时,例如您对矩形函数的调用-考虑一下如何将数字存储在某种列表,元组或数据结构中可以简化代码。

例如:

pygame.draw.rect(screen,red,(200,100,250,250),2)
pygame.draw.rect(screen,green,(150,75,350,300),(100,50,450,350),2)

可能会变成:

board_rects = [  ( 200,red ),( 150,300,green ),( 100,red ) ]
for rect in board_rects:
    x_pos,y_pos  = rect[0],rect[1]
    width,height = rect[2],rect[3]
    colour        = rect[4]
    pygame.draw.rect( screen,colour,( x_pos,y_pos,width,height ),2 )

这显然是更多的代码,但是它更简单,因为只有一个调用可以绘制所有矩形。如果说,矩形的数量随难度级别的增加而增加,仅需向board-rects添加另一个数据元组,就没有逻辑上的改变。

类似地:

board_lines = [ ( 325,325,100 ),( 325,400 ),200,200 ),( 450,550,200 ) ]
for line in board_lines:
    line_from = ( line[0],line[1] )
    line_to   = ( line[2],line[3] )
    pygame.draw.line( screen,white,line_from,line_to,3 )

现在,板的矩形和直线都存储在数据结构中。因此,可以遍历列表执行其他测试和操作。 现在我们有了数据结构中的所有点和线,我们可以在它们上进行交叉点测试:

for line in board_lines:
    for rect in board_rects:
        rect = rect[ 0: -1 ] # trim off the colour
        intersection_points = lineRectIntersectionPoints( line,rect )
        for p in intersection_points:
            pygame.draw.circle( screen,blue,p,10 )  # Draw a circle at the point

newer version of rename

确定线与矩形的交点的一种方法是将矩形视为4条线的集合,并分别确定给定线的board with circles at points。当然,如果线是平行的,它们不会相交(它们确实会相交,但是无限地),因此我们也必须检查一下。最后,我们不在乎线是否在屏幕外相交,这也被认为是不相交的。

这给了我们令人讨厌的交集功能,但实际上只是一堆简单的几何计算相互关联:

def lineRectIntersectionPoints( line,rect ):
    """ Get the list of points where the line and rect
        intersect,The result may be zero,one or two points.

        BUG: This function fails when the line and the side
             of the rectangle overlap """

    def linesAreParallel( x1,y1,x2,y2,x3,y3,x4,y4 ):
        """ Return True if the given lines (x1,y1)-(x2,y2) and
            (x3,y3)-(x4,y4) are parallel """
        return (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)) == 0)

    def intersectionPoint( x1,y4 ):
        """ Return the point where the lines through (x1,y2)
            and (x3,y4) cross.  This may not be on-screen  """
        #Use determinant method,as per
        #Ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
        Px = ((((x1*y2)-(y1*x2))*(x3 - x4)) - ((x1-x2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
        Py = ((((x1*y2)-(y1*x2))*(y3 - y4)) - ((y1-y2)*((x3*y4)-(y3*x4)))) / (((x1-x2)*(y3-y4)) - ((y1-y2)*(x3-x4)))
        return Px,Py

    ### Begin the intersection tests
    result = []                                 # empty list for result-set
    line_x1,line_y1,line_x2,line_y2 = line   # split into components
    pos_x,pos_y,height = rect

    ### Convert the rectangle into 4 lines
    rect_lines = [ ( pos_x,pos_x+width,pos_y ),( pos_x,pos_y+height,pos_y+height ),# top & bottom
                   ( pos_x,pos_x,( pos_x+width,pos_y+height ) ] # left & right

    ### intersect each rect-side with the given line
    for r in rect_lines:
        rx1,ry1,rx2,ry2 = r
        if ( not linesAreParallel( line_x1,line_y2,rx1,ry2 ) ):    # not parallel
            pX,pY = intersectionPoint( line_x1,ry2 )  # so intersecting somewhere
            # Lines intersect,but is it on-screen?
            if ( pX >= 0 and pY >= 0 and pX < WINDOW_WIDTH and pY < WINDOW_HEIGHT ):          # yes! on-screen
                result.append( ( round(pX),round(pY) ) )                                     # keep it
                if ( len( result ) == 2 ):
                    break   # Once we've found 2 intersection points,that's it

    return result

将它们放在一起:

import pygame
import sys

WINDOW_WIDTH = 800
WINDOW_HEIGHT= 600

#define colour
white = (255,255,255)
black = (0,0)

red = (255,0)
green = (0,0)
blue = (121,202,255)
yellow= (255,0)


def lineRectIntersectionPoints( line,Py

    ### Begin the intersection tests
    result = []
    line_x1,pos_y+height ) ] # left & right

    ### intersect each rect-side with the line
    for r in rect_lines:
        rx1,that's it

    return result



#opening window
pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))

#pygame.draw.rect(screen,2)
#pygame.draw.rect(screen,2)
##draw lines
##upper line
#pygame.draw.line(screen,(325,50),100),3)
##lower line
#pygame.draw.line(screen,400),3)
##left line
#pygame.draw.line(screen,200),3)
##right line
#pygame.draw.line(screen,(450,(550,3)

board_rects = [  ( 200,2 )

board_lines = [ ( 325,3)    

for line in board_lines:
    for rect in board_rects:
        rect = rect[ 0: -1 ] # trim off the colour
        intersection_points = lineRectIntersectionPoints( line,10 )  # Draw a circle at the intersection point

#updateing window
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    pygame.display.update()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-