世界杯太精彩了,带大家用Python做个足球游戏,边玩游戏边看比赛

Python零基础快速制作足球游戏(附源代码)

前言

卡塔尔世界杯正是进行得火热,十六强队伍已经诞生,后面就是越来越紧张的争夺八强的淘汰赛。目前爆冷的赛果让球迷一度情绪失落,比如:日本2-1战胜西班牙,韩国2-1战胜葡萄牙。

这正是足球的魅力所在,结果只会给更努力的一方,过去的成绩在比赛不在起决定性的作用,亚洲强队越战越强,期望国足能在下届世界杯有出场的机会。

没能看到国足在这届世界杯的球场奔驰,只能用Python制作世界杯足球游戏,让国足可以在游戏里的世界杯上场。国足能否在足球游戏里拿到大力神杯,请看到文末,结果让人惊喜,接下是对源代码简单讲述。

一、Python环境说明

详细的Python安装教程:Python基础(二):不同系统安装Python3_Lansonli的博客-CSDN博客

Python版本:3.9.13

主要模块:

pygame

安装步骤:

python -m pip install --upgrade pip

pip install pygame

二、游戏程序说明

1、游戏开始界面

首先游戏需要一个开始界面,为了方便大家操作,设置成了按任意键就可以开始游戏。

def myinit():
    screen = pygame.display.set_mode((769,563))
    g1 = pygame.image.load("g1.jpg").convert()
    g2 = pygame.image.load("hh.png").convert()
    t = 0
    timer = pygame.time.Clock()
    while(1):
        timer.tick(30)
        ticks = pygame.time.get_ticks();
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        screen.blit(g1,(0,0))
        t+= 1
        print(t)
        if t > 66:
            break;
        pygame.display.update()
    while(1):
        timer.tick(30)
        ticks = pygame.time.get_ticks();
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONUP:
                mouse_up = event.button
                mouse_up_x,mouse_up_y = event.pos
                if mouse_up_x > 245 and mouse_up_x < 469 and mouse_up_y> 368 and mouse_up_y < 470:
                    return
        screen.blit(g2,(0,0))
        pygame.display.update()

游戏开始界面效果如下:

2、人物移动规则说明,可支持两位玩家

人物移动规则:

  • 守门员:就在球门边上来回走;
  • 负责上半场的球员:在上半场出现球的时候就往球的位置移动,如果捕获到了球,则往对方球门移动并随机射门,否则随机移动;
  • 负责下半场的球员:在下半场出现球的时候就往球的位置移动,如果捕获到了球,则往对方球门移动并随机射门,否则随机移动;
  • 负责全场的球员:往球的位置移动,如果捕获到了球,则往对方球门移动并随机射门。

操作说明:

  • 一号玩家,WASD + T 射门
  • 二号玩家,方向键 + K 射门

核心代码如下:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from pygame.locals import *
from MyLibrary import *
filename = 'p2.png'
filename2 = 'p1.png'
size_of_player = (32,47.5)
size_of_action = 4
size_of_playground = (1200,850)
dict_ = {(0,0):0,(-1, 0): 3, (1, 0): 0, (0, 1): 2, (0, -1): 1, (-1, 1): 2, (-1, -1): 1, (1, -1): 1, (1, 1): 2};
def player2_AI(myball,player,game_over,player_moving,Reference):
    x_bias,y_bias,X,Y = Reference
    TEMP = [0,0]
    player.direction = list(player.direction)
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]: sys.exit()
    if keys[K_UP]: TEMP[0] = -1
    if keys[K_RIGHT]: TEMP[1] = 1
    if keys[K_DOWN]: TEMP[0] = 1
    if keys[K_LEFT]: TEMP[1] = -1
    if keys[K_k] and myball.player == player: myball.kick_off()
    if ([0,0] == TEMP):
        player_moving = False
    else:
        player_moving = True
    if player_moving:
        player.direction = TEMP 
    which_column = dict_[tuple(player.direction)]

    if not game_over:
    # 根据角色的不同方向,使用不同的动画帧
        player.first_frame = which_column * player.columns
        player.last_frame = player.first_frame + player.columns - 1
        if player.frame < player.first_frame:
            player.frame = player.first_frame
        # print(player.direction)
        if player.X >=0  and player.X <= 70 and player.Y >=255 and player.Y <=260:
            if player.direction[0] == 1:
                player.direction[0] = 0
        if player.X >=70 and player.X <=75 and player.Y >=260 and player.Y <=497:
            if player.direction[1] == -1:
                player.direction[1] =0
        if player.X >=0  and player.X <= 70 and player.Y >=497 and player.Y <=502:
            if player.direction[0] == -1:
                player.direction[0] = 0

        if player.X >=1080 and player.X <= 1200 and player.Y >=255 and player.Y <260:
            if player.direction[0] == 1:
                player.direction[0] = 0
        if player.X > 1075 and player.X <= 1080 and player.Y >=260 and player.Y <  503:
            if player.direction[1] == 1:
                player.direction[1] =0
        if player.X >=1080 and player.X <= 1200 and player.Y >=503 and player.Y <=507:
            if player.direction[0] == -1:
                player.direction[0] = 0
        if not player_moving:
            # 当停止按键(即人物停止移动的时候),停止更新动画帧
            player.frame = player.last_frame= player.first_frame 
            player.moving = False;
        else:
            player.moving = True;
            player.velocity.x = player.direction[1] * 2
            player.velocity.y = player.direction[0]*   2
            player.velocity.x *= 1
            player.velocity.y *= 1

        if player_moving:
            X += player.velocity.x
            Y += player.velocity.y
            if X < 0: X = 0
            if X > size_of_playground[0] - 48: X = size_of_playground[0] - 48
            if Y < 0: Y = 0
            if Y > size_of_playground[1] - 88: Y = size_of_playground[1] - 88
            player.X = X + x_bias
            player.Y = Y + y_bias
    # Reference = x_bias,y_bias,X,Y
    Reference[0] = x_bias
    Reference[1]= y_bias
    Reference[2] = X
    Reference[3] = Y
            
def player1_AI(myball,player,game_over,player_moving,Reference):
    x_bias,y_bias,X,Y = Reference
    TEMP = [0,0]
    player.direction = list(player.direction)
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]: sys.exit()
    if keys[K_w]: TEMP[0] = -1
    if keys[K_d]: TEMP[1] = 1
    if keys[K_s]: TEMP[0] = 1
    if keys[K_a]: TEMP[1] = -1
    if keys[K_t] and myball.player == player: myball.kick_off()
    if ([0,0] == TEMP):
        player_moving = False
    else:
        player_moving = True
    if player_moving:
        player.direction = TEMP 
    which_column = dict_[tuple(player.direction)]
        # print(player.direction)
        # print(which_column)
    if not game_over:
    # 根据角色的不同方向,使用不同的动画帧
        player.first_frame = which_column * player.columns
        player.last_frame = player.first_frame + player.columns - 1
        if player.frame < player.first_frame:
            player.frame = player.first_frame

        if player.X >=0  and player.X <= 70 and player.Y >=255 and player.Y <=260:
            if player.direction[0] == 1:
                player.direction[0] = 0
        if player.X >=70 and player.X <=75 and player.Y >=260 and player.Y <=497:
            if player.direction[1] == -1:
                player.direction[1] =0
        if player.X >=0  and player.X <= 70 and player.Y >=497 and player.Y <=502:
            if player.direction[0] == -1:
                player.direction[0] = 0


        if player.X >=1080 and player.X <= 1200 and player.Y >=255 and player.Y <260:
            if player.direction[0] == 1:
                player.direction[0] = 0
        if player.X > 1075 and player.X <= 1080 and player.Y >=260 and player.Y <503:
            if player.direction[1] == 1:
                player.direction[1] =0
        if player.X >=1080 and player.X <= 1200 and player.Y >=503 and player.Y <507:
            if player.direction[0] == -1:
                player.direction[0] = 0
        if not player_moving:
            # 当停止按键(即人物停止移动的时候),停止更新动画帧
            player.frame = player.first_frame = player.last_frame
            player.moving = False;
        else:
            player.moving = True;
            player.velocity.x = player.direction[1] * 2
            player.velocity.y = player.direction[0]*  2
            player.velocity.x *= 1
            player.velocity.y *= 1

        if player_moving:
            X += player.velocity.x
            Y += player.velocity.y
            if X < 0: X = 0
            if X > size_of_playground[0] - 48: X = size_of_playground[0] - 48
            if Y < 0: Y = 0
            if Y > size_of_playground[1] - 88: Y = size_of_playground[1] - 88
            player.X = X + x_bias
            player.Y = Y + y_bias

    Reference[0] = x_bias
    Reference[1]= y_bias
    Reference[2] = X
    Reference[3] = Y

3、足球规则

状态说明:

  • 被球员捕获,跟着球员走;
  • 被球员踢出去之后根据球员踢的方向和设定的初速度进行减速运动,如果碰到边界则反方向弹出。

核心代码:

from __future__ import unicode_literals
import sys, time, random, math, pygame
from pygame.locals import *
from math import pow
class ball(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image_list = []
        self.image = None
        self.frame = 0
        self.old_frame = 0
        self.first_frame = 0
        self.last_frame = 2
        self.direction = list([0,0])
        self.speed = 0;
        self.fetch = False;
        self.f = 1.7
        self.last_time = 0;
        self.player = None
        self.cal = 0
    def _getx(self): return self.rect.x
    def _setx(self,value):self.rect.x = value
    X = property(_getx,_setx)

    #Y property
    def _gety(self):return self.rect.y
    def _sety(self,value):self.rect.y = value
    Y = property(_gety,_sety)

    #position property
    def _getpos(self): return self.rect.topleft
    def _setpos(self,pos): self.rect.topleft = pos
    position = property(_getpos,_setpos)
    def load(self):
        filename = 'ball1.png','ball2.png','ball3.png'
        for x in filename:
        	ball = pygame.image.load(x).convert_alpha()
        	self.image_list.append(ball)
        self.frame = 0;
        self.old_frame = 2;
        self.image = self.image_list[0];
        self.frame_height = self.image_list[0].get_rect().height
        self.frame_width = self.image_list[0].get_rect().width
        self.rect = Rect(0,0,self.frame_width,self.frame_height);
    def update(self,current_time,rate =30):
        if self.fetch and self.player.moving:
            self.speed = (self.player.velocity.x **2 + self.player.velocity.y **2)**(1/2)
        if self.speed == 0 or (self.fetch and self.player.moving == False):
            return
        if current_time > self.last_time + (4-self.speed//4)*20:
        	self.frame += 1
        	self.frame %= 3
        	self.last_time = current_time
        if self.frame != self.old_frame:
        	self.image = self.image_list[self.frame]
        	self.old_frame = self.frame
        
    def run(self):
        self.speed -= self.f*0.05;
        self.speed = max(0,self.speed)
        if(self.direction==[0,0]):return;
        # print(self.direction)
        # print(self.speed)
        self.X += ((self.direction[0]*self.speed)/pow((self.direction[1]**2 + self.direction[0]**2),(1/2)))
        self.Y += ((self.direction[1]*self.speed)/pow((self.direction[0]**2 + self.direction[1]**2),(1/2)))
    def fetched(self,player_):
        self.fetch = True;
        if player_ != None:
            self.player = player_
        player = self.player
        if(player.direction[1] >0):
        	self.X = self.player.X + self.player.frame_width*3/4
        else :
        	self.X = self.player.X - self.player.frame_width/3
        self.Y = self.player.Y + self.player.frame_height -self.frame_height;
    def kick_off(self):
        self.speed = 12
        self.direction[0] = self.player.direction[1]
        self.direction[1]  =self.player.direction[0]
        self.player = None
        self.fetch =False
        self.cal = 0
    def check_bound(self,width,height):
        temp = self.X,self.Y
        if self.X < 0:
            self.X =0
            self.direction[0] = abs(self.direction[0])
        if self.Y < 0:
            self.Y = 0
            self.direction[1] = abs(self.direction[1])
        if self.X >width-34:
            self.X= width-34
            self.direction[0] = -1*abs(self.direction[0])
        if self.Y > height-14:
            self.Y = height-14;
            self.direction[1] = -1*abs(self.direction[1])
        if self.X >=0 and self.X <72 and self.Y >300 - 17 and self.Y <315 - 17:
            self.Y = 300-17
            self.direction[1] = -1*abs(self.direction[1])
        if self.X >1110 and self.X <1200 and self.Y >300 - 17 and self.Y <315 - 17:
            self.Y = 300-17
            self.direction[1] = -1*abs(self.direction[1])
        if self.X >=0 and self.X <72 and self.Y >495 and self.Y <510:
            self.Y = 510 
            self.direction[1] = -1*abs(self.direction[1])
        if self.X >1110 and self.X <1200 and self.Y >495 and self.Y <510:
            self.Y = 510
            self.direction[1] = -1*abs(self.direction[1])
        if((self.X,self.Y) != temp):
            self.speed *= 0.8

4、主方法调取

整合调取上面三大核心代码,游戏运行只需操作该方法文件即可。

注意:全部的源代码会文末链接上,拿来就可以直接运行无需修改。

核心代码:

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("世界杯足球游戏-大数据联盟")
    font = pygame.font.Font(None, 36)
    myinit()
    timer = pygame.time.Clock()
    n1 = 0
    n2 =0
    screen = pygame.display.set_mode((1200, 800))
    for x in range(10000):
        t = begin_a_game(n1,n2);
        if t == 1:
            n1 +=1
        else:
            n2 += 1

三、游戏运行效果与比赛结果

1、游戏开始界面

2、下届世界杯预测比赛结果

世界杯足球游戏娱乐为主,切勿用它模拟真实比赛结果,以免造成不必要的误判。

文末惊喜:

通过模拟比赛,希望国足下一届世界杯能以3:1的比分战胜日本队。

游戏源代码下载:

https://download.csdn.net/download/xiaoweite1/87242585

原文地址:https://cloud.tencent.com/developer/article/2186068

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

相关推荐


Python中的函数(二) 在上一篇文章中提到了Python中函数的定义和使用,在这篇文章里我们来讨论下关于函数的一些更深的话题。在学习C语言函数的时候,遇到的问题主要有形参实参的区别、参数的传递和改变、变量的作用域。同样在Python中,关于对函数的理解和使用也存在这些问题。下面来逐一讲解。一.函
Python中的字符串 可能大多数人在学习C语言的时候,最先接触的数据类型就是字符串,因为大多教程都是以&quot;Hello world&quot;这个程序作为入门程序,这个程序中要打印的&quot;Hello world&quot;就是字符串。如果你做过自然语言处理方面的研究,并且用Python
Python 面向对象编程(一) 虽然Python是解释性语言,但是它是面向对象的,能够进行对象编程。下面就来了解一下如何在Python中进行对象编程。一.如何定义一个类 在进行python面向对象编程之前,先来了解几个术语:类,类对象,实例对象,属性,函数和方法。 类是对现实世界中一些事物的封装,
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定义和使用方法,这只体现了面向对象编程的三大特点之一:封装。下面就来了解一下另外两大特征:继承和多态。 在Python中,如果需要的话,可以让一个类去继承一个类,被继承的类称为父类或者超类、也可以称作基类,继承的类称为子类。并且Pytho
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非常熟悉,无论在哪门编程语言当中,函数(当然在某些语言里称作方法,意义是相同的)都扮演着至关重要的角色。今天就来了解一下Python中的函数用法。一.函数的定义 在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明
在windows下如何快速搭建web.py开发框架 用Python进行web开发的话有很多框架供选择,比如最出名的Django,tornado等,除了这些框架之外,有一个轻量级的框架使用起来也是非常方便和顺手,就是web.py。它由一名黑客所创建,但是不幸的是这位创建者于2013年自杀了。据说现在由
将Sublime Text 2搭建成一个好用的IDE 说起编辑器,可能大部分人要推荐的是Vim和Emacs,本人用过Vim,功能确实强大,但是不是很习惯,之前一直有朋友推荐SUblime Text 2这款编辑器,然后这段时间就试了一下,就深深地喜欢上这款编辑器了...
Python中的模块 有过C语言编程经验的朋友都知道在C语言中如果要引用sqrt这个函数,必须用语句&quot;#include&lt;math.h&gt;&quot;引入math.h这个头文件,否则是无法正常进行调用的。那么在Python中,如果要引用一些内置的函数,该怎么处理呢?在Python中
Python的基础语法 在对Python有了基础的认识之后,下面来了解一下Python的基础语法,看看它和C语言、java之间的基础语法差异。一.变量、表达式和语句 Python中的语句也称作命令,比如print &quot;hello python&quot;这就是一条语句。 表达式,顾名思义,是
Eclipse+PyDevʽjango+Mysql搭建Python web开发环境 Python的web框架有很多,目前主流的有Django、Tornado、Web.py等,最流行的要属Django了,也是被大家最看好的框架之一。下面就来讲讲如何搭建Django的开发环境。一.准备工作 需要下载的
在windows下安装配置Ulipad 今天推荐一款轻便的文本编辑器Ulipad,用来写一些小的Python脚本非常方便。 Ulipad下载地址: https://github.com/limodou/ulipad http://files.cnblogs.com/dolphin0520/u...
Python中的函数(三) 在前面两篇文章中已经探讨了函数的一些相关用法,下面一起来了解一下函数参数类型的问题。在C语言中,调用函数时必须依照函数定义时的参数个数以及类型来传递参数,否则将会发生错误,这个是严格进行规定的。然而在Python中函数参数定义和传递的方式相比而言就灵活多了。一.函数参数的
在Notepad++中搭配Python开发环境 Python在最近几年一度成为最流行的语言之一,不仅仅是因为它简洁明了,更在于它的功能之强大。它不仅能够完成一般脚本语言所能做的事情,还能很方便快捷地进行大规模的项目开发。在学习Python之前我们来看一下Python的历史由来,&quot;Pytho
Python中的条件选择和循环语句 同C语言、Java一样,Python中也存在条件选择和循环语句,其风格和C语言、java的很类似,但是在写法和用法上还是有一些区别。今天就让我们一起来了解一下。一.条件选择语句 Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如
关于raw_input( )和sys.stdin.readline( )的区别 之前一直认为用raw_input( )和sys.stdin.readline( )来获取输入的效果完全相同,但是最近在写程序时有类似这样一段代码:import sysline = sys.stdin.readline()
初识Python 跟学习所有的编程语言一样,首先得了解这门语言的编程风格和最基础的语法。下面就让我们一起来了解一下Python的编程风格。1.逻辑行与物理行 在Python中有逻辑行和物理行这个概念,物理行是指在编辑器中实际看到的一行,逻辑行是指一条Python语句。在Python中提倡一个物理行只
当我们的代码是有访问网络相关的操作时,比如http请求或者访问远程数据库,经常可能会发生一些错误,有些错误可能重新去发送请求就会成功,本文分析常见可能需要重试的场景,并最后给出python代码实现。
1.经典迭代器 2.将Sentence中的__iter__改成生成器函数 改成生成器后用法不变,但更加简洁。 3.惰性实现 当列表比较大,占内存较大时,我们可以采用惰性实现,每次只读取一个元素到内存。 或者使用更简洁的生成器表达式 4.yield from itertools模块含有大量生成器函数可
本文介绍简单介绍socket的常用函数,并以python-kafka中的源码socketpair为例,来讲解python socket的运用
python实践中经常出现编码相关的异常,大多网上找资料而没有理解原理,导致一次次重复错误。本文对常用Unicode、UTF-8、GB2312编码的原理进行介绍,接着介绍了python字符类型unicode和str以及常见编解码错误UnicodeEncodeError和UnicodeDEcodeEr